auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void pausePartitions() { _logger.info("About to pause partitions."); Validate.isTrue(_consumer != null, "Consumer cannot be null when pausing partitions."); _pausedPartitionsUpdatedCount++; Set<TopicPartition> currentPausedPartitions = _consumer.paused(); Set<TopicPartition> currentAssignedPartitions = _consumer.assignment(); _logger.info("Current partition assignment for task is: {}, and paused partitions are: {}", _taskName, currentAssignedPartitions, currentPausedPartitions); Set<TopicPartition> partitionsToResume = getPartitionsToResume(currentPausedPartitions, _pausedSourcePartitions, _autoPausedSourcePartitions); if (!partitionsToResume.isEmpty()) { _logger.info("Partitions to resume for task are {}", _taskName, partitionsToResume); _consumer.resume(partitionsToResume); _logger.info("Resumed these partitions: {}", partitionsToResume); } else { _logger.debug("No partitions to resume for task {}", _taskName); } Set<TopicPartition> partitionsToPause = getPartitionsToPause(currentAssignedPartitions, currentPausedPartitions, _pausedSourcePartitions, _autoPausedSourcePartitions); if (!partitionsToPause.isEmpty()) { _logger.info("Partitions to pause for task are {}", _taskName, partitionsToPause); _consumer.pause(partitionsToPause); _logger.info("Paused these partitions: {}", partitionsToPause); } else { _logger.debug("No partitions to pause for task {}", _taskName); } _taskUpdates.remove(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); }

Target:
private void pausePartitions() { _logger.info("Checking for partitions to pause or resume."); Validate.isTrue(_consumer != null, "Consumer cannot be null when pausing partitions."); _pausedPartitionsConfigUpdateCount++; Set<TopicPartition> currentPausedPartitions = _consumer.paused(); Set<TopicPartition> currentAssignedPartitions = _consumer.assignment(); _logger.info("Current partition assignment for task is: {}, and paused partitions are: {}", _taskName, currentAssignedPartitions, currentPausedPartitions); _logger.info("Current auto-pause partition set is: {}", _autoPausedSourcePartitions); _consumer.resume(currentPausedPartitions); Set<TopicPartition> partitionsToPause = determinePartitionsToPause(currentAssignedPartitions, _pausedPartitionsConfig, _autoPausedSourcePartitions); _autoPausedSourcePartitions.retainAll(currentAssignedPartitions); if (!partitionsToPause.equals(currentPausedPartitions)) { _logger.info("There were new partitions to pause. New partitions pause list is: {}", partitionsToPause); } _logger.info("Full pause list is: {}", partitionsToPause); _consumer.pause(partitionsToPause); }
Source:
protected synchronized void processGetBlockHeaders(GetBlockHeadersMessage msg) { Iterator<BlockHeader> headersIterator = blockchain.getIteratorOfHeadersStartFrom( msg.getBlockIdentifier(), msg.getSkipBlocks(), min(msg.getMaxHeaders(), MAX_HASHES_TO_SEND), msg.isReverse() ); BlockHeadersMessage response = new BlockHeadersMessage(headersIterator); sendMessage(response); }

Target:
protected synchronized void processGetBlockHeaders(GetBlockHeadersMessage msg) { Iterator<BlockHeader> headersIterator = blockchain.getIteratorOfHeadersStartFrom( msg.getBlockIdentifier(), msg.getSkipBlocks(), min(msg.getMaxHeaders(), MAX_HASHES_TO_SEND), msg.isReverse() ); List<BlockHeader> blockHeaders = new ArrayList<>(); while (headersIterator.hasNext()) { blockHeaders.add(headersIterator.next()); } BlockHeadersMessage response = new BlockHeadersMessage(blockHeaders); sendMessage(response); }
Source:
public ActionResult execute() throws EntityNotFoundException { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String studentsInfo = getNonNullRequestParamValue(Const.ParamsNames.STUDENTS_ENROLLMENT_INFO); try { List<StudentAttributes>[] students = enrollAndProcessResultForDisplay(studentsInfo, courseId); EnrollResults dataFormat = new EnrollResults(getInstructorCourseEnrollResult(students)); return new JsonResult(dataFormat); } catch (EntityDoesNotExistException e) { throw new EntityNotFoundException(new EntityDoesNotExistException(e)); } catch (EnrollException | InvalidParametersException e) { return new JsonResult(e.getMessage(), HttpStatus.SC_BAD_REQUEST); } catch (EntityAlreadyExistsException e) { log.severe("Entity already exists exception occurred when updating student: " + e.getMessage()); return new JsonResult("The enrollment failed, possibly because some students were re-enrolled before " + "the previous enrollment action was still being processed by TEAMMATES database " + "servers. Please try again after about 10 minutes. If the problem persists, " + "please contact TEAMMATES support", HttpStatus.SC_NOT_FOUND); } }

Target:
public ActionResult execute() throws EntityNotFoundException { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String studentsInfo = getRequestBody(); try { List<StudentAttributes>[] students = enrollAndProcessResultForDisplay(studentsInfo, courseId); EnrollResults dataFormat = new EnrollResults(getInstructorCourseEnrollResult(students)); return new JsonResult(dataFormat); } catch (EntityDoesNotExistException e) { throw new EntityNotFoundException(e); } catch (EnrollException | InvalidParametersException e) { return new JsonResult(e.getMessage(), HttpStatus.SC_BAD_REQUEST); } catch (EntityAlreadyExistsException e) { log.severe("Entity already exists exception occurred when updating student: " + e.getMessage()); return new JsonResult("The enrollment failed, possibly because some students were re-enrolled before " + "the previous enrollment action was still being processed by TEAMMATES database " + "servers. Please try again after about 10 minutes. If the problem persists, " + "please contact TEAMMATES support", HttpStatus.SC_CONFLICT); } }
Source:
public Map<Guid, HostNicVfsConfig> findHostNicVfsConfigs() { final List<HostNicVfsConfig> hostNicVfsConfigs = getBackendCollection(HostNicVfsConfig.class, VdcQueryType.GetAllVfsConfigByHostId, new IdQueryParameters(asGuid(hostId))); return hostNicVfsConfigs.stream().collect(Collectors.toMap(HostNicVfsConfig::getNicId, x -> x)); }

