auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ValidationResult validate(Object value) { if (!(value instanceof IconWithOsDefault)) { throw new IllegalArgumentException("Illegal argument type: " + (value == null ? "null" : value.getClass().toString())); } <START> final IconWithOsDefault iconWithOsDefault = (IconWithOsDefault) value; <END> return iconWithOsDefault.getValidationResult(); }</code><technical_language>iconWithOsDefault null validation finish yet, good return some validation failure instead of null null fail NPE later</technical_language>

Target:
public ValidationResult validate(Object value) { if (!(value instanceof IconWithOsDefault)) { throw new IllegalArgumentException("Illegal argument type: " + (value == null ? "null" : value.getClass().toString())); } final IconWithOsDefault iconWithOsDefault = (IconWithOsDefault) value; if (iconWithOsDefault.getValidationResult() == null) { UIConstants constants = ConstantsManager.getInstance().getConstants(); return ValidationResult.fail(constants.iconNotValidatedYet()); } return iconWithOsDefault.getValidationResult(); }
Source:
<code>public void image(Attributes attributes, String url) { assertOpenBlock(); try { currentBlock.write('!'); writeAttributes(attributes); if (url != null) <START> { <END> currentBlock.write(url); } currentBlock.write('!'); } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>consider moving this null check write() method, guard in other places well</technical_language>

Target:
public void image(Attributes attributes, String url) { assertOpenBlock(); try { currentBlock.write('!'); writeAttributes(attributes); currentBlock.write(url); currentBlock.write('!'); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>public Query optimizeQuery(Query q, NullCheckCategory category) { if (category == NullCheckCategory.NOT_NULL) { for (InputColumn<?> col : columns) { Column column = col.getPhysicalColumn(); if (column == null) { throw new IllegalStateException("Cannot optimize on non-physical column: " + col); } q.where(column, OperatorType.DIFFERENT_FROM, null); if (considerEmptyStringAsNull && col.getDataType() == String.class) { <START> q.where(column, OperatorType.LIKE, "%"); <END> } } } else { List<FilterItem> filterItems = new ArrayList<>(); for (InputColumn<?> col : columns) { Column column = col.getPhysicalColumn(); if (column == null) { throw new IllegalStateException("Cannot optimize on non-physical column: " + col); } SelectItem selectItem = new SelectItem(column); FilterItem fi1 = new FilterItem(selectItem, OperatorType.EQUALS_TO, null); filterItems.add(fi1); if (considerEmptyStringAsNull && col.getDataType() == String.class) { FilterItem fi2 = new FilterItem(selectItem, OperatorType.EQUALS_TO, ""); filterItems.add(fi2); } } q.where(new FilterItem(filterItems.toArray(new FilterItem[filterItems.size()]))); } return q; }</code><technical_language>I (I wrong) '%' match empty string, this wrong</technical_language>

Target:
public Query optimizeQuery(Query q, NullCheckCategory category) { if (category == NullCheckCategory.NOT_NULL) { for (InputColumn<?> col : columns) { Column column = col.getPhysicalColumn(); if (column == null) { throw new IllegalStateException("Cannot optimize on non-physical column: " + col); } q.where(column, OperatorType.DIFFERENT_FROM, null); if (considerEmptyStringAsNull && col.getDataType() == String.class) { q.where(column, OperatorType.DIFFERENT_FROM, ""); } } } else { List<FilterItem> filterItems = new ArrayList<>(); for (InputColumn<?> col : columns) { Column column = col.getPhysicalColumn(); if (column == null) { throw new IllegalStateException("Cannot optimize on non-physical column: " + col); } SelectItem selectItem = new SelectItem(column); FilterItem fi1 = new FilterItem(selectItem, OperatorType.EQUALS_TO, null); filterItems.add(fi1); if (considerEmptyStringAsNull && col.getDataType() == String.class) { FilterItem fi2 = new FilterItem(selectItem, OperatorType.EQUALS_TO, ""); filterItems.add(fi2); } } q.where(new FilterItem(filterItems.toArray(new FilterItem[filterItems.size()]))); } return q; }
Source:
<code>public void createOrUpdateNetworks(final Guid vmId, final List<NicWithLogicalNetworks> nicsWithLogicalNetworks) { AsyncQuery getVmNicsQuery = new AsyncQuery(); getVmNicsQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object result) { List<VmNetworkInterface> createdFromTemplate = (List<VmNetworkInterface>) result; if (createdFromTemplate.size() == 0) { createNetworks(vmId, nicsWithLogicalNetworks); } else { ArrayList<VdcActionParametersBase> parameters = new ArrayList<VdcActionParametersBase>(); for (VmNetworkInterface created : createdFromTemplate) { for (NicWithLogicalNetworks edited : nicsWithLogicalNetworks) { boolean sameNic = edited.getNetworkInterface().getName().equals(created.getName()); <START> boolean assignedNetworkChanged = <END> !((created.getNetworkName() == null && edited.getNetworkInterface() .getNetworkName() == null) || (created.getNetworkName() != null && created.getNetworkName() .equals(edited.getNetworkInterface().getNetworkName()))); if (sameNic && assignedNetworkChanged) { created.setNetworkName(edited.getNetworkInterface().getNetworkName()); parameters.add(new AddVmInterfaceParameters(vmId, created)); break; } } } updateNetworksFromParams(vmId, parameters); } } }; AsyncDataProvider.getVmNicList(getVmNicsQuery, vmId); }</code><technical_language>logic a bit complex, extract "created.getNetworkName().equals(edited.getNetworkInterface().getNetworkName())" a variable - 'sameNetwork'</technical_language>

Target:
public void createOrUpdateNetworks(final Guid vmId, final List<NicWithLogicalNetworks> nicsWithLogicalNetworks) { AsyncQuery getVmNicsQuery = new AsyncQuery(); getVmNicsQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object result) { List<VmNetworkInterface> createdFromTemplate = (List<VmNetworkInterface>) result; if (createdFromTemplate.size() == 0) { createNetworks(vmId, nicsWithLogicalNetworks); } else { ArrayList<VdcActionParametersBase> parameters = new ArrayList<VdcActionParametersBase>(); for (VmNetworkInterface created : createdFromTemplate) { for (NicWithLogicalNetworks edited : nicsWithLogicalNetworks) { boolean sameNic = edited.getNetworkInterface().getName().equals(created.getName()); boolean bothNetworksNull = created.getNetworkName() == null && edited.getNetworkInterface().getNetworkName() == null; boolean sameNetworkNames = created.getNetworkName() != null && created.getNetworkName().equals(edited.getNetworkInterface().getNetworkName()); boolean assignedNetworkChanged = !(bothNetworksNull || sameNetworkNames); if (sameNic && assignedNetworkChanged) { created.setNetworkName(edited.getNetworkInterface().getNetworkName()); parameters.add(new AddVmInterfaceParameters(vmId, created)); break; } } } updateNetworksFromParams(vmId, parameters); } } }; AsyncDataProvider.getVmNicList(getVmNicsQuery, vmId); }
Source:
<code>public SpatialDimensionRowFormatter(List<SpatialDimensionSchema> spatialDimensions) { this.spatialDimensionMap = Maps.newHashMap(); for (SpatialDimensionSchema spatialDimension : spatialDimensions) { <START> this.spatialDimensionMap.put(spatialDimension.getDimName(), spatialDimension); <END> } this.spatialPartialDimNames = Sets.newHashSet( Iterables.concat( Lists.transform( spatialDimensions, new Function<SpatialDimensionSchema, List<String>>() { @Override public List<String> apply(SpatialDimensionSchema input) { return input.getDims(); } } ) ) ); }</code><technical_language>Throw exception if spatialDimensionMap includes dimName</technical_language>

