auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldGetAllGatewayAccounts() { when(getMockGatewayAccountEntity1.getType()).thenReturn("test"); when(getMockGatewayAccountEntity2.getType()).thenReturn("test"); when(mockGatewayAccountDao.listAll()).thenReturn(Arrays.asList(getMockGatewayAccountEntity1, getMockGatewayAccountEntity2)); List<GatewayAccountResourceDTO> gatewayAccounts = gatewayAccountService.getAllGatewayAccounts(); assertThat(gatewayAccounts, hasSize(2)); <START> } <END></code><technical_language>In this test (and other modified), good check GatewayAccountResourceDTO objects returned converted correct GatewayAccountEntity objects. ways I of this: 1. Stub getServiceName() mock GatewayAccountEntity a unique name verify getServiceName() matching GatewayAccountResourceDTO object returns value. 1. Move logic for converting a GatewayAccountEntity GatewayAccountResourceDTO out a static method GatewayAccountResourceDTO a separate converter class. If this converter is unit-tested, stub call a mock converter in tests: java when(mockGatewayAccountEntityToGatewayAccountResourceDTOConverter.convert(mockGatewayAccountEntity1).thenReturn(mockGatewayAccountResourceDTO1); separate converters feels a bit cleaner a separation of concerns point of view (why GatewayAccountResourceDTO GatewayAccountEntity exists?) converter injected in places generally approach in connector. Friday, a moment wistfully wish Rust, in-built support for conversions traits. Anyway, happy if one</technical_language>

Target:
public void shouldGetAllGatewayAccounts() { when(mockGatewayAccountDao.listAll()).thenReturn(Arrays.asList(getMockGatewayAccountEntity1, getMockGatewayAccountEntity2)); List<GatewayAccountResourceDTO> gatewayAccounts = gatewayAccountService.getAllGatewayAccounts(); assertThat(gatewayAccounts, hasSize(2)); assertThat(gatewayAccounts.get(0).getServiceName(), is("service one")); assertThat(gatewayAccounts.get(1).getServiceName(), is("service two")); }
Source:
<code>private void releaseExternally() { if (state == State.ALLOCATED && requestedLogicalSlots.values().isEmpty()) { <START> externalReleaseCallback.accept(executionSlotSharingGroup); <END> state = State.RELEASED; } }</code><technical_language>state needs updated calling externalReleaseCallback. This is SharedSlot#release() triggered in calling stack</technical_language>

Target:
private void releaseExternally() { if (state == State.ALLOCATED && requestedLogicalSlots.values().isEmpty()) { state = State.RELEASED; externalReleaseCallback.accept(executionSlotSharingGroup); } }
Source:
<code>public Map<String, Map<String, Session>> loadSessions() { checkValidity(); <START> return null; <END> }</code><technical_language>returning null null pointer exceptions</technical_language>

Target:
public Map<String, Map<String, Session>> loadSessions() { checkValidity(); return new ConcurrentHashMap<>(); }
Source:
<code>private DefaultPreparedStatement cache(DefaultPreparedStatement preparedStatement) { DefaultPreparedStatement previous = preparedStatementsCache.putIfAbsent(preparedStatement.getId(), preparedStatement); if (previous != null) { LOG.warn( "Re-preparing already prepared query. " + "This is generally an anti-pattern and will likely affect performance. " + "The cached version of the PreparedStatement will be returned which may have a " <START> + "different base Statement configuration than the base Statement that was prepared. " <END> + "Consider preparing the statement only once. Query='{}'", preparedStatement.getQuery()); return previous; } else { return preparedStatement; } }</code><technical_language>a bit cryptic for uninitiated, hard explain in a short message. about: > cached version of PreparedStatement returned, bound statement execution parameters (CL, timeout, etc.) current session.prepare call</technical_language>

Target:
private DefaultPreparedStatement cache(DefaultPreparedStatement preparedStatement) { DefaultPreparedStatement previous = preparedStatementsCache.putIfAbsent(preparedStatement.getId(), preparedStatement); if (previous != null) { LOG.warn( "Re-preparing already prepared query. " + "This is generally an anti-pattern and will likely affect performance. " + "The cached version of the PreparedStatement will be returned, which may use " + "different bound statement execution parameters (CL, timeout, etc.) from the " + "current session.prepare call. Consider preparing the statement only once. " + "Query='{}'", preparedStatement.getQuery()); return previous; } else { return preparedStatement; } }
Source:
<code><START> public synchronized void pauseJob(final String groupName) throws SchedulerException { <END> if (!ifJobExist(groupName)) { logger.warn("can not find job with " + groupName + " in quartz."); } else { this.scheduler.pauseJob(new JobKey(DEFAULT_JOB_NAME, groupName)); } }</code><technical_language>Based <LINK_0>, name groupName "flowTrigger", jobName "project_name+flow_name"</technical_language>

Target:
public synchronized void pauseJob(final String groupName) throws SchedulerException { if (!ifJobExist(groupName)) { throw new SchedulerException("can not find job with group name: " + groupName + " in quartz."); } else { this.scheduler.pauseJob(new JobKey(DEFAULT_JOB_NAME, groupName)); } }
Source:
<code>private ImageTicket getTestTicket() { ImageTicket ticket = new ImageTicket(); ticket.setId(Guid.createGuidFromString("799030aa-97c3-4354-871e-0adf0556fcbf")); ticket.setSize(1073741824L); <START> ticket.setUrl("file:/ END> ticket.setTimeout(300); ticket.setOps(new String[]{"read", "write"}); return ticket; }</code><technical_language>This "https://server:port/imageio/799030aa-97c3-4354-871e-0adf0556fcbf"</technical_language>

Target:
private ImageTicket getTestTicket() { ImageTicket ticket = new ImageTicket(); ticket.setId(Guid.createGuidFromString("799030aa-97c3-4354-871e-0adf0556fcbf")); ticket.setSize(1073741824L); ticket.setUrl("https://server:port/imageio/799030aa-97c3-4354-871e-0adf0556fcbf"); ticket.setTimeout(300); ticket.setOps(new String[]{"read", "write"}); return ticket; }
Source:
<code>public static void main(String[] args) throws IOException { <START> System.out.println("Copying rsdl.xml, rsdl_gluster.xml to: " + args[0]); <END> copyRsdl(args[0]); }</code><technical_language>run this maven, write a "target/generated-metadata" directory, initially exist, please create directory if exist: File outputDir = new File(args[0]); if (!outputDir.exists()) { outputDir.mkdirs(); }</technical_language>

Target:
public static void main(String[] args) throws IOException { System.out.println("Copying rsdl.xml, rsdl_gluster.xml, api.xsd to: " + args[0]); copyRsdl(args[0]); }
Source:
<code>public boolean checkUsable() { var optionalVersionMessage = attemptHandshakeForVersionMessage(); handleHandshakeAttempt(optionalVersionMessage); <START> return isUsable().get(); <END> }</code><technical_language>checks for Optional.isPresent()</technical_language>

Target:
private void checkUsable() { var optionalVersionMessage = attemptHandshakeForVersionMessage(); handleHandshakeAttempt(optionalVersionMessage); }
Source:
<code>public static void main(String[] args) throws Exception { FProtocolFactory protocolFactory = new FProtocolFactory(new TBinaryProtocol.Factory()); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); Connection connection = connectionFactory.createConnection(); connection.start(); <START> FSubscriberTransportFactory subscriberFactory = new FJmsSubscriberTransport.Factory(connection, "Consumer.frugal-examples.VirtualTopic.", true); <END> FScopeProvider provider = new FScopeProvider(null, subscriberFactory, protocolFactory); AlbumWinnersSubscriber.Iface subscriber = new AlbumWinnersSubscriber.Client(provider); subscriber.subscribeWinner((ctx, album) -> System.out.println("You won! " + album)); subscriber.subscribeContestStart((ctx, albums) -> System.out.println("Contest started, available albums: " + albums)); System.out.println("Subscriber started..."); }</code><technical_language>virtual topics match other examples</technical_language>

Target:
public static void main(String[] args) throws Exception { FProtocolFactory protocolFactory = new FProtocolFactory(new TBinaryProtocol.Factory()); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(); Connection connection = connectionFactory.createConnection(); connection.start(); FSubscriberTransportFactory subscriberFactory = new FJmsSubscriberTransport.Factory.Builder(connection).build(); FScopeProvider provider = new FScopeProvider(null, subscriberFactory, protocolFactory); AlbumWinnersSubscriber.Iface subscriber = new AlbumWinnersSubscriber.Client(provider); subscriber.subscribeWinner((ctx, album) -> System.out.println("You won! " + album)); subscriber.subscribeContestStart((ctx, albums) -> System.out.println("Contest started, available albums: " + albums)); System.out.println("Subscriber started..."); }
Source:
<code>HashMap<String, Object> removeFromList(Model model, @PathVariable String profileIdentifier) throws Exception { logger.info("Attempting to remove {}", profileIdentifier); <START> String[] toRemove = profileIdentifier.split(","); <END> for( int i = 0; i < toRemove.length; i++ ) { Integer profileId = ControllerUtils.convertProfileIdentifier(toRemove[i]); logger.info("Want to (preRemove) DELETE on id {}", profileId); profileService.remove(profileId); } return Utils.getJQGridJSON(profileService.findAllProfiles(), "profiles"); }</code><technical_language>This array. url pattern of profileIdentifier=a&profileIdentifier=b Changing method signature String[] profileIdentifier do rest for you</technical_language>

Target:
HashMap<String, Object> removeFromList(Model model, @PathVariable String profileIdentifier) throws Exception { Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier); logger.info("Want to (preRemove) DELETE on id {}", profileId); profileService.remove(profileId); return Utils.getJQGridJSON(profileService.findAllProfiles(), "profiles"); }
Source:
<code>public void onMapReady(final GoogleMap map) { mMap = map; LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (Pair<Entity<TreeReference>, LatLng> entityLocation: entityLocations) { <START> Marker marker = map.addMarker(new MarkerOptions() <END> .position(entityLocation.second) .title(entityLocation.first.getFieldString(0)) .snippet(entityLocation.first.getFieldString(1))); markerReferences.put(marker, entityLocation.first.getElement()); builder.include(entityLocation.second); } final LatLngBounds bounds = builder.build(); map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() { @Override public void onMapLoaded() { map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, MAP_PADDING)); } }); map.setOnInfoWindowClickListener(this); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { map.setMyLocationEnabled(true); } }</code><technical_language>I mMap instead of map of this method. clearer modifying internal state of class, some local variable</technical_language>

