auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String resolveAsStringConstant(ExpressionTree tree) { ExpressionTree expression = tree; while (expression.is(Tree.Kind.PARENTHESIZED_EXPRESSION)) { expression = ((ParenthesizedTree) expression).expression(); } if (expression.is(Tree.Kind.MEMBER_SELECT)) { expression = ((MemberSelectExpressionTree) expression).identifier(); } if (expression.is(Tree.Kind.IDENTIFIER)) { IdentifierTree id = (IdentifierTree) expression; Symbol symbol = id.symbol(); if (symbol instanceof JavaSymbol.ConstantJavaSymbol) { Object constantValue = ((JavaSymbol.ConstantJavaSymbol) symbol).value(); if (constantValue instanceof String) { return (String) constantValue; } } } if (expression.is(Tree.Kind.STRING_LITERAL)) { return LiteralUtils.trimQuotes(((LiteralTree) expression).value()); } if (expression.is(Tree.Kind.PLUS)) { BinaryExpressionTree binaryExpression = (BinaryExpressionTree) expression; String left = resolveAsStringConstant(binaryExpression.leftOperand()); String right = resolveAsStringConstant(binaryExpression.rightOperand()); if (left != null && right != null) { return left + right; } } return null; }

Target:
public static String resolveAsStringConstant(ExpressionTree tree) { Object constant = resolveAsConstant(tree); return constant instanceof String ? (String) constant : null; }
Source:
private static CloseableHttpResponse getAllRoutingData() throws IOException { HttpGet requestAllData = new HttpGet( MSDS_ENDPOINT + MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT); try (CloseableHttpClient httpClient = HttpClients.custom() .setConnectionBackoffStrategy(new DefaultBackoffStrategy()) .setRetryHandler(new DefaultHttpRequestRetryHandler()).build()) { return httpClient.execute(requestAllData); } }

Target:
private static String getAllRoutingData() throws IOException { ENDPOINT should provide high-availability - it risks becoming a single point of failure if it's backed by a single IP address/host HttpGet requestAllData = new HttpGet( MSDS_ENDPOINT + MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT); RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_TIMEOUT_IN_MS) .setConnectionRequestTimeout(HTTP_TIMEOUT_IN_MS).setSocketTimeout(HTTP_TIMEOUT_IN_MS) .build(); try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config) .setConnectionBackoffStrategy(new DefaultBackoffStrategy()) .setRetryHandler(new DefaultHttpRequestRetryHandler()).build()) { HttpEntity entity = httpClient.execute(requestAllData).getEntity(); if (entity == null) { throw new IOException("Response's entity is null!"); } return EntityUtils.toString(entity, "UTF-8"); } }
Source:
public void testNonQuietOutputIsSorted() throws Exception { when(options.getBoolean("q")).thenReturn(false); int ret = command.run(options, client, out, false, null); assertEquals(0, ret); assertEquals(expectedOrder, readJobIdsFromOutput(true)); }

Target:
public void testNonQuietOutputIsSorted() throws Exception { when(options.getBoolean("q")).thenReturn(false); final int ret = command.run(options, client, out, false, null); assertEquals(0, ret); assertEquals(expectedOrder, readJobIdsFromOutput(true)); }
Source:
static final File baseSchemaIndexFolder( File databaseStoreDir ) { return path( databaseStoreDir, "schema", "index" ); }

Target:
static File baseSchemaIndexFolder( File databaseStoreDir ) { return path( databaseStoreDir, "schema", "index" ); }
Source:
public String setInputCommand(Command command){ switch(((StringType) command).toString().toLowerCase()){ case "btaudio": return "extInput:btAudio"; case "tv": return "extInput:tv"; case "analog": return "extInput:line"; case "usb": return "storage:usb1"; case "network": return "dlna:music"; } return ((StringType) command).toString(); }

Target:
public String setInputCommand(Command command) { switch (command.toString().toLowerCase()) { case "btaudio": return "extInput:btAudio"; case "tv": return "extInput:tv"; case "analog": return "extInput:line"; case "usb": return "storage:usb1"; case "network": return "dlna:music"; case "cast": return "cast:audio"; } return command.toString(); }
Source:
private XADataSource createXaDataSourceInstance(String className) { try { Class<?> dataSourceClass = ClassUtils.forName(className, this.getClass().getClassLoader()); Object instance = BeanUtils.instantiate(dataSourceClass); Assert.isInstanceOf(XADataSource.class, instance); return (XADataSource) instance; } catch (Exception ex) { throw new IllegalStateException( "Unable to create XADataSource instance from '" + className + "'"); } }

Target:
private XADataSource createXaDataSourceInstance(String className) { try { Class<?> dataSourceClass = ClassUtils.forName(className, this.getClass().getClassLoader()); Object instance = BeanUtils.instantiate(dataSourceClass); Assert.isInstanceOf(XADataSource.class, instance); return (XADataSource) instance; } catch (Exception ex) { throw new IllegalStateException( "Unable to create XADataSource instance from '" + className + "'", ex); } }
Source:
private void setValuesForGroupby(List<BlockBuilder> blockBuilders, List<Type> types, int numGroupByClause, JsonNode group, String[] values) { for (int k = 0; k < group.size(); k++) { setValue(types.get(k), blockBuilders.get(k), group.get(k).asText()); } for (int aggrIndex = 0; aggrIndex < values.length; ++aggrIndex) { int metricColumnIndex = aggrIndex + numGroupByClause; if (metricColumnIndex < blockBuilders.size()) { setValue(types.get(metricColumnIndex), blockBuilders.get(metricColumnIndex), values[aggrIndex]); } } }

Target:
private void setValuesForGroupby( List<BlockBuilder> blockBuilders, List<Type> types, int numGroupByClause, JsonNode group, String[] values) { for (int i = 0; i < group.size(); i++) { setValue(types.get(i), blockBuilders.get(i), group.get(i).asText()); } for (int i = 0; i < values.length; i++) { int metricColumnIndex = i + numGroupByClause; if (metricColumnIndex < blockBuilders.size()) { setValue(types.get(metricColumnIndex), blockBuilders.get(metricColumnIndex), values[i]); } } }
Source:
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int lastIndex = data.read(cache); if (lastIndex == -1 && currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } currentTotalLength[0] += lastIndex; return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error details: " + e.getMessage())); } }); }

Target:
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { Pair pair = new Pair(); final long[] currentTotalLength = new long[1]; return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[blockSize]; try { int numBytes = data.read(buffer); if (numBytes > 0) { currentTotalLength[0] += numBytes; return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }) .takeUntil(p -> p.readBytes() == -1 || currentTotalLength[0] > length) .filter(p -> p.readBytes() > 0) .flatMap(p -> { if (currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else if (currentTotalLength[0] > length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else { return Flux.just(p.buffer()); } }); }
Source:
private static void invokeForEachKeyFactory(KeyFactoryRunnable runnable) throws Exception { for (Provider provider : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider)); } catch (Exception e) { throw new Exception("provider: " + provider.getName(), e); } } }