Target:
public SpatialDimensionRowFormatter(List<SpatialDimensionSchema> spatialDimensions) { this.spatialDimensionMap = Maps.newHashMap(); for (SpatialDimensionSchema spatialDimension : spatialDimensions) { if (this.spatialDimensionMap.put(spatialDimension.getDimName(), spatialDimension) != null) { throw new ISE("Duplicate spatial dimension names found! Check your schema yo!"); } } this.spatialPartialDimNames = Sets.newHashSet( Iterables.concat( Lists.transform( spatialDimensions, new Function<SpatialDimensionSchema, List<String>>() { @Override public List<String> apply(SpatialDimensionSchema input) { return input.getDims(); } } ) ) ); }
Source:
<code>public void onMapReady(@NonNull final MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.SATELLITE_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { mapboxMap.setLatLngBoundsForCameraTarget(AUSTRALIA_BOUNDS); mapboxMap.setMinZoomPreference(2); <START> showBoundsArea(); <END> showCrosshair(); } }); }</code><technical_language>Fixed java @Override public void onMapReady(@NonNull final MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; mapboxMap.setStyle(Style.SATELLITE_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { // Set bounds Australia mapboxMap.setLatLngBoundsForCameraTarget(AUSTRALIA_BOUNDS); mapboxMap.setMinZoomPreference(2); // Visualise bounds area showBoundsArea(style); showCrosshair(); } }); } private void showBoundsArea(@NonNull Style loadedMapStyle) { GeoJsonSource geoJsonSource = new GeoJsonSource("source-id", FeatureCollection.fromFeatures(new Feature[] { Feature.fromGeometry(Point.fromLngLat(AUSTRALIA_BOUNDS.getNorthWest().getLongitude(), AUSTRALIA_BOUNDS.getNorthWest().getLatitude())), Feature.fromGeometry(Point.fromLngLat(AUSTRALIA_BOUNDS.getNorthEast().getLongitude(), AUSTRALIA_BOUNDS.getNorthWest().getLatitude())), Feature.fromGeometry(Point.fromLngLat(AUSTRALIA_BOUNDS.getSouthEast().getLongitude(), AUSTRALIA_BOUNDS.getNorthWest().getLatitude())), Feature.fromGeometry(Point.fromLngLat(AUSTRALIA_BOUNDS.getSouthWest().getLongitude(), AUSTRALIA_BOUNDS.getNorthWest().getLatitude())) })); loadedMapStyle.addSource(geoJsonSource); FillLayer boundsAreaFillLayer = new FillLayer("layer-id", "source-id"); boundsAreaFillLayer.setProperties( fillColor(Color.RED), fillOpacity(.25f) ); loadedMapStyle.addLayer(boundsAreaFillLayer); }</technical_language>

Target:
public void onMapReady(@NonNull final MapboxMap mapboxMap) { mapboxMap.setStyle(Style.SATELLITE_STREETS, new Style.OnStyleLoaded() { @Override public void onStyleLoaded(@NonNull Style style) { mapboxMap.setLatLngBoundsForCameraTarget(RESTRICTED_BOUNDS_AREA); mapboxMap.setMinZoomPreference(2); showBoundsArea(style); showCrosshair(); } }); }
Source:
<code><START> public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) { <END> Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("X-Custom-Header", "application/json"); APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent() .withHeaders(headers); if (input != null && input.getBody() != null) { try { Request request = mapper.readValue(input.getBody(), Request.class); try { String s = parseWDLFile(request.getUri(), request.getBranch(), request.getDescriptorRelativePathInGit()); return response.withStatusCode(HttpURLConnection.HTTP_OK).withBody(s); } catch (IOException e) { e.printStackTrace(); return response.withBody("Could not clone repository to temporary directory").withStatusCode(HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (GitAPIException e) { e.printStackTrace(); return response.withBody("Could not clone Git repository").withStatusCode(HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (JsonProcessingException e) { e.printStackTrace(); return response.withBody("Could not process request").withStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); } } else { return response.withBody("No body in request").withStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); } }</code><technical_language>missing @override, if applies getResponse is public</technical_language>

Target:
public APIGatewayProxyResponseEvent handleRequest( final APIGatewayProxyRequestEvent input, final Context context) { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("X-Custom-Header", "application/json"); APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent().withHeaders(headers); if (input != null && input.getBody() != null) { try { LanguageParsingRequest request = mapper.readValue(input.getBody(), LanguageParsingRequest.class); try { String s = parseWdlFile( request.getUri(), request.getBranch(), request.getDescriptorRelativePathInGit(), request); return response.withStatusCode(HttpURLConnection.HTTP_OK).withBody(s); } catch (IOException e) { e.printStackTrace(); return response .withBody("Could not clone repository to temporary directory") .withStatusCode(HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (GitAPIException e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exceptionAsString = sw.toString(); return response .withBody(exceptionAsString) .withStatusCode(HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (IOException e) { e.printStackTrace(); return response .withBody("Could not process request") .withStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); } } else { return response .withBody("No body in request") .withStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); } }
Source:
<code>public static ZCallPedFile fromFile(final File pedFile, final File mapFile) throws FileNotFoundException { final String[] pedFileFields = IOUtil.slurp(pedFile).split(" "); final String[] mapFileLines = IOUtil.slurpLines(mapFile).toArray(new String[0]); final ZCallPedFile zCallPedFile = new ZCallPedFile(); for (int i = 0; i < mapFileLines.length; i++) { final int index = (i * 2) + OFFSET; final String alleles = pedFileFields[index] + pedFileFields[index + 1]; <START> zCallPedFile.addAllele(mapFileLines[i].split("\t")[1], alleles); <END> } return zCallPedFile; }</code><technical_language>map is whitespace separated, split tabs</technical_language>

Target:
public static ZCallPedFile fromFile(final File pedFile, final File mapFile) throws FileNotFoundException { final String[] pedFileLines = IOUtil.slurpLines(pedFile).toArray(new String[0]); if (pedFileLines.length > 1) { throw new PicardException("Only single-sample .ped files are supported."); } final String[] pedFileFields = IOUtil.slurp(pedFile).split("\\s"); final String[] mapFileLines = IOUtil.slurpLines(mapFile).toArray(new String[0]); final ZCallPedFile zCallPedFile = new ZCallPedFile(); for (int i = 0; i < mapFileLines.length; i++) { final int index = (i * 2) + OFFSET; if (pedFileFields[index].length() != 1 || pedFileFields[index + 1].length() != 1) { throw new PicardException("Malformed file: each allele should be a single character."); } final String alleles = pedFileFields[index] + pedFileFields[index + 1]; zCallPedFile.addAllele(mapFileLines[i].split("\\s")[1], alleles); } return zCallPedFile; }
Source:
<code>public OncotreeMappingsResp getMappings( @RequestParam(value="vocabularyId", required=false) String vocabularyId, @RequestParam(value="conceptId", required=false) String conceptId, @RequestParam(value="histologyCode", required=false) String histologyCode, @RequestParam(value="siteCode", required=false) String siteCode ) { if( !validateMappingParameters(vocabularyId, conceptId, histologyCode, siteCode) ){ throw new RuntimeException("Your query parameters, vocabularyId: " + vocabularyId + ", conceptId: " + conceptId + ", histologyCode: " + histologyCode + ", siteCode: " + siteCode + " are not valid. Please refer to the documentation"); } <START> MSKConcept mskConcept = crosswalkRepository.queryCVS(vocabularyId, conceptId, histologyCode, siteCode); <END> return extractOncotreeMappings( mskConcept ); }</code><technical_language>This web service api relays calls crosswalkRepository filters response</technical_language>

Target:
public OncotreeMappingsResp getMappings( @RequestParam(value="vocabularyId", required=false) String vocabularyId, @RequestParam(value="conceptId", required=false) String conceptId, @RequestParam(value="histologyCode", required=false) String histologyCode, @RequestParam(value="siteCode", required=false) String siteCode ) { if( !validateMappingParameters(vocabularyId, conceptId, histologyCode, siteCode) ){ throw new InvalidOncotreeMappingsParameters("Your query parameters, vocabularyId: " + vocabularyId + ", conceptId: " + conceptId + ", histologyCode: " + histologyCode + ", siteCode: " + siteCode + " are not valid. Please refer to the documentation"); } MSKConcept mskConcept = crosswalkRepository.queryCVS(vocabularyId, conceptId, histologyCode, siteCode); return extractOncotreeMappings( mskConcept ); }
Source:
<code>public void testGetApplicationReportsForProjectModelSortedByPriority() { ProjectModel projectModel = context.getFramed().addVertex(null, ProjectModel.class); <START> ApplicationReportModel m1 = context.getFramed().addVertex(null, ApplicationReportModel.class); <END> m1.setReportName("m1"); m1.setReportPriority(100); ApplicationReportModel m2 = context.getFramed().addVertex(null, ApplicationReportModel.class); m2.setReportName("m2"); m2.setReportPriority(200); ApplicationReportModel m3 = context.getFramed().addVertex(null, ApplicationReportModel.class); m3.setReportName("m3"); m3.setReportPriority(300); ApplicationReportModel m4 = context.getFramed().addVertex(null, ApplicationReportModel.class); m4.setReportName("m4"); m4.setReportPriority(400); ApplicationReportModel m5 = context.getFramed().addVertex(null, ApplicationReportModel.class); m5.setReportName("m5"); m5.setReportPriority(500); MainNavigationIndexModel idx1 = context.getFramed().addVertex(null, MainNavigationIndexModel.class); idx1.addProjectModel(projectModel); MainNavigationIndexModel idx2 = context.getFramed().addVertex(null, MainNavigationIndexModel.class); m1.setProjectModel(projectModel); m2.setProjectModel(projectModel); m3.setProjectModel(projectModel); m4.setProjectModel(projectModel); MainNavigationIndexModel result = service.getNavigationIndexForProjectModel(projectModel); Assert.assertNotNull(result); Assert.assertEquals(idx1.asVertex().getId(), result.asVertex().getId()); }</code><technical_language>calls replaced a GraphService...create() :)</technical_language>

Target:
public void testGetApplicationReportsForProjectModelSortedByPriority() { ProjectModel projectModel = projectModelService.create(); ApplicationReportModel m1 = applicationReportModelService.create(); m1.setReportName("m1"); m1.setReportPriority(100); ApplicationReportModel m2 = applicationReportModelService.create(); m2.setReportName("m2"); m2.setReportPriority(200); ApplicationReportModel m3 = applicationReportModelService.create(); m3.setReportName("m3"); m3.setReportPriority(300); ApplicationReportModel m4 = applicationReportModelService.create(); m4.setReportName("m4"); m4.setReportPriority(400); ApplicationReportModel m5 = applicationReportModelService.create(); m5.setReportName("m5"); m5.setReportPriority(500); MainNavigationIndexModel idx1 = mainNavigationIndexModelService.create(); idx1.addProjectModel(projectModel); MainNavigationIndexModel idx2 = mainNavigationIndexModelService.create(); m1.setProjectModel(projectModel); m2.setProjectModel(projectModel); m3.setProjectModel(projectModel); m4.setProjectModel(projectModel); MainNavigationIndexModel result = mainNavigationIndexModelService .getNavigationIndexForProjectModel(projectModel); Assert.assertNotNull(result); Assert.assertEquals(idx1.asVertex().getId(), result.asVertex().getId()); }
Source:
<code>public void saveStateShouldBeSuccessSaving() { given(modelMapper.map(stateDTO, StateEntity.class)).willReturn(stateEntity); given(applicationsRepository.findOne(FIRST_ID)).willReturn(applicationEntity); given(statesRepository.save(stateEntity)).willReturn(stateEntity); <START> Long expectedId = statesService.saveState(stateDTO, FIRST_ID); <END> assertThat(stateEntity, notNullValue()); assertThat(stateEntity.getCreationDate(), greaterThanOrEqualTo(now)); assertThat(stateEntity.getApplicationEntity(), equalTo(applicationEntity)); assertThat(stateEntity.getId(), equalTo(expectedId)); then(applicationsRepository).should((times(AT_ONE_TIME))).findOne(FIRST_ID); then(statesRepository).should(times(AT_ONE_TIME)).save(stateEntity); }</code><technical_language>rename variable returned is expected</technical_language>

Target:
public void saveStateShouldBeSuccessSaving() { given(modelMapper.map(stateDTO, StateEntity.class)).willReturn(firstStateEntity); given(applicationsRepository.findOne(SECOND_ID)).willReturn(secondApplicationEntity); given(statesRepository.save(firstStateEntity)).willReturn(firstStateEntity); Long resultId = statesService.saveState(stateDTO, SECOND_ID); assertStateEntityWhenSavingStateEntity(firstStateEntity, savedStateEntity); assertThat(resultId, notNullValue()); assertThat(resultId, equalTo(FIRST_ID)); then(applicationsRepository).should().findOne(SECOND_ID); then(statesRepository).should().save(firstStateEntity); }
Source:
<code>public BPMNDiagram getBpmnDiagram() { BPMNDiagram bpmnDiagram = di.createBPMNDiagram(); bpmnDiagram.setId(process.getId()); BPMNPlane bpmnPlane = di.createBPMNPlane(); bpmnDiagram.setPlane(bpmnPlane); <START> List<DiagramElement> planeElement = bpmnPlane.getPlaneElement(); <END> childElements.values().forEach(p -> { BPMNShape shape = p.getShape(); BPMNEdge edge = p.getEdge(); if (shape != null) { planeElement.add(shape); } if (edge != null) { planeElement.add(edge); } }); childElements.values().stream().flatMap(e -> e.getChildElements().stream()).forEach(p -> { BPMNShape shape = p.getShape(); BPMNEdge edge = p.getEdge(); if (shape != null) { planeElement.add(shape); } if (edge != null) { planeElement.add(edge); } }); return bpmnDiagram; }</code><technical_language>mmm for brainstorming a bit... I need change here. in way, planeElement is mutable, foreach add elements in list is intermediate stream operation, achieve laziness, this concurrency is guaranteed if code is run in parallel some point, sense? other hand, working Streams here, address laziness in code ensuring intermediate functions behave pure functions - Streams ensure purity of functions if ensure arguments (childElements) mutable, this point happens. right? want map/collect items in a new list, I anonymous functions achieve this do require variable enclosing parent. laziness guaranteed well. This this? -> Removing planeElement instance, creating a new static function p argument returns a Stream<DiagramElement>, shape and/or edge (just creating Stream for array work). This perform a flatMap for childElements.values() Stream<DiagramElement>, collect for terminate function. This mapping collection operations in this code guarantee purity of functions, laziness concurrency (thread-safe). replicating code foeach, creating static function somewhere</technical_language>

Target:
public BPMNDiagram getBpmnDiagram() { bpmnDiagram.getPlane().setBpmnElement(process); return bpmnDiagram; }
Source:
<code>public void testPrioritySequenceNumbers() throws Exception { final RemoteInputChannel channel = buildInputGateAndGetChannel(); sendBuffersAndBarrier(channel, 0); <START> assertGetNextBufferSequenceNumbers(channel, 2, 0, 1, 3, 4); <END> }</code><technical_language>inlined. I aim a test structured in _given_, _when_, _then_ structure I this change, managed get (much before)</technical_language>

Target:
public void testPrioritySequenceNumbers() throws Exception { int sequenceNumber = 0; int bufferSize = 1; final RemoteInputChannel channel = buildInputGateAndGetChannel(sequenceNumber); sendBuffer(channel, sequenceNumber++, bufferSize++); sendBuffer(channel, sequenceNumber++, bufferSize++); sendBarrier(channel, sequenceNumber++, 0); sendBuffer(channel, sequenceNumber++, bufferSize++); sendBuffer(channel, sequenceNumber++, bufferSize++); assertGetNextBufferSequenceNumbers(channel, 2, 0, 1, 3, 4); }
Source:
<code>public void testOnResultCalledInFragment() { FragmentStartedActivity_.intent(fragment).startForResult(AwaitingResultFragment.FIRST_REQUEST); <START> ShadowActivity a = (ShadowActivity) ShadowExtractor.extract(fragment.getActivity()); <END> a.receiveResult(FragmentStartedActivity_.intent(fragment).get(), Activity.RESULT_OK, new Intent()); assertThat(fragment.onResultCalled).isTrue(); }</code><technical_language>In other places static import extract. I consistent</technical_language>

Target:
public void testOnResultCalledInFragment() { FragmentStartedActivity_.intent(fragment).startForResult(AwaitingResultFragment.FIRST_REQUEST); ShadowActivity a = (ShadowActivity) extract(fragment.getActivity()); a.receiveResult(FragmentStartedActivity_.intent(fragment).get(), Activity.RESULT_OK, new Intent()); assertThat(fragment.onResultCalled).isTrue(); }
Source:
<code>public void testCorrectBehaviourOfShortDescription() { final String id = "EOF"; final String shortDescription = TokenUtils.getShortDescription(id); <START> assertNotNull(shortDescription); <END> }</code><technical_language>verify a specific value</technical_language>

Target:
public void testCorrectBehaviourOfShortDescription() { final String id = "EOF"; final String shortDescription = TokenUtils.getShortDescription(id); assertEquals("The end of file token.", shortDescription); }
Source:
<code>public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { changesMadeSinceLastSave = false; <START> currentMessageBuilder.setHighPriority(isHighPriority); <END> setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } }</code><technical_language>this in createMessageBuilder</technical_language>

Target:
public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { changesMadeSinceLastSave = false; setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } }
Source:
<code>public boolean isEnsembleAdheringToPlacementPolicy(List<BookieSocketAddress> ensembleList, int writeQuorumSize, int ackQuorumSize) { int ensembleSize = ensembleList.size(); int minNumRacksPerWriteQuorumForThisEnsemble = Math.min(writeQuorumSize, minNumRacksPerWriteQuorum); HashSet<String> racksOrRegionsInQuorum = new HashSet<String>(); BookieSocketAddress bookie; for (int i = 0; i < ensembleList.size(); i++) { racksOrRegionsInQuorum.clear(); for (int j = 0; j < writeQuorumSize; j++) { <START> bookie = ensembleList.get((ensembleSize + i + j) % ensembleSize); <END> try { racksOrRegionsInQuorum.add(knownBookies.get(bookie).getNetworkLocation()); } catch (Exception e) { LOG.warn("Received exception while trying to get network location of bookie: {}", bookie, e); } } if (racksOrRegionsInQuorum.size() < minNumRacksPerWriteQuorumForThisEnsemble) { return false; } } return true; }</code><technical_language>ensembleSize difference in (ensembleSize + i + j) equation? moding ensembleSize</technical_language>

Target:
public boolean isEnsembleAdheringToPlacementPolicy(List<BookieSocketAddress> ensembleList, int writeQuorumSize, int ackQuorumSize) { int ensembleSize = ensembleList.size(); int minNumRacksPerWriteQuorumForThisEnsemble = Math.min(writeQuorumSize, minNumRacksPerWriteQuorum); HashSet<String> racksOrRegionsInQuorum = new HashSet<String>(); BookieSocketAddress bookie; for (int i = 0; i < ensembleList.size(); i++) { racksOrRegionsInQuorum.clear(); for (int j = 0; j < writeQuorumSize; j++) { bookie = ensembleList.get((i + j) % ensembleSize); try { racksOrRegionsInQuorum.add(knownBookies.get(bookie).getNetworkLocation()); } catch (Exception e) { LOG.warn("Received exception while trying to get network location of bookie: {}", bookie, e); } } if (racksOrRegionsInQuorum.size() < minNumRacksPerWriteQuorumForThisEnsemble) { return false; } } return true; }
Source:
<code>public void createProjectFromXML_checkGoodName() throws Failure, IOException { final String badName = "calvin@jenkins"; final String xml = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<!DOCTYPE project[\n" + " <!ENTITY foo SYSTEM \"file:/ "]>\n" + "<project>\n" + " <actions/>\n" + " <description>&foo;</description>\n" + " <keepDependencies>false</keepDependencies>\n" + " <properties/>\n" + " <scm class=\"hudson.scm.NullSCM\"/>\n" + " <canRoam>true</canRoam>\n" + " <triggers/>\n" + " <builders/>\n" + " <publishers/>\n" + " <buildWrappers/>\n" + "</project>"; <START> try { r.jenkins.createProjectFromXML(badName, new ByteArrayInputStream(xml.getBytes())); fail("@ is an unsafe character therefore creating a project named " + badName + " should have failed"); } catch (Failure x) { assertEquals(x.getMessage(), Messages.Hudson_UnsafeChar("@")); } <END> }</code><technical_language>JUnit assertThrows is (JUnit 4.13) types of assertion checks cleaner. Learned new here, [Failure class](<LINK_0> is a Jenkins exception class</technical_language>

Target:
public void createProjectFromXML_checkGoodName() throws Failure, IOException { final String badName = "calvin@jenkins"; final String xml = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<!DOCTYPE project[\n" + " <!ENTITY foo SYSTEM \"file:/ "]>\n" + "<project>\n" + " <actions/>\n" + " <description>&foo;</description>\n" + " <keepDependencies>false</keepDependencies>\n" + " <properties/>\n" + " <scm class=\"hudson.scm.NullSCM\"/>\n" + " <canRoam>true</canRoam>\n" + " <triggers/>\n" + " <builders/>\n" + " <publishers/>\n" + " <buildWrappers/>\n" + "</project>"; Failure exception = assertThrows(Failure.class, () -> { r.jenkins.createProjectFromXML(badName, new ByteArrayInputStream(xml.getBytes())); }); assertEquals(exception.getMessage(), Messages.Hudson_UnsafeChar("@")); }
Source:
<code>public void onReceive(Context context, Intent intent) { ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conn.getActiveNetworkInfo(); <START> if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { <END> setWifiReceiverComponent(false, context); Intent serviceIntent = new Intent(context, KeyserverSyncAdapterService.class); serviceIntent.setAction(KeyserverSyncAdapterService.ACTION_UPDATE_ALL); context.startService(serviceIntent); } }</code><technical_language>Docs (<LINK_0> check isConnected() initia..</technical_language>

Target:
public void onReceive(Context context, Intent intent) { ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conn.getActiveNetworkInfo(); boolean isTypeWifi = (networkInfo.getType() == ConnectivityManager.TYPE_WIFI); boolean isConnected = networkInfo.isConnected(); if (isTypeWifi && isConnected) { setWifiReceiverComponent(false, context); Intent serviceIntent = new Intent(context, KeyserverSyncAdapterService.class); serviceIntent.setAction(KeyserverSyncAdapterService.ACTION_SYNC_NOW); context.startService(serviceIntent); } }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MifosBaseActivity) getActivity()).getActivityComponent().inject(this); <START> if (getArguments() != null) { <END> } if (savedInstanceState != null) { mSheet = (IndividualCollectionSheet) savedInstanceState.get( Constants.EXTRA_COLLECTION_INDIVIDUAL); showCollectionSheetViews(mSheet); } setHasOptionsMenu(true); }</code><technical_language>Remove this block, if adding argument in constructor</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MifosBaseActivity) getActivity()).getActivityComponent().inject(this); if (savedInstanceState != null) { sheet = (IndividualCollectionSheet) savedInstanceState.get( Constants.EXTRA_COLLECTION_INDIVIDUAL); showCollectionSheetViews(sheet); } setHasOptionsMenu(true); }
Source:
<code>public void setMessage (String message) { checkWidget (); if (message == null) error (SWT.ERROR_NULL_ARGUMENT); this.message = message; <START> if (GTK.GTK_VERSION >= OS.VERSION (3, 4, 0)) { <END> if ((style & SWT.SINGLE) != 0) { byte buffer = Converter.wcsToMbcs (message, true); GTK.gtk_entry_set_placeholder_text (handle, buffer); return; } } redraw (false); }</code><technical_language>SWT requires 3.4 guard removed</technical_language>

Target:
public void setMessage (String message) { checkWidget (); if (message == null) error (SWT.ERROR_NULL_ARGUMENT); this.message = message; if ((style & SWT.SINGLE) != 0) { byte buffer = Converter.wcsToMbcs (message, true); GTK.gtk_entry_set_placeholder_text (handle, buffer); return; } redraw (false); }
Source:
<code><START> public boolean allGoalFilesExist() { <END> boolean allExist = true; EntityPanel entityPanel = getController().getMainView().getMainPanel().getEntityPanel(); int numRows = entityPanel.getBotTableModel().getRowCount(); for(int i = 0; i < numRows && allExist; i++) { String goalFile = "" + entityPanel.getBotTable().getValueAt(i, 2); allExist = AgentFileChecker.fileNameExists(goalFile); } numRows = entityPanel.getEPartnerTableModel().getRowCount(); for(int i = 0; i < numRows && allExist; i++) { String goalFile = "" + entityPanel.getBotTable().getValueAt(i, 2); allExist = AgentFileChecker.fileNameExists(goalFile); } return allExist; }</code><technical_language>model for reading goal file names</technical_language>

Target:
public boolean allGoalFilesExist() { boolean allExist = true; BW4TClientConfig model = this.getModel(); List<BotConfig> botList = model.getBots(); for(int i = 0; i < botList.size() && allExist; i++) { allExist = allExist && AgentFileChecker.fileNameExists(botList.get(i).getFileName()); } List<EPartnerConfig> epartnerList = model.getEpartners(); for(int i = 0; i < epartnerList.size() && allExist; i++) { allExist = allExist && AgentFileChecker.fileNameExists(epartnerList.get(i).getFileName()); } return allExist; }
Source:
<code>public T executeAsBlocking() { try { final GetResolver<T> getResolver; if (explicitGetResolver != null) { getResolver = explicitGetResolver; } else { final ContentResolverTypeMapping<T> typeMapping = storIOContentResolver.internal().typeMapping(type); if (typeMapping == null) { throw new IllegalStateException("This type does not have type mapping: " + "type = " + type + "," + "ContentProvider was not touched by this operation, please add type mapping for this type"); } getResolver = typeMapping.getResolver(); } final Cursor cursor = getResolver.performGet(storIOContentResolver, query); try { final int count = cursor.getCount(); if (count == 0) { return null; } <START> cursor.moveToNext(); <END> return getResolver.mapFromCursor(cursor); } finally { cursor.close(); } } catch (Exception exception) { throw new StorIOException(exception); } }</code><technical_language>moveToFirst(), in case of broken initial position of Cursor returned user's GetResolver</technical_language>

Target:
public T executeAsBlocking() { try { final GetResolver<T> getResolver; if (explicitGetResolver != null) { getResolver = explicitGetResolver; } else { final ContentResolverTypeMapping<T> typeMapping = storIOContentResolver.internal().typeMapping(type); if (typeMapping == null) { throw new IllegalStateException("This type does not have type mapping: " + "type = " + type + "," + "ContentProvider was not touched by this operation, please add type mapping for this type"); } getResolver = typeMapping.getResolver(); } final Cursor cursor = getResolver.performGet(storIOContentResolver, query); try { final int count = cursor.getCount(); if (count == 0) { return null; } cursor.moveToFirst(); return getResolver.mapFromCursor(cursor); } finally { cursor.close(); } } catch (Exception exception) { throw new StorIOException(exception); } }
Source:
<code>public void human$setExhaustion(double exhaustion) { <START> this.foodStats.foodExhaustionLevel = exhaustion; <END> }</code><technical_language>Build Error: loss of precision</technical_language>

Target:
public void human$setExhaustion(double exhaustion) { this.getFoodStats().foodExhaustionLevel = (float) exhaustion; }
Source:
<code>public <T extends Enum<?>> void setEnum(final String section, final String subsection, final String name, final T value) { String n = value.name().toLowerCase().replace('_', ' '); <START> if (!value.name().equals(value.toString())) <END> n = value.toString(); setString(section, subsection, name, n); }</code><technical_language>not: if (value.names().equals(value.toString()) n = value.name().toLowerCase().replace('_', ' '); else n = value.toString();</technical_language>

Target:
public <T extends Enum<?>> void setEnum(final String section, final String subsection, final String name, final T value) { String n = value.name().toLowerCase().replace('_', ' '); if (value instanceof FastForwardMode) { n = ((FastForwardMode) value).toString(section, subsection, name); } setString(section, subsection, name, n); }
Source:
<code>public void execute(String[] args, Console console) { if (args.length > 2) { String subCommand = args[0]; switch (subCommand) { case SUBCMD_LIST: listMetadata(console, args[1], args[2]); break; case SUBCMD_ADD: if (args.length < 4) { printUsage(console); } else { addMetadata(console, args[1], args[2], args[3], args.length > 4 ? Arrays.stream(args, 4, args.length).collect(Collectors.joining()) <START> : null); <END> } break; case SUBCMD_REMOVE: removeMetadata(console, args[1], args[2]); break; default: console.println("Unknown command '" + subCommand + "'"); printUsage(console); break; } } else { printUsage(console); } }</code><technical_language>get right: arguments 4-x joined separator, correct? So, if argument 4 is "1", argument 5 is "2" argument 6 is "3", this result a string "123"</technical_language>

Target:
public void execute(String[] args, Console console) { if (args.length > 0) { String subCommand = args[0]; switch (subCommand) { case SUBCMD_LIST: listMetadata(console, args.length > 1 ? args[1] : null, args.length > 2 ? args[2] : null, false); break; case SUBCMD_LIST_INTERNAL: listMetadata(console, args.length > 1 ? args[1] : null, args.length > 2 ? args[2] : null, true); break; case SUBCMD_ADD: if (args.length < 4) { printUsage(console); } else { addMetadata(console, args[1], args[2], args[3], args.length > 4 ? args[4] : null); } break; case SUBCMD_REMOVE: removeMetadata(console, args[1], args.length > 2 ? args[2] : null); break; default: console.println("Unknown command '" + subCommand + "'"); printUsage(console); break; } } else { printUsage(console); } }
Source:
<code>private String generateNextDemoCourseId(String instructorEmailOrProposedCourseId, int maximumIdLength){ final boolean isFirstCourseId = instructorEmailOrProposedCourseId.contains("@"); if(isFirstCourseId){ <START> return new StringHelper().truncateHead(getDemoCourseIdRoot(instructorEmailOrProposedCourseId) <END> , maximumIdLength); } else { final boolean isFirstTimeDuplicate = instructorEmailOrProposedCourseId.endsWith("-demo"); if(isFirstTimeDuplicate){ return new StringHelper().truncateHead(instructorEmailOrProposedCourseId + "0" , maximumIdLength); } else { final int lastIndexOfDemo = instructorEmailOrProposedCourseId.lastIndexOf("-demo"); final String root = instructorEmailOrProposedCourseId.substring(0, lastIndexOfDemo); final int previousDedupSuffix = Integer.parseInt(instructorEmailOrProposedCourseId.substring(lastIndexOfDemo + 5)); return new StringHelper().truncateHead(root + "-demo" + (previousDedupSuffix+1) , maximumIdLength); } } }</code><technical_language>Is new necessary? for below</technical_language>

Target:
private String generateNextDemoCourseId(String instructorEmailOrProposedCourseId, int maximumIdLength){ final boolean isFirstCourseId = instructorEmailOrProposedCourseId.contains("@"); if(isFirstCourseId){ return StringHelper.truncateHead(getDemoCourseIdRoot(instructorEmailOrProposedCourseId), maximumIdLength); } else { final boolean isFirstTimeDuplicate = instructorEmailOrProposedCourseId.endsWith("-demo"); if(isFirstTimeDuplicate){ return StringHelper.truncateHead(instructorEmailOrProposedCourseId + "0", maximumIdLength); } else { final int lastIndexOfDemo = instructorEmailOrProposedCourseId.lastIndexOf("-demo"); final String root = instructorEmailOrProposedCourseId.substring(0, lastIndexOfDemo); final int previousDedupSuffix = Integer.parseInt(instructorEmailOrProposedCourseId.substring(lastIndexOfDemo + 5)); return StringHelper.truncateHead(root + "-demo" + (previousDedupSuffix + 1), maximumIdLength); } } }
Source:
<code>public void tryMkDir(final Path dir) throws IOException { callHdfsOperation(new HdfsOperation<Void>() { @Override public Void call() throws IOException { if (!fs.exists(dir)) { fs.mkdirs(dir); LOGGER.info("Create dir in hdfs", dir.toString()); } if (fs.isFile(dir)) { throw new IOException("{} is file instead of directory, please remove it or " + <START> "specify another directory"); <END> } fs.mkdirs(dir); return null; } }); }</code><technical_language>missing a parameter? is passed</technical_language>

Target:
public void tryMkDir(final Path dir) throws IOException { callHdfsOperation(new HdfsOperation<Void>() { @Override public Void call() throws IOException { if (!fs.exists(dir)) { fs.mkdirs(dir); LOGGER.info("Create dir in hdfs", dir.toString()); } if (fs.isFile(dir)) { throw new IOException(dir.toString() + " is file instead of directory, please remove " + "it or specify another directory"); } fs.mkdirs(dir); return null; } }); }
Source:
<code>public static void registerTags() { registerTag("is_open", (attribute, object) -> { return new ElementTag(object.door.isOpen()); }); registerTag("is_locked", (attribute, object) -> { return new ElementTag(object.door.isLocked()); }); registerTag("is_busy", (attribute, object) -> { return new ElementTag(BigDoorsBridge.commander.isDoorBusy(object.door.getDoorUID())); }); registerTag("is_loaded", (attribute, object) -> { return new ElementTag(BigDoorsBridge.bigDoors.areChunksLoadedForDoor(object.door)); }); registerTag("cuboid", (attribute, object) -> { return new CuboidTag(object.door.getMinimum(), object.door.getMaximum()); }); registerTag("auto_close", (attribute, object) -> { return new ElementTag(object.door.getAutoClose()); <START> }, "autoclose"); <END> registerTag("power_block", (attribute, object) -> { return new LocationTag(object.door.getPowerBlockLoc()); }); registerTag("owners", (attribute, object) -> { ListTag owners = new ListTag(); for (DoorOwner owner : BigDoorsBridge.commander.getDoorOwners(object.door.getDoorUID(), null)) { owners.addObject(PlayerTag.valueOf(owner.getPlayerUUID().toString(), CoreUtilities.noDebugContext)); } return owners; }); registerTag("door_type", (attribute, object) -> { return new ElementTag(object.door.getType().toString()); }); registerTag("name", (attribute, object) -> { return new ElementTag(object.door.getName()); }); }</code><technical_language>is a deprecated format of a brand new tag</technical_language>

Target:
public static void registerTags() { registerTag("is_open", (attribute, object) -> { return new ElementTag(object.door.isOpen()); }); registerTag("is_locked", (attribute, object) -> { return new ElementTag(object.door.isLocked()); }); registerTag("is_busy", (attribute, object) -> { return new ElementTag(BigDoorsBridge.commander.isDoorBusy(object.door.getDoorUID())); }); registerTag("is_loaded", (attribute, object) -> { return new ElementTag(BigDoorsBridge.bigDoors.areChunksLoadedForDoor(object.door)); }); registerTag("cuboid", (attribute, object) -> { return new CuboidTag(object.door.getMinimum(), object.door.getMaximum()); }); registerTag("auto_close", (attribute, object) -> { return new DurationTag(object.door.getAutoClose()); }); registerTag("power_block", (attribute, object) -> { return new LocationTag(object.door.getPowerBlockLoc()); }); registerTag("owners", (attribute, object) -> { ListTag owners = new ListTag(); for (DoorOwner owner : BigDoorsBridge.commander.getDoorOwners(object.door.getDoorUID(), null)) { owners.addObject(new PlayerTag(owner.getPlayerUUID())); } return owners; }); registerTag("door_type", (attribute, object) -> { return new ElementTag(object.door.getType().toString()); }); registerTag("name", (attribute, object) -> { return new ElementTag(object.door.getName()); }); }
Source:
<code>protected void onAttachedToWindow() { super.onAttachedToWindow(); SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int color = getSelectedColor(); setSelectedColor(color); if (fromUser) { onColorChanged(color); } } }; seekBarRed.setOnSeekBarChangeListener(seekBarListener); seekBarGreen.setOnSeekBarChangeListener(seekBarListener); seekBarBlue.setOnSeekBarChangeListener(seekBarListener); seekBarAlpha.setOnSeekBarChangeListener(seekBarListener); editTextHex.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable newText) { if (editTextHex.getTag() == null) { <START> if (parseInputToCheckIfHEX(newText.toString())) { <END> int color = Color.parseColor(newText.toString()); setSelectedColor(color); onColorChanged(color); resetTextColor(); } else { setTextColorToRed(); } } else { resetTextColor(); } } }); }</code><technical_language>This calls Color.parseColor, next line calls newText.toString()</technical_language>