Target:
public void onMapReady(final GoogleMap map) { mMap = map; if (entityLocations.size() > 0) { LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (Pair<Entity<TreeReference>, LatLng> entityLocation : entityLocations) { Marker marker = mMap.addMarker(new MarkerOptions() .position(entityLocation.second) .title(entityLocation.first.getFieldString(0)) .snippet(entityLocation.first.getFieldString(1))); markerReferences.put(marker, entityLocation.first.getElement()); builder.include(entityLocation.second); } final LatLngBounds bounds = builder.build(); mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() { @Override public void onMapLoaded() { mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, MAP_PADDING)); } }); } mMap.setOnInfoWindowClickListener(this); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); } }
Source:
<code>public long getLastModified() { long lastMod = -1; for (Iterator<Path> i = dirIterator(); i.hasNext(); ) { Path dir = i.next(); try { for (FileStatus st : fileSystem.listStatus(dir)) { if (lastMod < st.getModificationTime()) { lastMod = st.getModificationTime(); } } } catch (IOException e) { throw new DatasetIOException("Cannot find last modified time of of " + dir, e); } } <START> long viewModified = unbounded.getLastModified(); <END> if (lastMod < viewModified) { lastMod = viewModified; } return lastMod; }</code><technical_language>This delegation recursively check file system, logic removed. I this delegate unbounded.getLastModified()</technical_language>