Target:
private static void invokeForEachKeyFactory(KeyFactoryRunnable runnable) throws Exception { for (Provider provider : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider)); } catch (Throwable e) { throw new Exception("provider: " + provider.getName(), e); } } }
Source:
protected void doConnectViaSsh(Deployment deployment, LoginCredentials creds) { SshClient ssh = sshFactory.create(HostAndPort.fromParts(deployment.virtualIPs().get(0).address(), 22), creds); try { ssh.connect(); ExecResponse hello = ssh.exec("echo hello"); assertEquals(hello.getOutput().trim(), "hello"); System.err.println(ssh.exec("df -k").getOutput()); System.err.println(ssh.exec("mount").getOutput()); System.err.println(ssh.exec("uname -a").getOutput()); } finally { if (ssh != null) ssh.disconnect(); } }

Target:
protected void doConnectViaSsh(Deployment deployment, LoginCredentials creds) { SshClient ssh = sshFactory.create(HostAndPort.fromParts(deployment.virtualIPs().get(0).address(), 22), creds); try { ssh.connect(); ExecResponse hello = ssh.exec("echo hello"); assertEquals(hello.getOutput().trim(), "hello"); } finally { if (ssh != null) ssh.disconnect(); } }
Source:
public GarageDoorData(JsonNode rootNode) throws IOException { if (rootNode.has("Devices")) { JsonNode node = rootNode.get("Devices"); if (node.isArray()) { logger.trace("Chamberlain MyQ Devices:"); int arraysize = node.size(); for (int i = 0; i < arraysize; i++) { int deviceId = node.get(i).get("MyQDeviceId").asInt(); String deviceName = node.get(i).get("SerialNumber") .asText(); String deviceType = node.get(i).get("MyQDeviceTypeName") .asText(); if (deviceType.contains("Garage") && deviceType.contains("Door") && deviceType.contains("Opener")) { JsonNode attributes = node.get(i).get("Attributes"); if (attributes.isArray()) { int attributesSize = attributes.size(); for (int j = 0; j < attributesSize; j++) { String attributeName = attributes.get(j) .get("AttributeDisplayName").asText(); if (attributeName.contains("doorstate")) { int doorstate = attributes.get(j) .get("Value").asInt(); logger.trace( "DeviceID: DeviceName: DeviceType: Doorstate : ", deviceId, deviceName, deviceType, doorstate); devices.add(new GarageDoorDevice(deviceId, deviceType, deviceName, doorstate)); break; } } } } } } } }

Target:
public GarageDoorData(JsonNode rootNode) throws IOException { if (rootNode.has("Devices")) { JsonNode node = rootNode.get("Devices"); if (node.isArray()) { logger.trace("Chamberlain MyQ Devices:"); int arraysize = node.size(); for (int i = 0; i < arraysize; i++) { int deviceId = node.get(i).get("MyQDeviceId").asInt(); String deviceName = node.get(i).get("SerialNumber") .asText(); String deviceType = node.get(i).get("MyQDeviceTypeName") .asText(); if (DEVICE_TYPE_PATTERN.matcher(deviceType).matches()) { JsonNode attributes = node.get(i).get("Attributes"); if (attributes.isArray()) { int attributesSize = attributes.size(); for (int j = 0; j < attributesSize; j++) { String attributeName = attributes.get(j) .get("AttributeDisplayName").asText(); if (attributeName.contains("doorstate")) { int doorstate = attributes.get(j) .get("Value").asInt(); logger.trace( "DeviceID: DeviceName: DeviceType: Doorstate : ", deviceId, deviceName, deviceType, doorstate); devices.add(new GarageDoorDevice(deviceId, deviceType, deviceName, doorstate)); break; } } } } } } } }
Source:
public static void setStartupBehavior(int startupBehavior) { log(LogUtil.info("setStartupBehavior = '" + startupBehavior + "' 0=dialog, 1=background, 2=disable")); IEclipsePreferences node = getPreferences(); if (startupBehavior == TipManager.START_DIALOG) { node.put(PREF_STARTUP_BEHAVIOR, PREF_STARTUP_BEHAVIOR_DIALOG); } else if (startupBehavior == TipManager.START_BACKGROUND) { node.put(PREF_STARTUP_BEHAVIOR, PREF_STARTUP_BEHAVIOR_BACKGROUND); } else { node.put(PREF_STARTUP_BEHAVIOR, PREF_STARTUP_BEHAVIOR_DISABLE); } try { node.flush(); } catch (BackingStoreException e) { throw new RuntimeException(e); } }