Target:
public Map<Guid, HostNicVfsConfig> findHostNicVfsConfigs() { final List<HostNicVfsConfig> hostNicVfsConfigs = getBackendCollection(HostNicVfsConfig.class, VdcQueryType.GetAllVfsConfigByHostId, new IdQueryParameters(asGuid(hostId))); return hostNicVfsConfigs.stream().collect(toMap(HostNicVfsConfig::getNicId, x -> x)); }
Source:
public static Artifact getDistroModule(String groupId, String artifactId, String version) { Artifact artifact = new Artifact(artifactId, version, groupId, Artifact.TYPE_ZIP); artifact.setClassifier("distro"); return artifact; }

Target:
public static Artifact getDistroModule(String groupId, String artifactId, String version) { return new Artifact(artifactId, version, groupId); }
Source:
public void testEmptyBitVector() { RankedBitVectorImpl bv0 = new RankedBitVectorImpl(); RankedBitVector bv1 = new RankedBitVectorImpl(); assertEqualsForBitVector(bv0, bv1); assertCorrectCount(bv0); assertCorrectCount(bv1); assertCorrectFindPosition(bv0); assertCorrectFindPosition(bv1); RankedBitVectorImpl bv2 = new RankedBitVectorImpl(0); assertEqualsForBitVector(bv1, bv2); assertCorrectCount(bv2); assertCorrectFindPosition(bv2); }