Target:
public long getLastModified() { return unbounded.getLastModified(); }
Source:
<code>private ImportTestFilesAndData prepareTestFiles() throws Throwable { Configuration defaultConf = new Configuration(); Path tempFile = new Path("target/accumulo-test/import/sample.rf"); Path failures = new Path("target/accumulo-test/failures/"); FileSystem fs = FileSystem.get(new URI("file:/ fs.deleteOnExit(tempFile); fs.deleteOnExit(failures); fs.delete(failures, true); fs.delete(tempFile, true); fs.mkdirs(failures); fs.mkdirs(tempFile.getParent()); <START> FileSKVWriter writer = FileOperations.getInstance().openWriter().ofFile(tempFile.toString(), fs, defaultConf) <END> .withTableConfiguration(AccumuloConfiguration.getDefaultConfiguration()).execute(); writer.startDefaultLocalityGroup(); List<Pair<Key,Value>> keyVals = new ArrayList<Pair<Key,Value>>(); for (int i = 0; i < 5; i++) { keyVals.add(new Pair<Key,Value>(new Key("a" + i, "b" + i, "c" + i, new ColumnVisibility(""), 1000l + i), new Value(Integer.toString(i).getBytes()))); } for (Pair<Key,Value> keyVal : keyVals) { writer.append(keyVal.getFirst(), keyVal.getSecond()); } writer.close(); ImportTestFilesAndData files = new ImportTestFilesAndData(); files.failurePath = failures; files.importPath = tempFile.getParent(); files.keyVals = keyVals; return files; }</code><technical_language>"verbage" feels a strange (maybe preserve original openWriter() methods?). do like: FileOperations.getInstance().newWriterBuilder().ofFile(tempFile.toString(), fs, defaultConf) .withTableConfiguration(AccumuloConfiguration.getDefaultConfiguration()).build(); common "builder" "build" terminology a bit obvious this works. "openWriter" imply is opened (that I need close) "execute" some I/O handle. of true misleading. I this is a nit-picky, if APIs better, in favor of making clear prevent coming soon</technical_language>

Target:
private ImportTestFilesAndData prepareTestFiles() throws Throwable { Configuration defaultConf = new Configuration(); Path tempFile = new Path("target/accumulo-test/import/sample.rf"); Path failures = new Path("target/accumulo-test/failures/"); FileSystem fs = FileSystem.get(new URI("file:/ fs.deleteOnExit(tempFile); fs.deleteOnExit(failures); fs.delete(failures, true); fs.delete(tempFile, true); fs.mkdirs(failures); fs.mkdirs(tempFile.getParent()); FileSKVWriter writer = FileOperations.getInstance().newWriterBuilder().forFile(tempFile.toString(), fs, defaultConf) .withTableConfiguration(AccumuloConfiguration.getDefaultConfiguration()).build(); writer.startDefaultLocalityGroup(); List<Pair<Key,Value>> keyVals = new ArrayList<Pair<Key,Value>>(); for (int i = 0; i < 5; i++) { keyVals.add(new Pair<Key,Value>(new Key("a" + i, "b" + i, "c" + i, new ColumnVisibility(""), 1000l + i), new Value(Integer.toString(i).getBytes()))); } for (Pair<Key,Value> keyVal : keyVals) { writer.append(keyVal.getFirst(), keyVal.getSecond()); } writer.close(); ImportTestFilesAndData files = new ImportTestFilesAndData(); files.failurePath = failures; files.importPath = tempFile.getParent(); files.keyVals = keyVals; return files; }
Source:
<code>private void validate(Schema inputSchema) { Schema.Field field = inputSchema.getField(inputCol); if (field == null) { throw new IllegalArgumentException(String.format("Input column %s does not exist in the input schema", inputCol)); } Schema schema = field.getSchema(); Schema.Type type = schema.isNullable() ? schema.getNonNullable().getType() : schema.getType(); if (!(type.equals(Schema.Type.STRING) || type.equals(Schema.Type.BOOLEAN) || (type.equals(Schema.Type.ARRAY) && (schema.getComponentSchema().getType().equals(Schema.Type.STRING) || schema.getComponentSchema().getType().equals(Schema.Type.BOOLEAN))))) { <START> throw new IllegalArgumentException(String.format("Input column can be of type string, boolean or array of " + <END> "string or boolean. But was %s for %s.", type, inputCol)); } }</code><technical_language>sense allow boolean fields, this model is for text. a string nullable string. need support array of strings either, optional split pattern a property defaults whitespace</technical_language>

Target:
public void validate(Schema inputSchema) { SparkUtils.validateTextField(inputSchema, inputCol); try { Pattern.compile(pattern); } catch (PatternSyntaxException e) { throw new IllegalArgumentException(String.format("Invalid expression - %s. Please provide a valid pattern " + "for splitting the string. %s.", pattern, e.getMessage()), e); } validateConfigParameters("vector size", vectorSize); validateConfigParameters("minimum count", minCount); validateConfigParameters("number of partitions", numPartitions); validateConfigParameters("number of iterations", numIterations); validateConfigParameters("window size", windowSize); }
Source:
<code>private final byte[] buildTREBytes() { String result; <START> String defaltEncoding = System.getProperty("file.encoding"); <END> Charset defaultCharset = Charset.forName(defaltEncoding); Charset iso88591charset = Charset.forName("ISO-8859-1"); ByteBuffer inputBuffer = ByteBuffer.wrap(mTestDataGzip.getBytes()); CharBuffer data = defaultCharset.decode(inputBuffer); ByteBuffer outputBuffer = iso88591charset.encode(data); byte[] outputData = outputBuffer.array(); byte[] gzipped = new byte[outputData.length + secuirtyGzipped.length]; System.arraycopy(outputData, 0, gzipped, 0, outputData.length); System.arraycopy(secuirtyGzipped, 0, gzipped, outputData.length, secuirtyGzipped.length); return gzipped; }</code><technical_language>default (typo) this of file.encoding is a good idea - test results depend locale of machine run</technical_language>

Target:
private final byte[] buildTREBytes() { String result; ByteBuffer inputBuffer = ByteBuffer.wrap(mTestDataGzip.getBytes()); CharBuffer data = StandardCharsets.UTF_8.decode(inputBuffer); ByteBuffer outputBuffer = StandardCharsets.ISO_8859_1.encode(data); byte[] outputData = outputBuffer.array(); byte[] gzipped = new byte[outputData.length + securityGzipped.length]; System.arraycopy(outputData, 0, gzipped, 0, outputData.length); System.arraycopy(securityGzipped, 0, gzipped, outputData.length, securityGzipped.length); return gzipped; }
Source:
<code>public PartitionUpsertMetadataManager getOrCreatePartitionManager(int partitionId) { return _partitionMetadataManagerMap <START> .computeIfAbsent(partitionId, k -> new PartitionUpsertMetadataManager(_tableName, partitionId, _serverMetrics)); <END> }</code><technical_language>(nit) suggestion .computeIfAbsent(partitionId, -> new PartitionUpsertMetadataManager(_tableName, k, _serverMetrics));</technical_language>

Target:
public PartitionUpsertMetadataManager getOrCreatePartitionManager(int partitionId) { return _partitionMetadataManagerMap.computeIfAbsent(partitionId, k -> new PartitionUpsertMetadataManager(_tableNameWithType, k, _serverMetrics)); }
Source:
<code>public SolutionFileIO<TspSolution> createSolutionFileIO() { <START> return new TspXStreamSolutionFileIO(); <END> }</code><technical_language>extract in a separate file? more files in example, harder is understand for users</technical_language>

Target:
public SolutionFileIO<TspSolution> createSolutionFileIO() { return new XStreamSolutionFileIO<>(TspSolution.class); }
Source:
<code>void errorWhenItemWithTextNotMatchedButShouldBe() { String expectedText = "Luis"; assertThatThrownBy(() -> $$("#user-table tbody tr td.firstname").shouldBe(itemWithText(expectedText))) .isInstanceOf(TextsMismatch.class) .hasMessageContaining( <START> String.format(String.format("Texts mismatch" + <END> "%nActual: %s" + "%nExpected: %s", Arrays.asList("Bob", "John"), Collections.singletonList(expectedText)))); }</code><technical_language>I another error message instead of "Texts mismatch". "element text found"</technical_language>

Target:
void errorWhenItemWithTextNotMatchedButShouldBe() { String expectedText = "Luis"; assertThatThrownBy(() -> $$("#user-table tbody tr td.firstname").shouldHave(itemWithText(expectedText))) .isInstanceOf(ElementWithTextNotFound.class) .hasMessageContaining( String.format(String.format("Element with text not found" + "%nActual: %s" + "%nExpected: %s", Arrays.asList("Bob", "John"), Collections.singletonList(expectedText)))); }
Source:
<code><START> CompletableFuture<Void> failedFuture(Throwable ex) { <END> Preconditions.checkNotNull(ex); CompletableFuture<Void> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(ex); return failedFuture; }</code><technical_language>move this end of class</technical_language>

Target:
private static CompletableFuture<Void> failedFuture(Throwable ex) { Preconditions.checkNotNull(ex); CompletableFuture<Void> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(ex); return failedFuture; }
Source:
<code>public void getVirtualAttributesByHolders() throws Exception { System.out.println(CLASS_NAME + "getVirtualAttributesByHolders"); AttributeDefinition memberVirtAttr = setUpVirtualMemberAttribute(); AttributeDefinition memberResourceVirtAttr = setUpVirtualMemberResourceAttribute(); setUpGroupAttribute(); setUpMemberGroupAttributeDefinition(); List<Attribute> attrs = cacheManager.getVirtualAttributes(Holder.HolderType.MEMBER, Holder.HolderType.RESOURCE); assertTrue("result should contain virtual member-resource attribute definition", attrs.contains(new Attribute(memberResourceVirtAttr))); <START> assertTrue("result should not contain virtual member attribute definition", !attrs.contains(new Attribute(memberVirtAttr))); <END> assertTrue("it should return only 1 attribute", attrs.size() == 1); }</code><technical_language>above</technical_language>

Target:
public void getVirtualAttributesByHolders() throws Exception { System.out.println(CLASS_NAME + "getVirtualAttributesByHolders"); AttributeDefinition memberVirtAttr = setUpVirtualMemberAttribute(); AttributeDefinition memberResourceVirtAttr = setUpVirtualMemberResourceAttribute(); setUpGroupAttribute(); setUpMemberGroupAttributeDefinition(); List<Attribute> attrs = cacheManager.getVirtualAttributes(Holder.HolderType.MEMBER, Holder.HolderType.RESOURCE); assertTrue("result should contain virtual member-resource attribute definition", attrs.contains(memberResourceVirtAttr)); assertTrue("result should not contain virtual member attribute definition", !attrs.contains(memberVirtAttr)); assertTrue("it should return only 1 attribute", attrs.size() == 1); }
Source:
<code>public Page getOutput() { if (!spillInProgress.isDone()) { return null; } checkSuccess(spillInProgress, "spilling failed"); if (probe == null && pageBuilder.isEmpty() && !finishing) { return null; } if (!tryFetchLookupSourceProvider()) { return null; } if (probe == null && finishing && !unspilling) { verify(partitionedConsumption == null, "partitioned consumption already started"); partitionedConsumption = lookupSourceFactory.finishProbeOperator(lookupJoinsCount); unspilling = true; } if (probe == null && unspilling && !finished) { tryUnspillNext(); } if (probe != null) { processProbe(); } if (outputPage != null) { <START> checkState(pageBuilder.isEmpty()); <END> Page output = outputPage; outputPage = null; return output; } return null; }</code><technical_language>verify is more trendy</technical_language>

Target:
public Page getOutput() { if (!spillInProgress.isDone()) { return null; } checkSuccess(spillInProgress, "spilling failed"); if (probe == null && pageBuilder.isEmpty() && !finishing) { return null; } if (!tryFetchLookupSourceProvider()) { return null; } if (probe == null && finishing && !unspilling) { verify(partitionedConsumption == null, "partitioned consumption already started"); partitionedConsumption = lookupSourceFactory.finishProbeOperator(lookupJoinsCount); unspilling = true; } if (probe == null && unspilling && !finished) { tryUnspillNext(); } if (probe != null) { processProbe(); } if (outputPage != null) { verify(pageBuilder.isEmpty()); Page output = outputPage; outputPage = null; return output; } if (!pageBuilder.isEmpty() && probe == null && finished && !useDictionaryProcessing) { Page page = pageBuilder.build(null); pageBuilder.reset(); return page; } return null; }
Source:
<code>public void deserialize(byte[] message, Collector<RowData> out) throws IOException { RowData row = jsonDeserializer.deserialize(message); String type = row.getString(2).toString(); if (OP_INSERT.equals(type)) { ArrayData data = row.getArray(0); for (int i = 0; i < data.size(); i++) { RowData insert = data.getRow(i, fieldCount); insert.setRowKind(RowKind.INSERT); out.collect(insert); } } else if (OP_UPDATE.equals(type)) { ArrayData data = row.getArray(0); ArrayData old = row.getArray(1); for (int i = 0; i < data.size(); i++) { GenericRowData after = (GenericRowData) data.getRow(i, fieldCount); GenericRowData before = (GenericRowData) old.getRow(i, fieldCount); for (int f = 0; f < fieldCount; f++) { if (before.isNullAt(f)) { before.setField(f, after.getField(f)); } } before.setRowKind(RowKind.UPDATE_BEFORE); after.setRowKind(RowKind.UPDATE_AFTER); out.collect(before); out.collect(after); } } else if (OP_DELETE.equals(type)) { ArrayData data = row.getArray(0); for (int i = 0; i < data.size(); i++) { RowData insert = data.getRow(i, fieldCount); insert.setRowKind(RowKind.DELETE); out.collect(insert); } } else { if (!ignoreParseErrors) { throw new IOException(format("Failed to deserialize Canal JSON '%s'.", new String(message))); <START> } <END> } }</code><technical_language>Give more detailed exception for intentionally thrown exception</technical_language>

Target:
public void deserialize(byte[] message, Collector<RowData> out) throws IOException { try { RowData row = jsonDeserializer.deserialize(message); String type = row.getString(2).toString(); if (OP_INSERT.equals(type)) { ArrayData data = row.getArray(0); for (int i = 0; i < data.size(); i++) { RowData insert = data.getRow(i, fieldCount); insert.setRowKind(RowKind.INSERT); out.collect(insert); } } else if (OP_UPDATE.equals(type)) { ArrayData data = row.getArray(0); ArrayData old = row.getArray(1); for (int i = 0; i < data.size(); i++) { GenericRowData after = (GenericRowData) data.getRow(i, fieldCount); GenericRowData before = (GenericRowData) old.getRow(i, fieldCount); for (int f = 0; f < fieldCount; f++) { if (before.isNullAt(f)) { before.setField(f, after.getField(f)); } } before.setRowKind(RowKind.UPDATE_BEFORE); after.setRowKind(RowKind.UPDATE_AFTER); out.collect(before); out.collect(after); } } else if (OP_DELETE.equals(type)) { ArrayData data = row.getArray(0); for (int i = 0; i < data.size(); i++) { RowData insert = data.getRow(i, fieldCount); insert.setRowKind(RowKind.DELETE); out.collect(insert); } } else { if (!ignoreParseErrors) { throw new IOException(format( "Unknown \"type\" value \"%s\". The Canal JSON message is '%s'", type, new String(message))); } } } catch (Throwable t) { if (!ignoreParseErrors) { throw new IOException(format( "Corrupt Canal JSON message '%s'.", new String(message)), t); } } }
Source:
<code>public void addQueryDateRange(final String name, LocalDate lowerBound, LocalDate upperBound) { <START> if (lowerBound != null && upperBound != null) { <END> int comparison = lowerBound.compareTo(upperBound); if (comparison > 0) { LocalDate temp = lowerBound; lowerBound = upperBound; upperBound = temp; } } if (lowerBound != null) { String value = lowerBound.toString(); addQueryParam(name + ">", value); } if (upperBound != null) { String value = upperBound.toString(); addQueryParam(name + "<", value); } }</code><technical_language>do this in other languages. here</technical_language>

Target:
public void addQueryDateRange(final String name, LocalDate lowerBound, LocalDate upperBound) { if (lowerBound != null) { String value = lowerBound.toString(); addQueryParam(name + ">", value); } if (upperBound != null) { String value = upperBound.toString(); addQueryParam(name + "<", value); } }
Source:
<code>private void setContentsInternal(@Nullable InputStream input) throws IOException { VirtualFile virtualFile = getVirtualFile(); if (!existsInternal(virtualFile)) { throw new FileNotFoundException( "Could not set contents of " + this + " as it does not exist or is not valid."); } <START> OutputStream out = virtualFile.getOutputStream(this); InputStream in = input == null ? new ByteArrayInputStream(new byte[0]) : input; byte[] buffer = new byte[BUFFER_SIZE]; <END> int read; try { while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } }</code><technical_language>please try-with-resources, apache commons for copy suggestion try (InputStream in = input == null ? new ByteArrayInputStream(new byte[0]) : input; OutputStream out = virtualFile.getOutputStream(this); ) { IOUtils.copy(in, out); }</technical_language>

Target:
private void setContentsInternal(@Nullable InputStream input) throws IOException { VirtualFile virtualFile = getVirtualFile(); if (!existsInternal(virtualFile)) { throw new FileNotFoundException( "Could not set contents of " + this + " as it does not exist or is not valid."); } try (InputStream in = input == null ? new ByteArrayInputStream(new byte[0]) : input; OutputStream out = virtualFile.getOutputStream(this)) { IOUtils.copy(in, out); } }
Source:
<code>private void serverRemovedSegment(DruidServerMetadata server, DataSegment segment) { String segmentId = segment.getIdentifier(); final Set<DruidServerMetadata> servers; synchronized (lock) { log.debug("Removing segment[%s] from server[%s].", segmentId, server); servers = selectors.get(segmentId); if (servers == null) { log.warn("Told to remove non-existant segment[%s]", segmentId); return; } servers.remove(server); if (servers.isEmpty()) { VersionedIntervalTimeline<String, SegmentLoadInfo> timeline = timelines.get(segment.getDataSource()); selectors.remove(segmentId); final PartitionChunk<SegmentLoadInfo> removedPartition = timeline.remove( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk( new SegmentLoadInfo( segment, <START> Sets <END> .<DruidServerMetadata>newHashSet() ) ) ); if (removedPartition == null) { log.warn( "Asked to remove timeline entry[interval: %s, version: %s] that doesn't exist", segment.getInterval(), segment.getVersion() ); } } } }</code><technical_language>ImmutableSet.<DruidServerMetadata>of()</technical_language>

Target:
private void serverRemovedSegment(DruidServerMetadata server, DataSegment segment) { String segmentId = segment.getIdentifier(); synchronized (lock) { log.debug("Removing segment[%s] from server[%s].", segmentId, server); final SegmentLoadInfo segmentLoadInfo = segmentLoadInfos.get(segmentId); if (segmentLoadInfo == null) { log.warn("Told to remove non-existant segment[%s]", segmentId); return; } segmentLoadInfo.removeServer(server); if (segmentLoadInfo.isEmpty()) { VersionedIntervalTimeline<String, SegmentLoadInfo> timeline = timelines.get(segment.getDataSource()); segmentLoadInfos.remove(segmentId); final PartitionChunk<SegmentLoadInfo> removedPartition = timeline.remove( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk( new SegmentLoadInfo( segment ) ) ); if (removedPartition == null) { log.warn( "Asked to remove timeline entry[interval: %s, version: %s] that doesn't exist", segment.getInterval(), segment.getVersion() ); } } } }
Source:
<code>protected <T> T handleError(Class<T> clz, Exception e, boolean notFoundAs404) { if ((e instanceof EntityNotFoundException) && (notFoundAs404)) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } else if ((e instanceof BackendFailureException) && (!StringUtils.isEmpty(e.getMessage()))) { LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), e.getMessage(), null); throw new WebFaultException(null, e.getMessage(), Response.Status.BAD_REQUEST); <START> } else if (e instanceof UrlParamException){ <END> UrlParamException e2 = (UrlParamException) e; throw e2; } else { LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), detail(e), e); throw new WebFaultException(e, detail(e), Response.Status.INTERNAL_SERVER_ERROR); } }</code><technical_language>expect check for WebFaultException, this permutations of WebFaultException in a handled way</technical_language>

Target:
protected <T> T handleError(Class<T> clz, Exception e, boolean notFoundAs404) { if ((e instanceof EntityNotFoundException) && (notFoundAs404)) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } else if ((e instanceof BackendFailureException) && (!StringUtils.isEmpty(e.getMessage()))) { LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), e.getMessage(), null); throw new WebFaultException(null, e.getMessage(), Response.Status.BAD_REQUEST); } else if (e instanceof WebFaultException) { WebFaultException e2 = (WebFaultException) e; LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), detail(e2), e2); throw e2; } else { LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), detail(e), e); throw new WebFaultException(e, detail(e), Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
<code>public ChannelPipelineFactory newChannelPipelineFactory(final int maxFrameSize, NettyClientConfig clientConfig) { return new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline cp = Channels.pipeline(); TimeoutHandler.addToPipeline(cp); cp.addLast("frameEncoder", new LengthFieldPrepender(LENGTH_FIELD_LENGTH)); cp.addLast( "frameDecoder", new LengthFieldBasedFrameDecoder( maxFrameSize, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP)); if (clientConfig.sslClientConfiguration() != null) { <START> cp.addFirst("ssl", clientConfig.sslClientConfiguration().initializeHandler()); <END> } return cp; } }; }</code><technical_language>Move beginning of pipeline call .addLast instead</technical_language>