Target:
protected void onAttachedToWindow() { super.onAttachedToWindow(); SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int color = getSelectedColor(); setSelectedColor(color); if (fromUser) { onColorChanged(color); } } }; seekBarRed.setOnSeekBarChangeListener(seekBarListener); seekBarGreen.setOnSeekBarChangeListener(seekBarListener); seekBarBlue.setOnSeekBarChangeListener(seekBarListener); seekBarAlpha.setOnSeekBarChangeListener(seekBarListener); editTextHex.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable newText) { if (editTextHex.getTag() == null) { int color = parseInputToCheckIfHEX(newText.toString()); if (color != NOT_A_HEX_VALUE) { setSelectedColor(color); onColorChanged(color); resetTextColor(); } else { setTextColorToRed(); } } else { resetTextColor(); } } }); }
Source:
<code>private boolean uploadDependencyToBlobStore(String key, File dependency) throws KeyAlreadyExistsException, AuthorizationException, IOException { boolean uploadNew = false; try { getBlobStore().getBlobMeta(key); } catch (KeyNotFoundException e) { List<AccessControl> acls = new ArrayList<>(); acls.add(new AccessControl(AccessControlType.USER, BlobStoreAclHandler.READ | BlobStoreAclHandler.WRITE | BlobStoreAclHandler.ADMIN)); acls.add(new AccessControl(AccessControlType.OTHER, BlobStoreAclHandler.READ)); InputStream in = null; AtomicOutputStream blob = null; try { <START> in = Files.newInputStream(dependency.toPath()); <END> blob = getBlobStore().createBlob(key, new SettableBlobMeta(acls)); IOUtils.copy(in, blob, this.uploadChuckSize); in.close(); in = null; blob.close(); blob = null; uploadNew = true; } finally { try { if (blob != null) { blob.cancel(); } } catch (IOException throwaway) { } } } return uploadNew; }</code><technical_language>Please try-with-resources before, is safer</technical_language>

Target:
private boolean uploadDependencyToBlobStore(String key, File dependency) throws KeyAlreadyExistsException, AuthorizationException, IOException { boolean uploadNew = false; try { getBlobStore().getBlobMeta(key); } catch (KeyNotFoundException e) { List<AccessControl> acls = new ArrayList<>(); acls.add(new AccessControl(AccessControlType.USER, BlobStoreAclHandler.READ | BlobStoreAclHandler.WRITE | BlobStoreAclHandler.ADMIN)); acls.add(new AccessControl(AccessControlType.OTHER, BlobStoreAclHandler.READ)); AtomicOutputStream blob = null; try { blob = getBlobStore().createBlob(key, new SettableBlobMeta(acls)); try(InputStream in = Files.newInputStream(dependency.toPath())) { IOUtils.copy(in, blob, this.uploadChuckSize); } blob.close(); blob = null; uploadNew = true; } finally { try { if (blob != null) { blob.cancel(); } } catch (IOException throwaway) { } } } return uploadNew; }