Target:
public void testEmptyBitVector() { RankedBitVectorImpl bv0 = new RankedBitVectorImpl(); Assert.assertEquals(0, bv0.size()); assertCorrectCount(bv0); assertCorrectFindPosition(bv0); Assert.assertNotEquals(bv0, new Object()); Assert.assertEquals(bv0, new BitVectorImpl()); RankedBitVector bv1 = new RankedBitVectorImpl(); RankedBitVectorImpl bv2 = new RankedBitVectorImpl(0); assertEqualsForBitVector(bv1, bv2); assertCorrectCount(bv2); assertCorrectFindPosition(bv2); }
Source:
public DruidExpression visitCall( CallExpression call, Map<VariableReferenceExpression, DruidQueryGeneratorContext.Selection> context) { Optional<DruidExpression> basicCallHandlingResult = basicCallHandling(call, context); if (basicCallHandlingResult.isPresent()) { return basicCallHandlingResult.get(); } FunctionMetadata functionMetadata = functionMetadataManager.getFunctionMetadata(call.getFunctionHandle()); Optional<OperatorType> operatorTypeOptional = functionMetadata.getOperatorType(); if (operatorTypeOptional.isPresent()) { OperatorType operatorType = operatorTypeOptional.get(); if (operatorType.isArithmeticOperator()) { return handleArithmeticExpression(call, operatorType, context); } if (operatorType.isComparisonOperator()) { throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported operator: " + call + " to pushdown for Druid connector "); } } return handleFunction(call, context); }

Target:
public DruidExpression visitCall( CallExpression call, Map<VariableReferenceExpression, DruidQueryGeneratorContext.Selection> context) { Optional<DruidExpression> basicCallHandlingResult = basicCallHandling(call, context); if (basicCallHandlingResult.isPresent()) { return basicCallHandlingResult.get(); } FunctionMetadata functionMetadata = functionMetadataManager.getFunctionMetadata(call.getFunctionHandle()); Optional<OperatorType> operatorTypeOptional = functionMetadata.getOperatorType(); if (operatorTypeOptional.isPresent()) { OperatorType operatorType = operatorTypeOptional.get(); if (operatorType.isArithmeticOperator()) { return handleArithmeticExpression(call, operatorType, context); } if (operatorType.isComparisonOperator()) { throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported operator: " + call + " to pushdown for Druid connector."); } } return handleFunction(call, context); }
Source:
protected Map<String, String> params() { Map<String, String> localParams = new HashMap<>(); localParams.put("card[exp_month]", authCardDetails.expiryMonth()); localParams.put("card[exp_year]", authCardDetails.expiryYear()); localParams.put("card[number]", authCardDetails.getCardNo()); localParams.put("card[cvc]", authCardDetails.getCvc()); localParams.put("billing_details[name]", authCardDetails.getCardHolder()); localParams.put("type", "card"); authCardDetails.getAddress().ifPresent(address -> { localParams.put("billing_details[address[line1]]", address.getLine1()); if (StringUtils.isNotBlank(address.getLine2())) { localParams.put("billing_details[address[line2]]", address.getLine2()); } northAmericanRegionMapper.getNorthAmericanRegionForCountry(address) .ifPresent(stateOrProvince -> localParams.put("billing_details[address[state]]", stateOrProvince.getFullName())); localParams.put("billing_details[address[city]]", address.getCity()); localParams.put("billing_details[address[country]]", address.getCountry()); localParams.put("billing_details[address[postal_code]]", address.getPostcode()); }); return Map.copyOf(localParams); }

Target:
protected Map<String, String> params() { Map<String, String> localParams = new HashMap<>(); localParams.put("card[exp_month]", authCardDetails.expiryMonth()); localParams.put("card[exp_year]", authCardDetails.expiryYear()); localParams.put("card[number]", authCardDetails.getCardNo()); localParams.put("card[cvc]", authCardDetails.getCvc()); localParams.put("billing_details[name]", authCardDetails.getCardHolder()); localParams.put("type", "card"); authCardDetails.getAddress().ifPresent(address -> { localParams.put("billing_details[address[line1]]", address.getLine1()); if (StringUtils.isNotBlank(address.getLine2())) { localParams.put("billing_details[address[line2]]", address.getLine2()); } northAmericanRegionMapper.getNorthAmericanRegionForCountry(address) .map(NorthAmericaRegion::getFullName) .ifPresent(stateOrProvince -> localParams.put("billing_details[address[state]]", stateOrProvince)); localParams.put("billing_details[address[city]]", address.getCity()); localParams.put("billing_details[address[country]]", address.getCountry()); localParams.put("billing_details[address[postal_code]]", address.getPostcode()); }); return Map.copyOf(localParams); }
Source:
TableAsyncBatch(String partitionKey, TableAsyncClient client) { this.partitionKey = partitionKey; this.batchImpl = new BatchImpl(client.getImplementation(), new TablesMultipartSerializer()); this.operationClient = new TableClientBuilder() .tableName(client.getTableName()) .endpoint(client.getImplementation().getUrl()) .serviceVersion(client.getApiVersion()) .pipeline(BuilderHelper.buildNullClientPipeline()) .buildAsyncClient(); }

Target:
TableAsyncBatch(String partitionKey, TableAsyncClient client) { this.partitionKey = partitionKey; this.batchImpl = new BatchImpl(client.getImplementation(), BATCH_SERIALIZER); this.operationClient = new TableClientBuilder() .tableName(client.getTableName()) .endpoint(client.getImplementation().getUrl()) .serviceVersion(client.getApiVersion()) .pipeline(BuilderHelper.buildNullClientPipeline()) .buildAsyncClient(); }
Source:
private CouponDefinition getIborInterpolatedStubDefinition( double notional, ZonedDateTime paymentDate, ZonedDateTime accrualStartDate, ZonedDateTime accrualEndDate, double accrualYearFraction, ZonedDateTime fixingDate, ZonedDateTime fixingPeriodStartDate, ZonedDateTime fixingPeriodEndDate, double fixingPeriodYearFraction, double initialRate, ZonedDateTime firstInterpolatedDate, double firstInterpolatedYearFraction, IborIndex firstStubIndex, ZonedDateTime secondInterpolatedDate, double secondInterpolatedYearFraction, IborIndex secondStubIndex) { assert !accrualEndDate.isBefore(firstInterpolatedDate); assert !accrualEndDate.isAfter(secondInterpolatedDate); ActualActualISDA dayCount = new ActualActualISDA(); double timeToPeriodEnd = dayCount.getDayCountFraction(accrualStartDate, accrualEndDate); double timeToFirstInterpolatedRateDate = dayCount.getDayCountFraction(accrualStartDate, firstInterpolatedDate); double timeToSecondInterpolatedRateDate = dayCount.getDayCountFraction(accrualStartDate, secondInterpolatedDate); double weightDenominator = timeToSecondInterpolatedRateDate - timeToFirstInterpolatedRateDate; double weightFirstIndex = (timeToSecondInterpolatedRateDate - timeToPeriodEnd) / weightDenominator; double weightSecondIndex = (timeToPeriodEnd - timeToFirstInterpolatedRateDate) / weightDenominator; return CouponIborAverageIndexDefinition.from( paymentDate, accrualStartDate, accrualEndDate, accrualYearFraction, notional, fixingDate, firstStubIndex, secondStubIndex, weightFirstIndex, weightSecondIndex, getFixingCalendar(), getFixingCalendar()); }

Target:
private CouponDefinition getIborInterpolatedStubDefinition( double notional, ZonedDateTime paymentDate, ZonedDateTime accrualStartDate, ZonedDateTime accrualEndDate, double accrualYearFraction, ZonedDateTime fixingDate, ZonedDateTime fixingPeriodStartDate, ZonedDateTime fixingPeriodEndDate, double fixingPeriodYearFraction, double initialRate, ZonedDateTime firstInterpolatedDate, double firstInterpolatedYearFraction, IborIndex firstStubIndex, ZonedDateTime secondInterpolatedDate, double secondInterpolatedYearFraction, IborIndex secondStubIndex) { Pair<Double, Double> weights = getInterpolationWeights(accrualStartDate, accrualEndDate, firstInterpolatedDate, secondInterpolatedDate); return CouponIborAverageIndexDefinition.from( paymentDate, accrualStartDate, accrualEndDate, accrualYearFraction, notional, fixingDate, firstStubIndex, secondStubIndex, weights.getFirst(), weights.getSecond(), getFixingCalendar(), getFixingCalendar()); }
Source:
protected void eventHandle(@NonNull ITmfEvent event) { ITmfStateSystemBuilder ss = getStateSystemBuilder(); if (ss == null) { return; } String phase = event.getContent().getFieldValue(String.class, ITraceEventConstants.PHASE); if (phase == null) { return; } long t = event.getTimestamp().toNanos(); int quark = ITmfStateSystem.INVALID_ATTRIBUTE; Object id = TmfTraceUtils.resolveEventAspectOfClassForEvent(event.getTrace(), TraceEventAspects.ID_ASPECT.getClass(), event); String name = String.valueOf(TmfTraceUtils.resolveAspectOfNameForEvent(event.getTrace(), "Name", event)); if (id == null) { return; } switch (phase) { case TraceEventPhases.OBJECT_CREATED: quark = ss.getQuarkAbsoluteAndAdd(name, String.valueOf(id)); ss.modifyAttribute(t, "", quark); break; case TraceEventPhases.OBJECT_SNAPSHOT: quark = ss.getQuarkAbsoluteAndAdd(name, String.valueOf(id)); ss.modifyAttribute(t, String.valueOf(TraceEventAspects.ARGS_ASPECT.resolve(event)), quark); break; case TraceEventPhases.OBJECT_DESTROYED: quark = ss.getQuarkAbsoluteAndAdd(name, String.valueOf(id)); ss.modifyAttribute(t, TmfStateValue.nullValue(), quark); break; default: break; } }

Target:
protected void eventHandle(@NonNull ITmfEvent event) { ITmfStateSystemBuilder ss = getStateSystemBuilder(); if (ss == null) { return; } String phase = event.getContent().getFieldValue(String.class, ITraceEventConstants.PHASE); if (phase == null) { return; } long t = event.getTimestamp().toNanos(); int quark = ITmfStateSystem.INVALID_ATTRIBUTE; Object id = TmfTraceUtils.resolveEventAspectOfClassForEvent(event.getTrace(), TraceEventAspects.ID_ASPECT.getClass(), event); String name = String.valueOf(TmfTraceUtils.resolveAspectOfNameForEvent(event.getTrace(), "Name", event)); if (id == null) { return; } switch (phase) { case TraceEventPhases.OBJECT_CREATED: quark = ss.getQuarkAbsoluteAndAdd(name, String.valueOf(id)); ss.modifyAttribute(t, "", quark); break; case TraceEventPhases.OBJECT_SNAPSHOT: quark = ss.getQuarkAbsoluteAndAdd(name, String.valueOf(id)); ss.modifyAttribute(t, String.valueOf(TraceEventAspects.ARGS_ASPECT.resolve(event)), quark); break; case TraceEventPhases.OBJECT_DESTROYED: quark = ss.getQuarkAbsoluteAndAdd(name, String.valueOf(id)); ss.modifyAttribute(t, (Object)null, quark); break; default: break; } }
Source:
public void validate_shouldFailValidationIfNumRefillsIsNullForOutpatientCareSetting() throws Exception { DrugOrder OutpatientOrder = new DrugOrder(); CareSetting outpatientCareSetting = new CareSetting("OPD", "Outpatient", CareSetting.CareSettingType.OUTPATIENT); OutpatientOrder.setCareSetting(outpatientCareSetting); OutpatientOrder.setNumRefills(null); Errors OutpatientOrderErrors = new BindException(OutpatientOrder, "order"); new DrugOrderValidator().validate(OutpatientOrder, OutpatientOrderErrors); Assert.assertTrue(OutpatientOrderErrors.hasFieldErrors("numRefills")); DrugOrder inPatientOrder = new DrugOrder(); CareSetting inpatientCareSetting = new CareSetting("IPD", "Inpatient", CareSetting.CareSettingType.INPATIENT); inPatientOrder.setCareSetting(inpatientCareSetting); inPatientOrder.setNumRefills(null); Errors InpatientOrderErrors = new BindException(inPatientOrder, "order"); new DrugOrderValidator().validate(inPatientOrder, InpatientOrderErrors); Assert.assertFalse(InpatientOrderErrors.hasFieldErrors("numRefills")); }

Target:
public void validate_shouldFailValidationIfNumRefillsIsNullForOutpatientCareSetting() throws Exception { DrugOrder OutpatientOrder = new DrugOrder(); OutpatientOrder.setCareSetting(Context.getOrderService().getCareSetting(1)); OutpatientOrder.setNumRefills(null); Errors OutpatientOrderErrors = new BindException(OutpatientOrder, "order"); new DrugOrderValidator().validate(OutpatientOrder, OutpatientOrderErrors); Assert.assertTrue(OutpatientOrderErrors.hasFieldErrors("numRefills")); DrugOrder inPatientOrder = new DrugOrder(); inPatientOrder.setCareSetting(Context.getOrderService().getCareSetting(2)); inPatientOrder.setNumRefills(null); Errors InpatientOrderErrors = new BindException(inPatientOrder, "order"); new DrugOrderValidator().validate(inPatientOrder, InpatientOrderErrors); Assert.assertFalse(InpatientOrderErrors.hasFieldErrors("numRefills")); }
Source:
private Boolean hasExistingTitle(Element mods) { Boolean hasOldTitle; try { Element title = mods.getChild("titleInfo", MODS_V3_NS).getChild("title", MODS_V3_NS); hasOldTitle = true; } catch (NullPointerException e) { hasOldTitle = false; } return hasOldTitle; }

Target:
private boolean hasExistingTitle(Element mods) { boolean hasOldTitle; try { Element title = mods.getChild("titleInfo", MODS_V3_NS).getChild("title", MODS_V3_NS); hasOldTitle = true; } catch (NullPointerException e) { hasOldTitle = false; } return hasOldTitle; }
Source:
public Builder(final ApiContext<AbiquoApi> context, final Datacenter datacenter) { super(); this.context = context; this.datacenter = datacenter; }

Target:
public Builder(final ApiContext<AbiquoApi> context, final Datacenter datacenter) { this.context = checkNotNull(context, "missing context object"); this.datacenter = checkNotNull(datacenter, "missing datacenter object"); }
Source:
public void testAggregateDisksSnapshots() { List<Disk> diskImagesTestParam = new ArrayList<>(); diskImagesTestParam.add(diskWithSnapshots); diskImagesTestParam.add(diskWithoutSnapshots); diskImagesTestParam.addAll(snapshotsList); diskImagesTestParam.add(ovfImage); diskImagesTestParam.add(cinderDisk); diskImagesTestParam.add(lunDisk); Collection<Disk> disks = getQuery().aggregateDisksSnapshots(diskImagesTestParam); assertAllDisksAreActive(disks); assertEquals("should be a total of four disks", 5, disks.size()); }

Target:
public void testAggregateDisksSnapshots() { List<Disk> disks = new ArrayList<>(Arrays.asList(diskWithSnapshots, diskWithoutSnapshots, ovfImage, cinderDisk, lunDisk)); disks.addAll(snapshotsList); Collection<Disk> result = getQuery().aggregateDisksSnapshots(disks); assertAllDisksAreActive(result); assertEquals("wrong number of disks returned", 5, result.size()); }
Source:
public void store(Item item, String alias) { if (item.getState() instanceof UnDefType) { return; } if (!isProperlyConfigured) { logger.warn("Configuration for influxdb not yet loaded or broken."); return; } if (!isConnected()) { logger.warn("InfluxDB is not yet connected"); return; } String realName = item.getName(); String name = (alias != null) ? alias : realName; State state = null; if (item.getAcceptedCommandTypes().contains(HSBType.class)) { state = item.getStateAs(HSBType.class); logger.trace("got hsbtype", state.toString()); } else if (item.getAcceptedDataTypes().contains(PercentType.class)) { state = item.getStateAs(PercentType.class); logger.trace("percentype item found {}", name); } else { logger.trace("other item found"); state = item.getState(); } Object value = stateToObject(state); logger.trace("storing in influxdb value {}, {}", name, value, item); Point point = Point.measurement(name).field(VALUE_COLUMN_NAME, value) .time(System.currentTimeMillis(), timeUnit).build(); try { influxDB.write(dbName, "default", point); } catch (RuntimeException e) { logger.error("storing failed with exception for item: {}", name); handleDatabaseException(e); } }

Target:
public void store(Item item, String alias) { if (item.getState() instanceof UnDefType) { return; } if (!isProperlyConfigured) { logger.warn("Configuration for influxdb not yet loaded or broken."); return; } if (!isConnected()) { logger.warn("InfluxDB is not yet connected"); return; } String realName = item.getName(); String name = (alias != null) ? alias : realName; State state = null; if (item.getAcceptedCommandTypes().contains(HSBType.class)) { state = item.getStateAs(HSBType.class); logger.trace("Tried to get item as {}, state is {}", HSBType.class, state.toString()); } else if (item.getAcceptedDataTypes().contains(PercentType.class)) { state = item.getStateAs(PercentType.class); logger.trace("Tried to get item as {}, state is {}", PercentType.class, state.toString()); } else { state = item.getState(); logger.trace("Tried to get item from item class {}, state is {}", item.getClass(), state.toString()); } Object value = stateToObject(state); logger.trace("storing in influxdb value {}, {}", name, value, item); Point point = Point.measurement(name).field(VALUE_COLUMN_NAME, value) .time(System.currentTimeMillis(), timeUnit).build(); try { influxDB.write(dbName, "default", point); } catch (RuntimeException e) { logger.error("storing failed with exception for item: {}", name); handleDatabaseException(e); } }
Source:
private Map<String, Object> getRootObject(InputStream input) throws CatalogTransformerException { Map<String, Object> rootObject; try { rootObject = GSON.fromJson(new InputStreamReader(input), MAP_STRING_TO_OBJECT_TYPE); } catch (JsonParseException e) { throw new CatalogTransformerException("Invalid JSON input", e); } if (rootObject == null) { throw new CatalogTransformerException("Unable to parse JSON for metacard."); } return rootObject; }

Target:
private Map<String, Object> getRootObject(InputStream input) throws CatalogTransformerException { Map<String, Object> rootObject; try { rootObject = GSON.fromJson( new InputStreamReader(input, StandardCharsets.UTF_8), MAP_STRING_TO_OBJECT_TYPE); } catch (JsonParseException e) { throw new CatalogTransformerException("Invalid JSON input", e); } if (rootObject == null) { throw new CatalogTransformerException("Unable to parse JSON for metacard."); } return rootObject; }
Source:
public AlreadyReportedRepositoryAccessException(Exception e) { super(e.getMessage(), e.getCause()); checkState(e instanceof NoSuchPackageException || e instanceof IOException || e instanceof EvalException || e instanceof ExternalPackageException); }

Target:
public AlreadyReportedRepositoryAccessException(Exception e) { super(e.getMessage(), e.getCause()); checkState(e instanceof NoSuchPackageException || e instanceof IOException || e instanceof EvalException || e instanceof ExternalPackageException, e); }
Source:
private void storeQuery(String query) { ContentValues cv = new ContentValues(); cv.put(SearchHistory.QUERY, query); getContentResolver().insert(SearchHistory.CONTENT_URI, cv); }

Target:
private void storeQuery(String query) { final ContentValues cv = new ContentValues(); cv.put(SearchHistory.QUERY, query); queryHandler.startInsert(0, null, SearchHistory.CONTENT_URI, cv); }
Source:
public String websocket() { String url = build().toString(); url = "wss" + url.substring(url.indexOf(":")); LOG.debug(String.format("Built url: %s", url)); return url; }

Target:
public String websocket() { String url = build().toString(); url = "wss" + url.substring(url.indexOf(":")); if(LOG.isDebugEnabled()) { LOG.debug(String.format("Built url: %s", url)); } return url; }
Source:
public void owner(String owner) throws RestApiException { String restPath = getRequestPath() + "/owner"; JsonElement result = gerritRestClient.putRequest(restPath, owner); }

Target:
public void owner(String owner) throws RestApiException { String restPath = getRequestPath() + "/owner"; gerritRestClient.putRequest(restPath, owner); }
Source:
public View getView(int position, View convertView, ViewGroup parent) { CommentView v; if (convertView == null) { v = new CommentView(mContext); } else { v = (CommentView) convertView; } Comment comment = getItem(position); v.buildView(comment); LinearLayout replyContainer = (LinearLayout) v.findViewById(R.id.comment_replies); replyContainer.removeAllViews(); for (Comment reply : comment.mReplies) { if (reply.mParentid == comment.mCommentid) { CommentView replyView = new CommentView(mContext); replyView.buildView(reply); replyView.setPadding(0, 0, 0, 0); replyContainer.addView(replyView); } } replyContainer.setVisibility(replyContainer.getChildCount() != 0 ? View.VISIBLE : View.GONE); return v; }

Target:
public View getView(int position, View convertView, ViewGroup parent) { CommentView v; if (convertView == null) { v = new CommentView(mContext); } else { v = (CommentView) convertView; } Comment comment = getItem(position); v.buildView(comment); LinearLayout replyContainer = (LinearLayout) v.findViewById(R.id.comment_replies); replyContainer.removeAllViews(); for (Comment reply : comment.mReplies) { CommentView replyView = new CommentView(mContext); replyView.buildView(reply); replyView.setPadding(0, 0, 0, 0); replyContainer.addView(replyView); } replyContainer.setVisibility(replyContainer.getChildCount() != 0 ? View.VISIBLE : View.GONE); return v; }
Source:
public void showAvailableApps() { this.showDetailsView(null); showRightView(availableApps); }

Target:
public void showAvailableApps() { this.closeDetailsView(); setCenter(availableApps); }
Source:
private Vector<ChangeBasedEvent> createEventsFromString(String eventsString) { Vector<ChangeBasedEvent> events = new Vector<ChangeBasedEvent>(); Scanner scanner = new Scanner(eventsString); while (scanner.hasNextLine()) { String line = scanner.nextLine(); logger.debug("found line: {}", line); JSONObject jsonObject = JSONObject.fromObject(line); GerritEvent evt = GerritJsonEventFactory.getEvent(jsonObject); if (evt instanceof ChangeBasedEvent) { Provider provider = new Provider(); provider.setName(serverName); ((GerritTriggeredEvent)evt).setProvider(provider); events.add((ChangeBasedEvent)evt); } } scanner.close(); return events; }

Target:
private List<GerritTriggeredEvent> createEventsFromString(String eventsString) { List<GerritTriggeredEvent> events = Collections.synchronizedList(new ArrayList<GerritTriggeredEvent>()); Scanner scanner = new Scanner(eventsString); while (scanner.hasNextLine()) { String line = scanner.nextLine(); logger.debug("found line: {}", line); JSONObject jsonObject = JSONObject.fromObject(line); GerritEvent evt = GerritJsonEventFactory.getEvent(jsonObject); if (evt instanceof ChangeBasedEvent) { Provider provider = new Provider(); provider.setName(serverName); ((GerritTriggeredEvent)evt).setProvider(provider); events.add((ChangeBasedEvent)evt); } } scanner.close(); return events; }
Source:
public void finished() { boolean processResults = result; if(!result) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message( "Tool execution failed or canceled by user. Output files were not written.")); } progressHandle.finish(); Storage motion = null; if(analyzeTool().getStatesStorage()!=null) { motion = new Storage(analyzeTool().getStatesStorage()); } updateMotion(motion); if (staticOptimizationMode){ StaticOptimization soA = StaticOptimization.safeDownCast(getModel().getAnalysisSet().get("StaticOptimization")); Storage storage = soA.getActivationStorage(); storage.print("soout.sto"); MotionDisplayer motionDisplayer = new MotionDisplayer(storage, getOriginalModel()); MuscleColoringFunction mcbya = new MuscleColorByActivationStorage( OpenSimDB.getInstance().getContext(getOriginalModel()), storage); motionDisplayer.setMuscleColoringFunction(mcbya); } getModel().removeAnalysis(interruptingCallback, false); interruptingCallback = null; if(result) resetModified(); setExecuting(false); SimulationDB.getInstance().fireToolFinish(); worker = null; }

Target:
public void finished() { boolean processResults = result; if(!result) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message( "Tool execution failed or canceled by user. Output files were not written.")); } progressHandle.finish(); Storage motion = null; if(analyzeTool().getStatesStorage()!=null) { motion = new Storage(analyzeTool().getStatesStorage()); } updateMotion(motion); if (staticOptimizationMode){ StaticOptimization soA = StaticOptimization.safeDownCast(getModel().getAnalysisSet().get("StaticOptimization")); Storage storage = soA.getActivationStorage(); MotionDisplayer motionDisplayer = new MotionDisplayer(storage, getOriginalModel()); MuscleColoringFunction mcbya = new MuscleColorByActivationStorage( OpenSimDB.getInstance().getContext(getOriginalModel()), storage); motionDisplayer.setMuscleColoringFunction(mcbya); } getModel().removeAnalysis(interruptingCallback, false); interruptingCallback = null; if(result) resetModified(); setExecuting(false); SimulationDB.getInstance().fireToolFinish(); worker = null; }
Source:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { if (syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) syntaxNode; if (MAP_PUT.matches(mit)) { ProgramState ps = context.getState(); SymbolicValue keySV = ps.peekValue(1); SymbolicValue mapSV = ps.peekValue(2); if(!isMethodInvocationThrowingCheckedException(mit.arguments().get(1))) { mapGetInvocations.get(mapSV).stream() .filter(getOnSameMap -> getOnSameMap.withSameKey(keySV)) .findAny() .ifPresent(getOnSameMap -> { ObjectConstraint constraint = ps.getConstraint(getOnSameMap.value, ObjectConstraint.class); if (constraint != null && isInsideIfStatementWithNullCheckWithoutElse(mit)) { checkIssues.add(new CheckIssue(context.getNode(), getOnSameMap.mit, mit, getOnSameMap.value, constraint)); } }); } } } return super.checkPreStatement(context, syntaxNode); }

Target:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { if (syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) syntaxNode; if (MAP_PUT.matches(mit) && !isMethodInvocationThrowingCheckedException(mit.arguments().get(1))) { ProgramState ps = context.getState(); SymbolicValue keySV = ps.peekValue(1); SymbolicValue mapSV = ps.peekValue(2); mapGetInvocations.get(mapSV).stream() .filter(getOnSameMap -> getOnSameMap.withSameKey(keySV)) .findAny() .ifPresent(getOnSameMap -> { ObjectConstraint constraint = ps.getConstraint(getOnSameMap.value, ObjectConstraint.class); if (constraint != null && isInsideIfStatementWithNullCheckWithoutElse(mit)) { checkIssues.add(new CheckIssue(context.getNode(), getOnSameMap.mit, mit, getOnSameMap.value, constraint)); } }); } } return super.checkPreStatement(context, syntaxNode); }
Source:
public void replaceLambdaIssue1290() { MethodCallExpr methodCallExpr = parseExpression("callSomeFun(r -> r instanceof SomeType)").asMethodCallExpr(); LambdaExpr lambdaExpr = methodCallExpr.getArgument(0).asLambdaExpr(); MethodCallExpr lambdaWrapper = new MethodCallExpr("lambdaWrapper"); lambdaExpr.replace(lambdaWrapper); assertEquals(2, methodCallExpr.getChildNodes().size()); }