Target:
public ChannelPipelineFactory newChannelPipelineFactory(final int maxFrameSize, NettyClientConfig clientConfig) { return new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline cp = Channels.pipeline(); TimeoutHandler.addToPipeline(cp); cp.addLast("frameEncoder", new LengthFieldPrepender(LENGTH_FIELD_LENGTH)); cp.addLast( "frameDecoder", new LengthFieldBasedFrameDecoder( maxFrameSize, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP)); if (clientConfig.sslClientConfiguration() != null) { cp.addFirst("ssl", clientConfig.sslClientConfiguration().createHandler(address)); } return cp; } }; }
Source:
<code>String encodeUrlForRedirect(String urlStr) throws MalformedURLException { try { URL url = new URL(urlStr); UriBuilder builder = UriBuilder.fromUri(url.toURI()); builder.host(url.getHost()); builder.port(url.getPort()); builder.replacePath(url.getPath()); URI uri = builder.build(); <START> LOGGER.info("encodeUrlForRedirect - from [{}]", uri, urlStr); <END> return uri.toString(); } catch (URISyntaxException exc) { throw new MalformedURLException(exc.getMessage()); } }</code><technical_language>please ensure uri.toString() is logged Object-Address</technical_language>

Target:
String encodeUrlForRedirect(String urlStr) throws MalformedURLException { try { URL url = new URL(urlStr); UriBuilder builder = UriBuilder.fromUri(url.toURI()); builder.host(url.getHost()); builder.port(url.getPort()); builder.replacePath(url.getPath()); String encodedUrl = builder.build().toString(); LOGGER.info("encodeUrlForRedirect - from [{}]", encodedUrl, urlStr); return encodedUrl; } catch (URISyntaxException exc) { throw new MalformedURLException(exc.getMessage()); } }
Source:
<code>public void writeTo( Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { <START> new PrintWriter(new OutputStreamWriter(entityStream)).print(GSON.toJson(o)); <END> }</code><technical_language>GSON.toJson(o, new OutputStreamWriter(entityStream))? flush writer leaving</technical_language>

Target:
public void writeTo( Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { GSON.toJson(o, new OutputStreamWriter(entityStream)); }
Source:
<code><START> protected String <END> getFontName(String fontNameExpression, EAttribute eAttribute, FontData defaultFontData) { String fontName = defaultFontData.getName(); Eval eval = new Eval(interpreter, variableManager); if (fontNameExpression != null && !fontNameExpression.isEmpty()) { String fontNameValue = eval.get(eAttribute, fontNameExpression, String.class); if (fontNameValue != null) { fontName = fontNameValue; } } return fontName; }</code><technical_language>useful, this method of AbstractEEFLifecycleManager</technical_language>

Target:
private String getFontName(String fontNameExpression, EAttribute eAttribute, FontData defaultFontData) { String fontName = defaultFontData.getName(); Eval eval = new Eval(interpreter, variableManager); if (fontNameExpression != null && !fontNameExpression.isEmpty()) { String fontNameValue = eval.get(eAttribute, fontNameExpression, String.class); if (fontNameValue != null) { fontName = fontNameValue; } } return fontName; }
Source:
<code>public void saveSMA(IAtsChangeSet changes) { super.saveSMA(changes); try { ActionArtifact parentAction = getParentActionArtifact(); if (parentAction != null) { ActionArtifactRollup rollup = new ActionArtifactRollup(parentAction); rollup.resetAttributesOffChildren(); changes.add(parentAction); <START> } <END> } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, "Can't reset Action parent of children", ex); } }</code><technical_language>If parent is null, this caller/log indication a problem. Is this desired</technical_language>