Target:
public static void setStartupBehavior(int startupBehavior) { log(LogUtil.info("setStartupBehavior = '" + startupBehavior + "' 0=dialog, 1=background, 2=disable")); IEclipsePreferences node = getPreferences(); if (startupBehavior == TipManager.START_DIALOG) { node.put(PREF_STARTUP_BEHAVIOR, PREF_STARTUP_BEHAVIOR_DIALOG); } else if (startupBehavior == TipManager.START_DISABLE) { node.put(PREF_STARTUP_BEHAVIOR, PREF_STARTUP_BEHAVIOR_DISABLE); } else { node.put(PREF_STARTUP_BEHAVIOR, PREF_STARTUP_BEHAVIOR_BACKGROUND); } try { node.flush(); } catch (BackingStoreException e) { log(LogUtil.error(e)); } }
Source:
public void testOnStartCommandStartReplicationCommandsQueuedConsecutiveDuplicatesRemoved() { PeriodicReplicationService service = new TestReplicationService(mMockContext); Intent startIntent = new Intent(mMockContext, TestReplicationService.class); startIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService.COMMAND_START_REPLICATION); Intent stopIntent = new Intent(mMockContext, TestReplicationService.class); stopIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService .COMMAND_STOP_REPLICATION); service.setReplicationPolicyManager(mMockReplicationPolicyManager); service.onCreate(); final CountDownLatch latch = new CountDownLatch(2); service.setOperationStartedListener(new PeriodicReplicationService .OperationStartedListener() { @Override public void operationStarted(int operationId) { if (latch.getCount() == 2 && operationId == PeriodicReplicationService .COMMAND_START_REPLICATION) { latch.countDown(); } else if (latch.getCount() == 1 && operationId == PeriodicReplicationService .COMMAND_STOP_REPLICATION) { latch.countDown(); } } }); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(stopIntent, 0, 0); service.setReplicators(mMockReplicators); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }

Target:
public void testOnStartCommandStartReplicationCommandsQueuedConsecutiveDuplicatesRemoved() { PeriodicReplicationService service = new TestReplicationService(mMockContext); Intent startIntent = new Intent(mMockContext, TestReplicationService.class); startIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService.COMMAND_START_REPLICATION); Intent stopIntent = new Intent(mMockContext, TestReplicationService.class); stopIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService .COMMAND_STOP_REPLICATION); service.setReplicationPolicyManager(mMockReplicationPolicyManager); service.onCreate(); final CountDownLatch latch = new CountDownLatch(2); service.setOperationStartedListener(new PeriodicReplicationService .OperationStartedListener() { @Override public void operationStarted(int operationId) { if (latch.getCount() == 2 && operationId == PeriodicReplicationService .COMMAND_START_REPLICATION) { latch.countDown(); } else if (latch.getCount() == 1 && operationId == PeriodicReplicationService .COMMAND_STOP_REPLICATION) { latch.countDown(); } else { fail("Unexpected command or commands received in incorrect order"); } } }); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(stopIntent, 0, 0); service.setReplicators(mMockReplicators); try { assertTrue("The countdown should reach zero", latch.await(DEFAULT_WAIT_SECONDS, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } }
Source:
public void testCanAttachToPackageMultipleNodes() { ClassNode node1 = new ClassNode(); InterfaceNode node2 = new InterfaceNode(); PackageNode node3 = new PackageNode(); aDiagram.addRootNode(node1); aDiagram.addRootNode(node2); aDiagram.addRootNode(node3); assertTrue(aBuilder.canAttachToPackage(Arrays.asList(node1, node2))); }

Target:
public void testCanAttachToPackageMultipleNodes() { ClassNode child1 = new ClassNode(); InterfaceNode child2 = new InterfaceNode(); PackageNode parent = new PackageNode(); aDiagram.addRootNode(child1); aDiagram.addRootNode(child2); aDiagram.addRootNode(parent); assertTrue(aBuilder.canAttachToPackage(Arrays.asList(child1, child2))); }
Source:
private static int calculateBinaryShiftCost(State state) { if (state.binaryShiftByteCount > 62) { return 21; } else if (state.binaryShiftByteCount > 31) { return 20; } else if (state.binaryShiftByteCount > 0) { return 10; } else { return 0; } }

Target:
private static int calculateBinaryShiftCost(State state) { if (state.binaryShiftByteCount > 62) { return 21; } if (state.binaryShiftByteCount > 31) { return 20; } if (state.binaryShiftByteCount > 0) { return 10; } return 0; }
Source:
public List<ValueReference> getAllPossibleValues(final Variable variable) { List<ValueReference> possibleValues = this.getCachedValues(false, variable); if (possibleValues.isEmpty()) { DataType dataType = variable.getScale().getDataType(); if (TermId.BREEDING_METHOD_CODE.getId() == variable.getId() || TermId.BREEDING_METHOD_VARIATE_CODE.getId() == variable.getId()) { dataType = DataType.BREEDING_METHOD; } switch (dataType) { case BREEDING_METHOD: possibleValues .add(new ValueReference(0, AppConstants.PLEASE_CHOOSE.getString(), AppConstants.PLEASE_CHOOSE.getString())); final List<ValueReference> allBreedingMethods = this.getAllBreedingMethods(true, this.contextUtil.getCurrentProgramUUID()); possibleValues.addAll(allBreedingMethods); this.possibleValuesCache.addPossibleValuesByDataType(DataType.BREEDING_METHOD, allBreedingMethods); break; case LOCATION: possibleValues = this.getAllLocations(true); this.possibleValuesCache.addLocations(true, possibleValues); break; case PERSON: possibleValues = this.convertPersonsToValueReferences(this.fieldbookMiddlewareService.getAllPersonsOrderedByLocalCentral()); this.possibleValuesCache.addPossibleValuesByDataType(DataType.PERSON, possibleValues); break; case CATEGORICAL_VARIABLE: for (final TermSummary value : variable.getScale().getCategories()) { possibleValues.add(new ValueReference(value)); } this.possibleValuesCache.addPossibleValues(variable.getId(), possibleValues); break; default: break; } } return possibleValues; }

Target:
public List<ValueReference> getAllPossibleValues(final Variable variable) { return this.getAllPosibleValues(variable, true, true); }
Source:
public Map<String, Object> execute(Map<String, Object> context) { for (String uid : ruleUIDs) { if (ruleRegistry != null) { ruleRegistry.runNow(uid, considerConditions); } else { logger.warn("Action is not applyed to because RuleRegistry is not available.", uid); } } return null; }

Target:
public Map<String, Object> execute(Map<String, Object> context) { for (String uid : ruleUIDs) { if (ruleRegistry != null) { ruleRegistry.runNow(uid, considerConditions); } else { logger.warn("Action is not applied to because RuleRegistry is not available.", uid); } } return null; }
Source:
public void populateCachedValues(Collection<?> objects, Map<Long, String> preComputedValueMap) { for (Object element : objects) { Artifact artifactCursor = getArtifactFromElement(element); if (artifactCursor != null) { Long artId = artifactCursor.getId(); if (!artIdToName.containsKey(artId)) { if (artifactCursor.isDeleted()) { artIdToName.put(artId, "deleted"); } else { StringBuilder builder = new StringBuilder(20); Artifact root = OseeSystemArtifacts.getDefaultHierarchyRootArtifact(artifactCursor.getBranch()); String error = Strings.emptyString(); while (!artifactCursor.equals(root)) { Artifact parent = null; try { parent = artifactCursor.getParent(); } catch (OseeCoreException ex) { error = "Hierarchy Index unavailable: " + ex.getLocalizedMessage(); break; } if (parent == null) { error = "not connected to root"; break; } builder.insert(0, getPosition(artifactCursor) + "."); artifactCursor = parent; } if (error.isEmpty()) { if (builder.length() > 0) { artIdToName.put(artId, builder.substring(0, builder.length() - 1)); } else { artIdToName.put(artId, "no parent"); } } else { artIdToName.put(artId, error); } } } } } parentToChildrenCache.clear(); }

Target:
public void populateCachedValues(Collection<?> objects, Map<Long, String> preComputedValueMap) { for (Object element : objects) { Artifact artifactCursor = getArtifactFromElement(element); if (artifactCursor != null) { Long artId = artifactCursor.getId(); if (!preComputedValueMap.containsKey(artId)) { if (artifactCursor.isDeleted()) { preComputedValueMap.put(artId, "deleted"); } else { StringBuilder builder = new StringBuilder(20); String error = Strings.emptyString(); while (!artifactCursor.equals(CoreArtifactTokens.DefaultHierarchyRoot)) { Artifact parent = null; try { parent = artifactCursor.getParent(); } catch (OseeCoreException ex) { error = "Hierarchy Index unavailable: " + ex.getLocalizedMessage(); break; } if (parent == null) { error = "not connected to root"; break; } builder.insert(0, getPosition(artifactCursor) + "."); artifactCursor = parent; } if (error.isEmpty()) { if (builder.length() > 0) { preComputedValueMap.put(artId, builder.substring(0, builder.length() - 1)); } else { preComputedValueMap.put(artId, "no parent"); } } else { preComputedValueMap.put(artId, error); } } } } } parentToChildrenCache.clear(); }
Source:
private int writeString(PutRecordRequest putRecordRequest, Object data) { putRecordRequest.setData(ByteBuffer.wrap(Bytes.toBytes((String) data))); kinesisClient.putRecord(putRecordRequest); return 1; }

Target:
private int writeString(PutRecordRequest putRecordRequest, Object data) { putRecordRequest.setData(ByteBuffer.wrap(Bytes.toBytes((String) data))); return putRecord(putRecordRequest); }
Source:
public Collection<Replay> getLocalReplays() { Collection<Replay> replayInfos = new ArrayList<>(); String replayFileGlob = clientProperties.getReplay().getReplayFileGlob(); Path replaysDirectory = preferencesService.getReplaysDirectory(); if (Files.notExists(replaysDirectory)) { noCatch(() -> createDirectories(replaysDirectory)); } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replaysDirectory, replayFileGlob)) { for (Path replayFile : directoryStream) { try { LocalReplayInfo replayInfo = replayFileReader.parseMetaData(replayFile); FeaturedMod featuredMod = modService.getFeaturedMod(replayInfo.getFeaturedMod()).getNow(FeaturedMod.UNKNOWN); mapService.findByMapFolderName(replayInfo.getMapname()) .thenAccept(mapBean -> { if (!mapBean.isPresent()) { notificationService.addNotification(new ImmediateNotification( i18n.get("errorTitle"), i18n.get("mapNotFound", replayInfo.getMapname()), WARN )); return; } replayInfos.add(new Replay(replayInfo, replayFile, featuredMod, mapBean.get())); }); } catch (Exception e) { logger.warn(MessageFormat.format("Could not read replay file {0}", replayFile), e); moveCorruptedReplayFile(replayFile); } } } return replayInfos; }

Target:
public Collection<Replay> getLocalReplays() { Collection<Replay> replayInfos = new ArrayList<>(); String replayFileGlob = clientProperties.getReplay().getReplayFileGlob(); Path replaysDirectory = preferencesService.getReplaysDirectory(); if (Files.notExists(replaysDirectory)) { noCatch(() -> createDirectories(replaysDirectory)); } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replaysDirectory, replayFileGlob)) { for (Path replayFile : directoryStream) { try { LocalReplayInfo replayInfo = replayFileReader.parseMetaData(replayFile); FeaturedMod featuredMod = modService.getFeaturedMod(replayInfo.getFeaturedMod()).getNow(FeaturedMod.UNKNOWN); mapService.findByMapFolderName(replayInfo.getMapname()) .thenAccept(mapBean -> { if (!mapBean.isPresent()) { notificationService.addNotification(new ImmediateNotification( i18n.get("errorTitle"), i18n.get("mapNotFound", replayInfo.getMapname()), WARN )); return; } replayInfos.add(new Replay(replayInfo, replayFile, featuredMod, mapBean.get())); }); } catch (Exception e) { logger.warn("Could not read replay file '{}'", replayFile, e); moveCorruptedReplayFile(replayFile); } } } return replayInfos; }
Source:
public void noLocalBinaryTest() throws Exception { String mimetype = "text/plain"; String checksumPrefix = "urn:sha1:"; String checksum = "61673dacf6c6eea104e77b151584ed7215388ea3"; Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(RESC_ID); resc.addProperty(RDF.type, Fcrepo4Repository.Binary); resc.addProperty(Ebucore.hasMimeType, mimetype); resc.addProperty(Premis.hasMessageDigest, checksumPrefix + checksum); setMessageBody(model); processor.process(exchange); verify(message).setHeader(CdrBinaryChecksum, checksum); verify(message).setHeader(CdrBinaryMimeType, mimetype); verify(message, never()).setHeader(eq(CdrBinaryPath), anyString()); verify(message, never()).setHeader(eq(CdrBinaryId), anyString()); }