Target:
public void replaceLambdaIssue1290() { MethodCallExpr methodCallExpr = parseExpression("callSomeFun(r -> r instanceof SomeType)").asMethodCallExpr(); LambdaExpr lambdaExpr = methodCallExpr.getArgument(0).asLambdaExpr(); MethodCallExpr lambdaWrapper = new MethodCallExpr("lambdaWrapper"); lambdaExpr.replace(lambdaWrapper); assertEquals(2, methodCallExpr.getChildNodes().size()); assertEquals(empty(), lambdaExpr.getParentNode()); }
Source:
public void process() throws IOException { String name = regionInfo.getEncodedName(); LOG.trace("Processing close of {}", name); String encodedRegionName = regionInfo.getEncodedName(); HRegion region = (HRegion)rsServices.getRegion(encodedRegionName); if (region == null) { LOG.warn("Received CLOSE for region but currently not serving - ignoring", name); return; } if (region.close(abort) == null) { LOG.warn("Can't close region {}, was already closed during close()", name); return; } this.rsServices.removeRegion(region, destination); rsServices.reportRegionStateTransition(new RegionStateTransitionContext(TransitionCode.CLOSED, HConstants.NO_SEQNUM, Procedure.NO_PROC_ID, -1, regionInfo)); this.rsServices.getRegionsInTransitionInRS(). remove(this.regionInfo.getEncodedNameAsBytes(), Boolean.FALSE); LOG.debug("Closed " + region.getRegionInfo().getRegionNameAsString()); }