Target:
public void saveSMA(IAtsChangeSet changes) { super.saveSMA(changes); try { ActionArtifact parentAction = getParentActionArtifact(); ActionArtifactRollup rollup = new ActionArtifactRollup(parentAction); rollup.resetAttributesOffChildren(); changes.add(parentAction); } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, "Can't reset Action parent of children", ex); } }
Source:
<code><START> public boolean canCreateChildProject() { <END> return user.getCapabilityByProject(state.getProject().getNameKey()) .canCreateProject(); }</code><technical_language>Is a child project? In commit message talk sub-projects, terminology a bit confusing, new project child projects (i.e. do inherit existing project?)</technical_language>

Target:
public boolean canCreateChildProject() { return user.getCapabilities().canAdministrateServer() || user.getCapabilityByProject(state.getProject().getNameKey()) .canCreateProject(); }
Source:
<code>private void addInterfacesFromTemplate() { <START> String macRegex = "^(\\p{XDigit}{2}:){5}\\p{XDigit}{2}$"; <END> VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(); for (VmNetworkInterface iface : getVm().getInterfaces()) { if (iface.getId() == null) { iface.setId(Guid.NewGuid()); } if (StringHelper.isNullOrEmpty(iface.getMacAddress())) { iface.setMacAddress(MacPoolManager.getInstance().allocateNewMac()); } if (!Regex.IsMatch(iface.getMacAddress(), macRegex)) { AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("MacAddress", iface.getMacAddress()); logable.AddCustomValue("IfaceName", iface.getName()); AuditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_IMPORT_INTERFACES_WITH_INVALID_MAC_ADDRESS); } iface.setVmTemplateId(null); iface.setVmId(getVm().getStaticData().getId()); iface.setVmName(getVm().getvm_name()); if (getParameters().isImportAsNewEntity()) { macAdded = true; } else { macAdded = vmInterfaceManager.add(iface, getCompensationContext()); } } }</code><technical_language>VmNetworkInterface a constant VALID_MAC_ADDRESS_FORMAT use</technical_language>