Target:
public void noLocalBinaryTest() throws Exception { String mimetype = "text/plain"; String checksumPrefix = "urn:sha1:"; String checksum = "61673dacf6c6eea104e77b151584ed7215388ea3"; Model model = ModelFactory.createDefaultModel(); Resource resc = model.createResource(RESC_ID); resc.addProperty(RDF.type, Fcrepo4Repository.Binary); resc.addProperty(Ebucore.hasMimeType, mimetype); resc.addProperty(Premis.hasMessageDigest, checksumPrefix + checksum); setMessageBody(model); processor.process(exchange); verify(message).setHeader(CdrBinaryChecksum, checksum); verify(message).setHeader(CdrBinaryMimeType, mimetype); verify(message, never()).setHeader(eq(CdrBinaryPath), anyString()); }
Source:
public JobFutureTask(final JobManager jobManager, final RunMonitor runMonitor, final JobInput input, final CallableChain<RESULT> callableChain, final Callable<RESULT> callable) { super(() -> callableChain.call(callable) ); m_jobManager = jobManager; m_runMonitor = runMonitor; m_input = input; m_executionSemaphore = ExecutionSemaphore.get(input); m_callableChain = callableChain; m_completionPromise = new CompletionPromise<>(this, jobManager.getExecutor()); m_expirationDate = (input.getExpirationTimeMillis() != JobInput.EXPIRE_NEVER ? System.currentTimeMillis() + input.getExpirationTimeMillis() : null); m_executionHints.addAll(input.getExecutionHints()); m_jobManager.interceptCallableChain(m_callableChain, this, m_runMonitor, m_input); addRunMonitorCancelledCallableInterceptor(m_callableChain, m_runMonitor); m_callableChain.addLast(() -> { changeState(JobState.RUNNING); return null; }); m_trigger = createQuartzTrigger(input); m_calendar = (input.getExecutionTrigger() == null ? null : input.getExecutionTrigger().getCalendar()); m_firstFireTime = computeFirstFireTime(m_trigger); m_singleExecution = computeSingleExecuting(m_trigger, m_firstFireTime); m_delayedExecution = (input.getExecutionTrigger() == null ? false : computeDelayedExecuting(m_firstFireTime, m_input.getExecutionTrigger().getNow())); m_jobManager.registerFuture(this); m_runMonitor.registerCancellable(this); }

Target:
public JobFutureTask(final JobManager jobManager, final RunMonitor runMonitor, final JobInput input, final CallableChain<RESULT> callableChain, final Callable<RESULT> callable) { super(() -> callableChain.call(callable) ); m_jobManager = jobManager; m_runMonitor = runMonitor; m_input = input; m_executionSemaphore = ExecutionSemaphore.get(input); m_callableChain = callableChain; m_completionPromise = new CompletionPromise<>(this, jobManager.getExecutor()); m_expirationDate = (input.getExpirationTimeMillis() != JobInput.EXPIRE_NEVER ? System.currentTimeMillis() + input.getExpirationTimeMillis() : null); m_executionHints.addAll(input.getExecutionHints()); m_jobManager.interceptCallableChain(m_callableChain, this, m_runMonitor, m_input); m_callableChain.addLast(new ICallableInterceptor<RESULT>() { @Override public RESULT intercept(Chain<RESULT> chain) throws Exception { return null; } @Override public boolean isEnabled() { return m_runMonitor.isCancelled(); } }); m_callableChain.addLast(() -> { changeState(JobState.RUNNING); return null; }); m_trigger = createQuartzTrigger(input); m_calendar = (input.getExecutionTrigger() == null ? null : input.getExecutionTrigger().getCalendar()); m_firstFireTime = computeFirstFireTime(m_trigger); m_singleExecution = computeSingleExecuting(m_trigger, m_firstFireTime); m_delayedExecution = (input.getExecutionTrigger() == null ? false : computeDelayedExecuting(m_firstFireTime, m_input.getExecutionTrigger().getNow())); m_jobManager.registerFuture(this); m_runMonitor.registerCancellable(this); }
Source:
public static String formatAbbrev(final Context context, final Date date) { if (date == null) { return ""; } GregorianCalendar now = new GregorianCalendar(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); cal.add(GregorianCalendar.DAY_OF_MONTH, 10); boolean withinLastYear = now.get(Calendar.YEAR) == cal.get(Calendar.YEAR); int format = android.text.format.DateUtils.FORMAT_ABBREV_ALL; if (withinLastYear) { format |= android.text.format.DateUtils.FORMAT_NO_YEAR; } return android.text.format.DateUtils.formatDateTime(context, date.getTime(), format); }

Target:
public static String formatAbbrev(final Context context, final Date date) { if (date == null) { return ""; } GregorianCalendar now = new GregorianCalendar(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); boolean withinLastYear = now.get(Calendar.YEAR) == cal.get(Calendar.YEAR); int format = android.text.format.DateUtils.FORMAT_ABBREV_ALL; if (withinLastYear) { format |= android.text.format.DateUtils.FORMAT_NO_YEAR; } return android.text.format.DateUtils.formatDateTime(context, date.getTime(), format); }
Source:
public void afterTest(Method method) { Robolectric.flushBackgroundThreadScheduler(); assertTrue(asyncTestsPassed); }