Target:
public void process() throws IOException { String name = regionInfo.getEncodedName(); LOG.trace("Processing close of {}", name); String encodedRegionName = regionInfo.getEncodedName(); HRegion region = (HRegion)rsServices.getRegion(encodedRegionName); try { if (region == null) { LOG.warn("Received CLOSE for region but currently not serving - ignoring", name); return; } if (region.close(abort) == null) { LOG.warn("Can't close {}; already closed", name); return; } this.rsServices.removeRegion(region, destination); rsServices.reportRegionStateTransition(new RegionStateTransitionContext(TransitionCode.CLOSED, HConstants.NO_SEQNUM, Procedure.NO_PROC_ID, -1, regionInfo)); this.rsServices.getRegionsInTransitionInRS(). remove(this.regionInfo.getEncodedNameAsBytes(), Boolean.FALSE); LOG.debug("Closed {}" + region.getRegionInfo().getRegionNameAsString()); } finally { this.rsServices.getRegionsInTransitionInRS().remove(regionInfo.getEncodedNameAsBytes()); } }
Source:
public void testFindAllIDs() throws DataException { List<Integer> allIDs = ServiceManager.getProcessService().findAllIDs(); System.out.println(allIDs); Assert.assertEquals("Wrong amount of id's in index", 7, allIDs.size()); Assert.assertTrue("id's contain wrong entries", allIDs.containsAll(Arrays.asList(5, 2, 6, 4, 1, 7, 3))); }