Target:
private void addInterfacesFromTemplate() { VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(); for (VmNetworkInterface iface : getVm().getInterfaces()) { if (iface.getId() == null) { iface.setId(Guid.NewGuid()); } validateImportMacAddress(iface); iface.setVmTemplateId(null); iface.setVmId(getVm().getStaticData().getId()); iface.setVmName(getVm().getvm_name()); if (getParameters().isImportAsNewEntity()) { macAdded = true; } else { macAdded = vmInterfaceManager.add(iface, getCompensationContext()); } } }
Source:
<code>private void scheduleRefreshAccessToken(final AuthenticationServer authServer, long expireDateInMs) { long refreshAfter = expireDateInMs - System.currentTimeMillis() - REFRESH_MARGIN_DELAY; if (refreshAfter < 0) { RealmLog.debug("Expires time already reached for the access token, refresh soon"); <START> refreshAfter = REFRESH_MARGIN_DELAY; <END> } RealmLog.debug("Scheduling an access_token refresh in " + (refreshAfter) + " milliseconds"); if (refreshTokenTask != null) { refreshTokenTask.cancel(); } ScheduledFuture<?> task = REFRESH_TOKENS_EXECUTOR.schedule(new Runnable() { @Override public void run() { if (!isClosed && !Thread.currentThread().isInterrupted()) { refreshAccessToken(authServer); } } }, refreshAfter, TimeUnit.MILLISECONDS); refreshTokenTask = new RealmAsyncTaskImpl(task, REFRESH_TOKENS_EXECUTOR); }</code><technical_language>Nitpick: 10 seconds a while wait there, or</technical_language>