Target:
public void afterTest(Method method) { Robolectric.flushBackgroundThreadScheduler(); if (!asyncExceptions.isEmpty()) { for(Throwable throwable: asyncExceptions) { throwable.printStackTrace(); fail("Test failed due to " + asyncExceptions.size() + " threads crashing off the main thread. See error log for more details"); } } }
Source:
public boolean isSubtypeOf(TypeValue other) { if (this == other) { return true; } if (!(other instanceof TupleTypeValue)) { return false; } TupleTypeValue oTuple = (TupleTypeValue) other; if (!(getSize() != oTuple.getSize())) { return false; } for (int i = 0; i < getSize(); ++i) { TypeValue myType = entry(i).getType(); TypeValue otherType = oTuple.entry(i).getType(); if (!(myType.isSubtypeOf(otherType) || otherType.isSubtypeOf(myType))) { return false; } } return true; }

Target:
public boolean isSubtypeOf(TypeValue other) { if (this == other) { return true; } if (!(other instanceof TupleTypeValue)) { return false; } TupleTypeValue oTuple = (TupleTypeValue) other; if (!(getSize() != oTuple.getSize())) { return false; } for (int i = 0; i < getSize(); ++i) { TypeValue myType = entry(i).getType(); TypeValue otherType = oTuple.entry(i).getType(); if (!myType.isSubtypeOf(otherType)) { return false; } } return true; }
Source:
PlanNodeStatsEstimate calculateJoinComplementStats( Optional<Expression> filter, List<JoinNode.EquiJoinClause> criteria, PlanNodeStatsEstimate leftStats, PlanNodeStatsEstimate rightStats, TypeProvider types) { if (leftStats.getOutputRowCount() == 0 || rightStats.getOutputRowCount() == 0) { return leftStats; } if (criteria.isEmpty()) { if (filter.isPresent()) { return PlanNodeStatsEstimate.unknown(); } return normalizer.normalize(leftStats.mapOutputRowCount(rowCount -> 0.0), types); } int numberOfFilterClauses = filter.map(expression -> extractConjuncts(expression).size()).orElse(0); return criteria.stream() .map(drivingClause -> calculateJoinComplementStats(leftStats, rightStats, drivingClause, criteria.size() - 1 + numberOfFilterClauses)) .filter(estimate -> !estimate.isOutputRowCountUnknown()) .max(comparingDouble(PlanNodeStatsEstimate::getOutputRowCount)) .map(estimate -> normalizer.normalize(estimate, types)) .orElse(PlanNodeStatsEstimate.unknown()); }

Target:
PlanNodeStatsEstimate calculateJoinComplementStats( Optional<Expression> filter, List<JoinNode.EquiJoinClause> criteria, PlanNodeStatsEstimate leftStats, PlanNodeStatsEstimate rightStats, TypeProvider types) { if (rightStats.getOutputRowCount() == 0) { return leftStats; } if (criteria.isEmpty()) { if (filter.isPresent()) { return PlanNodeStatsEstimate.unknown(); } return normalizer.normalize(leftStats.mapOutputRowCount(rowCount -> 0.0), types); } int numberOfFilterClauses = filter.map(expression -> extractConjuncts(expression).size()).orElse(0); return criteria.stream() .map(drivingClause -> calculateJoinComplementStats(leftStats, rightStats, drivingClause, criteria.size() - 1 + numberOfFilterClauses)) .filter(estimate -> !estimate.isOutputRowCountUnknown()) .max(comparingDouble(PlanNodeStatsEstimate::getOutputRowCount)) .map(estimate -> normalizer.normalize(estimate, types)) .orElse(PlanNodeStatsEstimate.unknown()); }
Source:
public boolean validateSettings() { try { DateTimeFormatter.ofPattern(markTimeStampFormatProperty.getValue()); } catch (IllegalArgumentException exception) { DefaultTaskExecutor.runInJavaFXThread(() -> dialogService.showErrorDialogAndWait(Localization.lang("Invalid date format"), Localization.lang("The chosen date format for new entries is not valid"))); return false; } return true; }

Target:
public boolean validateSettings() { ValidationStatus status = markTimeStampFormatValidationStatus(); if (!status.isValid()) { dialogService.showErrorDialogAndWait(status.getHighestMessage().get().getMessage()); return false; } return true; }
Source:
public static boolean isSunJDK() { return JAVA_VM_VENDOR.toUpperCase().contains("sun") || JAVA_VM_VENDOR.toUpperCase().contains("oracle"); }

Target:
public static boolean isSunJDK() { return JAVA_VM_VENDOR.toLowerCase().contains("sun") || JAVA_VM_VENDOR.toLowerCase().contains("oracle"); }
Source:
public Callsite getCallsite(String eventName) { return callsitesByName.get(eventName).getFirst(); }

Target:
public CTFCallsite getCallsite(String eventName) { return callsitesByName.get(eventName).getFirst(); }
Source:
public void blockPorts(final Range<Integer> blockedRange) { checkNotNull(blockedRange); synchronized (reservedPorts) { this.blockedPortRanges.add(blockedRange); } }

Target:
public synchronized void blockPorts(final Range<Integer> blockedRange) { checkNotNull(blockedRange); this.blockedPortRanges.add(blockedRange); }
Source:
public AutoCompletionCandidates doAutoCompleteApplication(@QueryParameter final String value, @AncestorInPath AbstractProject project) { String resolvedApplicationName = expandValue(value, project); final AutoCompletionCandidates applicationCadidates = new AutoCompletionCandidates(); final String applicationName = DeployitServerFactory.getNameFromId(resolvedApplicationName); DeployitNotifier deployitNotifier = RepositoryUtils.retrieveDeployitNotifierFromProject(project); if (deployitNotifier != null) { Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(deployitNotifier.credential, overridingcredential, project); if (null != deployitServer) { List<String> applicationSuggestions = deployitServer.search(DeployitDescriptorRegistry.UDM_APPLICATION, applicationName + "%"); for (String applicationSuggestion : applicationSuggestions) { applicationCadidates.add(applicationSuggestion); } } } return applicationCadidates; }