Target:
public void testFindAllIDs() throws DataException { List<Integer> allIDs = ServiceManager.getProcessService().findAllIDs(); Assert.assertEquals("Wrong amount of id's in index", 7, allIDs.size()); Assert.assertTrue("id's contain wrong entries", allIDs.containsAll(Arrays.asList(5, 2, 6, 4, 1, 7, 3))); }
Source:
EnvironmentVariableContext getEnvironmentVariableContextFromEnvironment(String pipelineName) { EnvironmentConfig environmentConfig = environmentConfigService.environmentForPipeline(pipelineName); if (environmentConfig == null) { return null; } secretParamResolver.resolve(environmentConfig); EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext(GO_ENVIRONMENT_NAME, CaseInsensitiveString.str(environmentConfig.name())); environmentConfig.getVariables().forEach(variable -> { environmentVariableContext.setProperty(variable.getName(), variable.valueForCommandline(), variable.isSecure() || variable.hasSecretParams()); }); return environmentVariableContext; }

Target:
EnvironmentVariableContext getEnvironmentVariableContextFromEnvironment(String pipelineName) { EnvironmentConfig environmentForPipeline = environmentConfigService.environmentForPipeline(pipelineName); if (environmentForPipeline == null) { return null; } secretParamResolver.resolve(environmentForPipeline); EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext(GO_ENVIRONMENT_NAME, CaseInsensitiveString.str(environmentForPipeline.name())); environmentForPipeline.getVariables().forEach(variable -> { environmentVariableContext.setProperty(variable.getName(), variable.valueForCommandline(), variable.isSecure() || variable.hasSecretParams()); }); return environmentVariableContext; }
Source:
public synchronized Set<TopicPartition> getPartitionsNeedingInit() { return _needingInit; }