Target:
private void scheduleRefreshAccessToken(final AuthenticationServer authServer, long expireDateInMs) { long refreshAfter = expireDateInMs - System.currentTimeMillis() - REFRESH_MARGIN_DELAY; if (refreshAfter < 0) { RealmLog.debug("Expires time already reached for the access token, refresh as soon as possible"); refreshAfter = REFRESH_MARGIN_DELAY; } RealmLog.debug("Scheduling an access_token refresh in " + (refreshAfter) + " milliseconds"); if (refreshTokenTask != null) { refreshTokenTask.cancel(); } ScheduledFuture<?> task = REFRESH_TOKENS_EXECUTOR.schedule(new Runnable() { @Override public void run() { if (!isClosed && !Thread.currentThread().isInterrupted()) { refreshAccessToken(authServer); } } }, refreshAfter, TimeUnit.MILLISECONDS); refreshTokenTask = new RealmAsyncTaskImpl(task, REFRESH_TOKENS_EXECUTOR); }
Source:
<code>public void stopJoiningNodes() throws Exception { deployer.undeploy(getJoiningNodeName()); deployer.undeploy(COORDINATOR_NODE); try { controller.stop(getJoiningNodeName()); <START> controller.stop(COORDINATOR_NODE); <END> } catch(Exception e) { LOG.warn("Server stop failed with %s", e.getCause()); controller.kill(COORDINATOR_NODE); controller.kill(getJoiningNodeName()); } assertFalse(controller.isStarted(getJoiningNodeName())); assertFalse(controller.isStarted(COORDINATOR_NODE)); }</code><technical_language>I this in @AfterClass method, stopJoiningNodes run if of previous tests fails. need other controller.kill() calls in startNodes</technical_language>