Target:
public AutoCompletionCandidates doAutoCompleteApplication(@QueryParameter final String value, @AncestorInPath AbstractProject project) { project.checkPermission(Jenkins.ADMINISTER); String resolvedApplicationName = expandValue(value, project); final AutoCompletionCandidates applicationCadidates = new AutoCompletionCandidates(); final String applicationName = DeployitServerFactory.getNameFromId(resolvedApplicationName); DeployitNotifier deployitNotifier = RepositoryUtils.retrieveDeployitNotifierFromProject(project); if (deployitNotifier != null) { Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(deployitNotifier.credential, overridingcredential, project); if (null != deployitServer) { List<String> applicationSuggestions = deployitServer.search(DeployitDescriptorRegistry.UDM_APPLICATION, applicationName + "%"); for (String applicationSuggestion : applicationSuggestions) { applicationCadidates.add(applicationSuggestion); } } } return applicationCadidates; }
Source:
void testMergeSegments() throws InterruptedException { tokenStore.initializeTokenSegments(testSubject.getName(), 2); testSubject.start(); while (testSubject.processingStatus().isEmpty()) { Thread.sleep(10); } assertTrue(testSubject.mergeSegment(0).join(), "Expected merge to succeed"); waitForProcessingStatus(0, EventTrackerStatus::isMerging); waitForSegmentStart(0); assertArrayEquals(new int[]{0}, tokenStore.fetchSegments(testSubject.getName())); publishEvents(1); waitForProcessingNotInStatus(0, EventTrackerStatus::isMerging); }

Target:
void testMergeSegments() throws InterruptedException { tokenStore.initializeTokenSegments(testSubject.getName(), 2); testSubject.start(); while (testSubject.processingStatus().isEmpty()) { Thread.sleep(10); } int segmentId = 0; assertTrue(testSubject.mergeSegment(segmentId).join(), "Expected merge to succeed"); waitForProcessingStatus(segmentId, EventTrackerStatus::isMerging); waitForSegmentStart(segmentId); assertArrayEquals(new int[]{0}, tokenStore.fetchSegments(testSubject.getName())); publishEvents(1); waitForProcessingNotInStatus(segmentId, EventTrackerStatus::isMerging); }
Source:
public void createPluginSettings(PluginSettings newPluginSettings, Username currentUser, LocalizedOperationResult result) { final String pluginId = newPluginSettings.getPluginId(); if (hasPermission(currentUser, result) && checkPluginLoaded(pluginId, result) && checkPluginSupportsPluginSettings(pluginId, result)) { final String keyToLockOn = keyToLockOn(newPluginSettings.getPluginId()); synchronized (keyToLockOn) { final Plugin plugin = pluginDao.findPlugin(newPluginSettings.getPluginId()); if (plugin instanceof NullPlugin) { updatePluginSettingsAndNotifyPluginSettingsChangeListeners(result, newPluginSettings); } else { result.unprocessableEntity(LocalizedMessage.string("SAVE_FAILED_WITH_REASON", String.format("The plugin settings for plugin[%s] is already exist. In order to update the plugin settings refer the <LINK_0>", newPluginSettings.getPluginId(), CurrentGoCDVersion.getInstance().goVersion()))); } } } }