Target:
public synchronized Set<TopicPartition> getPartitionsNeedingInit() { return Collections.unmodifiableSet(_needingInit); }
Source:
public TaskStateModelFactory(HelixManager manager, Map<String, TaskFactory> taskFactoryRegistry, ScheduledExecutorService taskExecutor) { _manager = manager; _taskFactoryRegistry = taskFactoryRegistry; _taskExecutor = taskExecutor; _timerTaskExecutor = createTimerTaskExecutor(); initializeTaskMonitor(); }

Target:
public TaskStateModelFactory(HelixManager manager, Map<String, TaskFactory> taskFactoryRegistry, ScheduledExecutorService taskExecutor) { _manager = manager; _taskFactoryRegistry = taskFactoryRegistry; _taskExecutor = taskExecutor; _timerTaskExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "TaskStateModelFactory-timeTask_thread"); } }); if (_taskExecutor instanceof ThreadPoolExecutor) { try { _monitor = new ThreadPoolExecutorMonitor(TaskConstants.STATE_MODEL_NAME, (ThreadPoolExecutor) _taskExecutor); } catch (JMException e) { LOG.warn("Error in creating ThreadPoolExecutorMonitor for TaskStateModelFactory.", e); } } }
Source:
public String text(Barcodable barcodable) { return barcodable.visit(new BarcodableVisitor<String>() { @Override public String visitLibraryAliquotDetailed(DetailedLibraryAliquot libraryAliquot) { return visitLibraryDetailed((DetailedLibrary) libraryAliquot.getLibrary()); } @Override public String visitLibraryDetailed(DetailedLibrary library) { return library.getLibraryDesignCode().getCode(); } }); }

Target:
public String text(Barcodable barcodable) { return barcodable.getAlias(); }
Source:
private void createDummyImages() throws IOException { URI processDirectory = serviceManager.getFileService().getProcessBaseUriForExistingProcess(this.prozessKopie); String imageDirectoryName = this.prozessKopie.getTitle() + "_" + Config.getParameter("MetsEditorDefaultSuffix"); URI imagesDirectory = serviceManager.getFileService().createDirectory( serviceManager.getFileService().createDirectory(processDirectory, "images"), imageDirectoryName); String numberOfDigits = extractNumber(Config.getParameter("ImagePrefix")); for (int i = 1; i <= this.guessedImages; i++) { serviceManager.getFileService().createResource(imagesDirectory, String.format("%0" + numberOfDigits + "d", i) + ".tif"); } }

Target:
private void createDummyImages() throws IOException { serviceManager.getFileService().createDummyImagesForProcess(this.prozessKopie, this.guessedImages); }
Source:
private List<QueryTrace> queryTracesFromRetries(List<RetryException> retryExceptions) { Iterator<RetryException> iterator = retryExceptions.iterator(); List<QueryTrace> traces = new ArrayList<QueryTrace>(); long lastTS = 0; while (iterator.hasNext()) { RetryException re = iterator.next(); Throwable cause = re.getCause(); String message = ""; if (cause instanceof RuntimeNodeException) { RuntimeNodeException rne = (RuntimeNodeException) cause; message += rne.getUri() + " "; } message += "error=" + cause.getMessage(); long microTS = TimeUnit.MICROSECONDS.convert(re.getOffsetMillis(), TimeUnit.MILLISECONDS); QueryTrace trace = QueryTrace.of(new QueryTrace.Identifier(message), microTS - lastTS); lastTS = microTS; traces.add(trace); } return traces; }