Target:
public void stopJoiningNodes() throws Exception { deployer.undeploy(getJoiningNodeName()); deployer.undeploy(COORDINATOR_NODE); try { controller.stop(getJoiningNodeName()); } catch(Exception e) { LOG.warn("Joining node stop failed with %s", e.getCause()); controller.kill(getJoiningNodeName()); } try { controller.stop(COORDINATOR_NODE); } catch(Exception e) { LOG.warn("Coordinator node stop failed with %s", e.getCause()); controller.kill(COORDINATOR_NODE); } assertFalse(controller.isStarted(getJoiningNodeName())); assertFalse(controller.isStarted(COORDINATOR_NODE)); }
Source:
<code>public ChemComp getChemComp(String recordName) { recordName = recordName.toUpperCase().trim(); boolean haveFile = true; if ( recordName.equals("?")){ return null; } if ( ! fileExists(recordName)) { checkDoFirstInstall(); } if ( ! fileExists(recordName)) { haveFile = downloadChemCompRecord(recordName); } if (haveFile) { String filename = getLocalFileName(recordName); InputStream inStream = null; try { InputStreamProvider isp = new InputStreamProvider(); inStream = isp.getInputStream(filename); MMcifParser parser = new SimpleMMcifParser(); ChemCompConsumer consumer = new ChemCompConsumer(); parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(inStream))); ChemicalComponentDictionary dict = consumer.getDictionary(); ChemComp chemComp = dict.getChemComp(recordName); if(chemComp != null) { return chemComp; } } catch (IOException e) { logger.error("Could not parse chemical component file {}. Error: {}. " + "There will be no chemical component info available for {}", filename, e.getMessage(), recordName); } finally{ if(inStream!=null){ try { inStream.close(); } catch (IOException e) { logger.error("Could not close chemical component file {}. A resource leak could occur!!", filename); } } } } if( fallback == null) { fallback = new ReducedChemCompProvider(); } <START> return fallback.getChemComp(recordName); <END> }</code><technical_language>Is a warning logged fallback is used? That'd important, users aware investigate if wrong in code file system</technical_language>

Target:
public ChemComp getChemComp(String recordName) { recordName = recordName.toUpperCase().trim(); boolean haveFile = true; if ( recordName.equals("?")){ return null; } if ( ! fileExists(recordName)) { checkDoFirstInstall(); } if ( ! fileExists(recordName)) { haveFile = downloadChemCompRecord(recordName); } if (haveFile) { String filename = getLocalFileName(recordName); InputStream inStream = null; try { InputStreamProvider isp = new InputStreamProvider(); inStream = isp.getInputStream(filename); MMcifParser parser = new SimpleMMcifParser(); ChemCompConsumer consumer = new ChemCompConsumer(); parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(inStream))); ChemicalComponentDictionary dict = consumer.getDictionary(); ChemComp chemComp = dict.getChemComp(recordName); if(chemComp != null) { return chemComp; } } catch (IOException e) { logger.error("Could not parse chemical component file {}. Error: {}. " + "There will be no chemical component info available for {}", filename, e.getMessage(), recordName); } finally{ if(inStream!=null){ try { inStream.close(); } catch (IOException e) { logger.error("Could not close chemical component file {}. A resource leak could occur!!", filename); } } } } if( fallback == null) { fallback = new ReducedChemCompProvider(); } logger.warn("Falling back to ReducedChemCompProvider for {}. This could indicate a network error.", recordName); return fallback.getChemComp(recordName); }
Source:
<code>Properties loadCostProperties(Path cachePath, String machineType) { Properties prop = new Properties(); try { <START> InputStream inp = new FileInputStream(cachePath.toString()); <END> prop.load(inp); return prop; } catch (FileNotFoundException fnf) { LOG.error("cost properties does not exist, using default values"); return null; } catch (IOException e) { LOG.error("error loading properties, using default values"); return null; } }</code><technical_language>This input stream is closed. follow a standard try-finally pattern for closing input stream. java 7, do try-with-resources pattern, I hraven requires java 7, out of question</technical_language>

Target:
Properties loadCostProperties(Path cachePath, String machineType) { Properties prop = new Properties(); InputStream inp = null; try { inp = new FileInputStream(cachePath.toString()); prop.load(inp); return prop; } catch (FileNotFoundException fnf) { LOG.error("cost properties does not exist, using default values"); return null; } catch (IOException e) { LOG.error("error loading properties, using default values"); return null; } finally { if (inp != null) { try { inp.close(); } catch (IOException ignore) { } } } }