Target:
public void createPluginSettings(PluginSettings newPluginSettings, Username currentUser, LocalizedOperationResult result) { final String keyToLockOn = keyToLockOn(newPluginSettings.getPluginId()); synchronized (keyToLockOn) { if (hasPermission(currentUser, result)) { final Plugin plugin = pluginDao.findPlugin(newPluginSettings.getPluginId()); if (plugin instanceof NullPlugin) { updatePluginSettingsAndNotifyPluginSettingsChangeListeners(result, newPluginSettings); } else { result.unprocessableEntity(LocalizedMessage.string("SAVE_FAILED_WITH_REASON", String.format("Plugin settings for the plugin `%s` already exist. In order to update the plugin settings refer the <LINK_0>", newPluginSettings.getPluginId(), CurrentGoCDVersion.getInstance().goVersion()))); } } } }
Source:
public void testCreateReadDelete() { CommentManager commentManager = new CommentManagerImpl(CommentServiceHelper.getCommentService().getConfig()); DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", USERNAME); DocumentModel folder = systemSession.createDocumentModel("/", "folder", "Folder"); systemSession.createDocument(folder); DocumentModel doc = systemSession.createDocumentModel("/folder/", "TestFile", "File"); doc = systemSession.createDocument(doc); ACP acp = doc.getACP(); ACL acl = acp.getOrCreateACL(ACL.LOCAL_ACL); acl.add(new ACE(USERNAME, SecurityConstants.READ, true)); doc.setACP(acp, true); try (CloseableCoreSession userSession = coreFeature.openCoreSession(USERNAME)) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); DocumentModel comment = userSession.createDocumentModel(CommentsConstants.COMMENT_DOC_TYPE); comment.setPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH, COMMENT_CONTENT); commentManager.createComment(userDoc, comment); List<DocumentModel> dml = systemSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(1, dml.size()); dml = userSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(0, dml.size()); List<DocumentModel> comments = commentManager.getComments(userDoc); assertEquals(1, comments.size()); assertEquals(COMMENT_CONTENT, comments.get(0).getPropertyValue(COMMENT_CONTENT_PROPERTY_XPATH)); commentManager.deleteComment(userDoc, comments.get(0)); comments = commentManager.getComments(userDoc); assertEquals(0, comments.size()); } }

Target:
public void testCreateReadDelete() { DocumentModel userModel = userManager.getBareUserModel(); String schemaName = userManager.getUserSchemaName(); userModel.setProperty(schemaName, "username", USERNAME); DocumentModel folder = session.createDocumentModel("/", "folder", "Folder"); session.createDocument(folder); DocumentModel doc = session.createDocumentModel("/folder/", "TestFile", "File"); doc = session.createDocument(doc); ACP acp = doc.getACP(); ACL acl = acp.getOrCreateACL(ACL.LOCAL_ACL); acl.add(new ACE(USERNAME, SecurityConstants.READ, true)); doc.setACP(acp, true); try (CloseableCoreSession userSession = coreFeature.openCoreSession(USERNAME)) { DocumentModel userDoc = userSession.getDocument(doc.getRef()); Comment comment = new CommentImpl(); comment.setAuthor(session.getPrincipal().getName()); comment.setText(COMMENT_CONTENT); comment.setParentId(userDoc.getId()); commentManager.createComment(session, comment); List<DocumentModel> dml = session.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(1, dml.size()); dml = userSession.query(QUERY_COMMENTS_AS_DOCUMENTS); assertEquals(0, dml.size()); List<Comment> comments = commentManager.getComments(userSession, userDoc.getId()); assertEquals(1, comments.size()); assertEquals(COMMENT_CONTENT, comments.get(0).getText()); commentManager.deleteComment(userSession, comments.get(0).getId()); comments = commentManager.getComments(userSession, userDoc.getId()); assertEquals(0, comments.size()); } }
Source:
private void validateAddress(String address) throws BindingConfigParseException { String lowerCaseAddress = address.toLowerCase(); if ( !lowerCaseAddress.matches("[a-p]([1-9]|1[0-6])") ) { throw new BindingConfigParseException("The specified address '" + address + "' is not a valid X10 address."); } }

Target:
private void validateAddress(String address) throws BindingConfigParseException { Matcher matcher = X10_ADDRESS_PATTERN.matcher(address.toLowerCase()); if ( !matcher.matches() ) { throw new BindingConfigParseException("The specified address '" + address + "' is not a valid X10 address."); } }
Source:
public void createRegistryDatabase() throws ConfigurationException { String databaseType = null; File scripFile = null; try { databaseType = DatabaseCreator.getDatabaseType(this.dataSource.getConnection()); String scripPath = getDbScriptLocation(databaseType); scripFile = new File(scripPath); } catch (Exception e) { log.error("Unexpected error occurred while connecting to the database."); throw new ConfigurationException("Unexpected error occurred while connecting to" + " the database.", e); } if(scripFile.canRead()){ try { super.createRegistryDatabase(); } catch (Exception e) { log.error("Unexpected error occurred while creating the database tables."); throw new ConfigurationException("Unexpected error occurred while creating the" + " database tables.", e); } } else { log.error("Unexpected error occurred while reading db script : " + scripFile); throw new ConfigurationException("Unexpected error occurred while reading db script"); } }

Target:
public void createRegistryDatabase() throws ConfigurationException { String databaseType; File scripFile; try { databaseType = DatabaseCreator.getDatabaseType(this.dataSource.getConnection()); String scripPath = getDbScriptLocation(databaseType); scripFile = new File(scripPath); } catch (Exception e) { log.error("Unexpected error occurred while connecting to the database.", e); throw new ConfigurationException("Unexpected error occurred while connecting to" + " the database.", e); } if (scripFile.canRead()) { try { super.createRegistryDatabase(); } catch (Exception e) { log.error("Unexpected error occurred while creating the database tables.", e); throw new ConfigurationException("Unexpected error occurred while creating the" + " database tables.", e); } } else { log.error("Unexpected error occurred while reading db script : " + scripFile); throw new ConfigurationException("Unexpected error occurred while reading db script"); } }
Source:
public void typeRamAmount(String machineName, String ramAmount) { moveCursorToEditButton(machineName); clickOnRamField(machineName); seleniumWebDriverHelper.setValue(getRamAmountTextFieldLocator(machineName), ""); if (ramAmount.isEmpty()) { return; } for (int i = 0; i < ramAmount.length(); i++) { seleniumWebDriverHelper.waitAndSendKeysTo( getRamAmountTextFieldLocator(machineName), valueOf(ramAmount.charAt(i))); } seleniumWebDriverHelper.waitValueEqualsTo(getRamAmountTextFieldLocator(machineName), ramAmount); }

Target:
public void typeRamAmount(String machineName, String ramAmount) { final String emptyValue = ""; seleniumWebDriverHelper.setValue(getRamAmountTextFieldLocator(machineName), emptyValue); if (ramAmount.isEmpty()) { return; } for (int i = 0; i < ramAmount.length(); i++) { seleniumWebDriverHelper.waitAndSendKeysTo( getRamAmountTextFieldLocator(machineName), valueOf(ramAmount.charAt(i))); } seleniumWebDriverHelper.waitValueEqualsTo(getRamAmountTextFieldLocator(machineName), ramAmount); }
Source:
private KeyStore initializeKeyStore(final String keyStoreLocation, final String keyStorePassword, final String keyStoreType) throws WebClientException { InputStream stream = null; try { final KeyStore keyStore = KeyStore.getInstance(keyStoreType.toUpperCase()); stream = new FileInputStream(this.keyStoreLocation); keyStore.load(stream, keyStorePassword.toCharArray()); return keyStore; } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { throw new WebClientException("Error initializing KeyStore", e); } finally { if (stream != null) { try { stream.close(); } catch (final IOException e) { throw new WebClientException("Error closing stream after initializing KeyStore", e); } } } }

Target:
private KeyStore initializeKeyStore(final String keyStoreLocation, final String keyStorePassword, final String keyStoreType) throws WebClientException { try (InputStream stream = new FileInputStream(keyStoreLocation)) { final KeyStore ks = KeyStore.getInstance(keyStoreType.toUpperCase()); ks.load(stream, keyStorePassword.toCharArray()); return ks; } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { throw new WebClientException("Error initializing KeyStore", e); } }