Target:
private List<QueryTrace> queryTracesFromRetries(List<RetryException> retryExceptions) { final List<QueryTrace> traces = new ArrayList<QueryTrace>(); long lastTS = 0; for (final RetryException re : retryExceptions) { final long microTS = TimeUnit.MICROSECONDS.convert(re.getOffsetMillis(), TimeUnit.MILLISECONDS); final long elapsed = microTS - lastTS; final QueryTrace trace = QueryTrace.of(new QueryTrace.Identifier(getMessageFrom(re.getCause())), elapsed); lastTS = microTS; traces.add(trace); } return traces; }
Source:
public void setRetainUntil(DocumentRef docRef, Calendar retainUntil, String comment) throws PropertyException { Document doc = resolveReference(docRef); checkPermission(doc, READ); if (!doc.isRecord()) { throw new PropertyException("Document is not a record"); } Calendar current = doc.getRetainUntil(); if (Objects.equals(current, retainUntil)) { return; } checkPermission(doc, SET_RETENTION); Map<String, Serializable> options = new HashMap<>(); options.put(CoreEventConstants.RETAIN_UNTIL, retainUntil); options.put("comment", retainUntil == null ? "" : retainUntil.toInstant().toString()); DocumentModel docModel = readModel(doc); boolean currentIndeterminate = current == null || RETAIN_UNTIL_INDETERMINATE.compareTo(current) == 0; String beforeRetentionEvent = currentIndeterminate ? DocumentEventTypes.BEFORE_SET_RETENTION : DocumentEventTypes.BEFORE_EXTEND_RETENTION; notifyEvent(beforeRetentionEvent, docModel, options, null, null, true, false); doc.setRetainUntil(retainUntil); docModel = readModel(doc); String afterRetentionEvent = currentIndeterminate ? DocumentEventTypes.AFTER_SET_RETENTION : DocumentEventTypes.AFTER_EXTEND_RETENTION; notifyEvent(afterRetentionEvent, docModel, options, null, null, true, false); }

Target:
public void setRetainUntil(DocumentRef docRef, Calendar retainUntil, String comment) throws PropertyException { Document doc = resolveReference(docRef); checkPermission(doc, READ); if (!doc.isRecord()) { throw new PropertyException("Document is not a record"); } Calendar current = doc.getRetainUntil(); if (current!=null && retainUntil!=null && current.compareTo(retainUntil) == 0) { return; } checkPermission(doc, SET_RETENTION); Map<String, Serializable> options = new HashMap<>(); options.put(CoreEventConstants.RETAIN_UNTIL, retainUntil); boolean retainUntilIndeterminate = retainUntil == null || RETAIN_UNTIL_INDETERMINATE.compareTo(retainUntil) == 0; options.put("comment", retainUntilIndeterminate ? "" : retainUntil.toInstant().toString()); DocumentModel docModel = readModel(doc); boolean currentIndeterminate = current == null || RETAIN_UNTIL_INDETERMINATE.compareTo(current) == 0; String beforeRetentionEvent = currentIndeterminate ? DocumentEventTypes.BEFORE_SET_RETENTION : DocumentEventTypes.BEFORE_EXTEND_RETENTION; notifyEvent(beforeRetentionEvent, docModel, options, null, null, true, false); doc.setRetainUntil(retainUntil); docModel = readModel(doc); String afterRetentionEvent = currentIndeterminate ? DocumentEventTypes.AFTER_SET_RETENTION : DocumentEventTypes.AFTER_EXTEND_RETENTION; notifyEvent(afterRetentionEvent, docModel, options, null, null, true, false); }
Source:
public void debug(String message, Object... objects) { LOG.warn(message, objects); }

Target:
public void debug(String message, Object... objects) { LOG.debug(message, objects); }
Source:
private TreeViewer createTreeViewer(final Composite parent) { final int style = SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER; tree = SWTUtil.createFilteredTree(parent, style, new EObjectFilter()); try { Method setQuickSelection = FilteredTree.class.getMethod("setQuickSelectionMode", Boolean.TYPE); if (setQuickSelection != null) { setQuickSelection.invoke(tree, true); } } catch (NoSuchMethodException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (IllegalArgumentException e) { } catch (InvocationTargetException e) { } final TreeViewer viewer = tree.getViewer(); final GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); viewer.getControl().setLayoutData(gridData); viewer.getTree().setHeaderVisible(false); viewer.getTree().setLinesVisible(false); viewer.setContentProvider(new SessionContentProvider()); viewer.setLabelProvider(new AdapterFactoryLabelProvider(ViewHelper.INSTANCE.createAdapterFactory())); return viewer; }

Target:
private TreeViewer createTreeViewer(final Composite parent) { final int style = SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER; tree = SWTUtil.createFilteredTree(parent, style, new EObjectFilter()); ReflectionHelper.invokeMethodWithoutException(tree, "setQuickSelectionMode", new Class[] { Boolean.TYPE }, new Object[] { true }); final TreeViewer viewer = tree.getViewer(); final GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); viewer.getControl().setLayoutData(gridData); viewer.getTree().setHeaderVisible(false); viewer.getTree().setLinesVisible(false); viewer.setContentProvider(new SessionContentProvider()); viewer.setLabelProvider(new AdapterFactoryLabelProvider(ViewHelper.INSTANCE.createAdapterFactory())); return viewer; }
Source:
public void addBuildVersionInfo() { String versionName = ""; int buildVersion = 0; PackageManager packageManager = this.getActivity().getPackageManager(); String packageName = this.getActivity().getPackageName(); try { versionName = packageManager.getPackageInfo(packageName, 0).versionName; ApplicationInfo ai = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA); buildVersion = ai.metaData.getInt("buildVersion"); } catch (PackageManager.NameNotFoundException e) { mPresenter.logException("Failed to load meta-data, NameNotFound: " + e.getMessage()); } catch (NullPointerException e) { mPresenter.logException("Failed to load meta-data, NullPointer: " + e.getMessage()); } TextView appName = root.findViewById(R.id.frag_settings_app_name_tv); TextView version = root.findViewById(R.id.frag_settings_version_tv); appName.setText(getResources().getString(R.string.app_name)); version.setText(versionName + " Build: " + buildVersion); }

Target:
public void addBuildVersionInfo() { String versionName = ""; int buildVersion = 0; PackageManager packageManager = this.getActivity().getPackageManager(); String packageName = this.getActivity().getPackageName(); try { versionName = packageManager.getPackageInfo(packageName, 0).versionName; ApplicationInfo ai = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA); buildVersion = ai.metaData.getInt("buildVersion"); } catch (PackageManager.NameNotFoundException e) { mPresenter.logException("Failed to load meta-data, NameNotFound: " + e.getMessage()); } catch (NullPointerException e) { mPresenter.logException("Failed to load meta-data, NullPointer: " + e.getMessage()); } TextView appName = root.findViewById(R.id.frag_settings_app_name_tv); TextView version = root.findViewById(R.id.frag_settings_version_tv); appName.setText(getResources().getString(R.string.app_name)); version.setText(versionName + getContext().getString(R.string.frag_settings_build) + buildVersion); }