auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void releaseWriteLock(int establishReadLocks, boolean flush) { synchronized (this.mutex) { Thread current = Thread.currentThread(); if (current != this.writeLockOwner) { throw new IllegalStateException("Index wasn't locked by this thread!!!"); } this.writeLockOwner = null; } boolean wasInterrupted = false; try { if (establishReadLocks == 0) { processDeletions(); this.db.putLong(Database.WRITE_NUMBER_OFFSET, ++this.fWriteNumber); clearResultCache(); } wasInterrupted = this.db.giveUpExclusiveLock() || wasInterrupted; } finally { assert this.lockCount == -1; this.lastWriteAccess = System.currentTimeMillis(); synchronized (this.mutex) { if (sDEBUG_LOCKS) { long timeHeld = this.lastWriteAccess - this.timeWriteLockAcquired; if (timeHeld >= LONG_WRITE_LOCK_REPORT_THRESHOLD) { System.out.println("Index write lock held for " + timeHeld + " ms"); } decWriteLock(establishReadLocks + 1); } if (this.lockCount < 0) { this.lockCount = establishReadLocks + 1; } this.mutex.notifyAll(); this.db.setLocked(true); } try { this.db.flush(); } finally { releaseReadLock(); } } if (wasInterrupted) { throw new OperationCanceledException(); } }

Target:
public void releaseWriteLock(int establishReadLocks, boolean flush) { synchronized (this.mutex) { Thread current = Thread.currentThread(); if (current != this.writeLockOwner) { throw new IllegalStateException("Index wasn't locked by this thread!!!"); } this.writeLockOwner = null; } RuntimeException exception = null ; boolean wasInterrupted = false; try { if (establishReadLocks == 0) { processDeletions(); this.db.putLong(Database.WRITE_NUMBER_OFFSET, ++this.fWriteNumber); clearResultCache(); } wasInterrupted = this.db.giveUpExclusiveLock() || wasInterrupted; } catch (RuntimeException e) { exception = e; } finally { assert this.lockCount == -1; this.lastWriteAccess = System.currentTimeMillis(); try { releaseWriteLockAndFlush(establishReadLocks); } catch (RuntimeException e) { if (exception != null) { e.addSuppressed(exception); } throw e; } } if (wasInterrupted) { throw new OperationCanceledException(); } }
Source:
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { if (!element.isValid() || !element.isWritable()) return false; GoAssignmentStatement assignment = getValidAssignmentParent(element); GoReferenceExpression selectedFieldReference = assignment != null ? getFieldReference(element, assignment) : null; return selectedFieldReference != null && !getUninitializedSingleFieldReferences(assignment, selectedFieldReference).isEmpty(); }

Target:
public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { Pair<List<GoReferenceExpression>, GoCompositeLit> pair = getFieldReferencesAndStructLiteral(element); return !pair.first.isEmpty() && pair.second != null; }
Source:
public String getDatacenterName(byte id) { if (id == ClusterMapUtils.UNKNOWN_DATACENTER_ID) { return null; } return hardwareLayout.getDatacenterById(id).getName(); }

Target:
public String getDatacenterName(byte id) { Datacenter datacenter = hardwareLayout.findDatacenter(id); return datacenter == null ? null : datacenter.getName(); }
Source:
public static String toJson(final Config config, final String path) { return config.withFallback(ConfigFactory.systemProperties()).resolve().getObject(path).render(ConfigRenderOptions.concise()); }

Target:
public static String toJson(final Config config, final String path) { return config.getObject(path).render(ConfigRenderOptions.concise()); }
Source:
public void getDockerRegistryOrganizationRepositoriesTest() { ApiClient client = getOpenAPIWebClient(USER_1_USERNAME, testingPostgres); UsersApi usersApi = new UsersApi(client); List<String> actualRepositories = usersApi.getDockerRegistryOrganizationRepositories("quay.io", "dockstoretestuser"); List<String> expectedRepositories = Arrays.asList("noautobuild", "nobuildsatall", "quayandbitbucket", "quayandbitbucketalternate", "quayandgithub", "quayandgithubalternate", "quayandgithubwdl", "quayandgitlab", "quayandgitlabalternate", "test_input_json"); Collections.sort(actualRepositories); Collections.sort(expectedRepositories); Assert.assertEquals("Should have the expected repositories", expectedRepositories, actualRepositories); }

Target:
public void getDockerRegistryOrganizationRepositoriesTest() { ApiClient client = getOpenAPIWebClient(USER_1_USERNAME, testingPostgres); UsersApi usersApi = new UsersApi(client); List<String> actualRepositories = usersApi.getDockerRegistryOrganizationRepositories("quay.io", "dockstoretestuser"); List<String> expectedRepositories = Arrays.asList("noautobuild", "nobuildsatall", "quayandbitbucket", "quayandbitbucketalternate", "quayandgithub", "quayandgithubalternate", "quayandgithubwdl", "quayandgitlab", "quayandgitlabalternate", "test_input_json"); expectedRepositories.forEach(repository -> { Assert.assertTrue("Should have the expected repositories", actualRepositories.contains(repository)); }); }
Source:
public void visitCallExpression(CallExpression callExpression) { Symbol calleeSymbol = callExpression.calleeSymbol(); shouldNotReportIssue |= calleeSymbol != null && "globals".equals(calleeSymbol.fullyQualifiedName()); super.visitCallExpression(callExpression); }

Target:
public void visitCallExpression(CallExpression callExpression) { Symbol calleeSymbol = callExpression.calleeSymbol(); shouldNotReportIssue |= isSymbolWithFQN(calleeSymbol, "globals"); super.visitCallExpression(callExpression); }
Source:
private void calibrateLimits() { users.entrySet().removeIf(entry -> entry.getValue().getOneMinuteRate() <= idleThreshold); int userCount = users.size(); if (userCount > 0) { long total = users.reduceValuesToLong(10, Throughput::getRoundedOneMinuteRate, 0, ((left, right) -> left + right)); long mean = total / userCount; long desiredMean = desired / userCount; users.entrySet() .stream() .filter(entry -> entry.getValue().getRoundedOneMinuteRate() >= mean) .forEach(entry -> entry.getValue().max = desiredMean); } }

Target:
private void calibrateLimits() { users.entrySet().removeIf(entry -> entry.getValue().getOneMinuteRate() <= idleThreshold); int userCount = users.size(); if (userCount > 0) { long total = users.reduceValuesToLong(Long.MAX_VALUE, Throughput::getRoundedOneMinuteRate, 0, ((left, right) -> left + right)); long mean = total / userCount; long desiredMean = desired / userCount; users.entrySet() .stream() .filter(entry -> entry.getValue().getRoundedOneMinuteRate() >= mean) .forEach(entry -> entry.getValue().max = desiredMean); } }
Source:
protected void testValidatorByte(ConstraintValidator<?, Byte> constraint, boolean inclusive, boolean isMax) { if ( inclusive ) { assertTrue( constraint.isValid( (byte) 15, null ) ); } else { assertFalse( constraint.isValid( (byte) 15, null ) ); } assertTrue( constraint.isValid( null, null ) ); assertEquals( constraint.isValid( Byte.MIN_VALUE, null ), isMax ); assertEquals( constraint.isValid( Byte.MAX_VALUE, null ), !isMax ); }

Target:
protected void testValidatorByte(ConstraintValidator<?, Byte> constraint, boolean inclusive, boolean isMax) { if ( inclusive ) { assertTrue( constraint.isValid( (byte) 15, null ) ); } else { assertFalse( constraint.isValid( (byte) 15, null ) ); } assertTrue( constraint.isValid( null, null ) ); assertEquals( constraint.isValid( (byte) 14, null ), isMax ); assertEquals( constraint.isValid( (byte) 16, null ), !isMax ); assertEquals( constraint.isValid( Byte.MIN_VALUE, null ), isMax ); assertEquals( constraint.isValid( Byte.MAX_VALUE, null ), !isMax ); }
Source:
Map getNetworkStatsMap(VM vm) { List<Device> nicDevices = vm.getDevicesByType(Device.DeviceType.NIC); String macAddress = vm.getMacAddress(); if( macAddress.equals(VM.NONE_STRING) ) { log.debug("no mac address for vm {}", vm.getId()); return map(); } Map resultMap = map(); int count = 0; for(Device device : nicDevices) { Map netStats = map(); String dName = "vnet" + count; netStats.put("txErrors", "0"); netStats.put("state", "unknown"); netStats.put("macAddr", device.getMacAddr()); netStats.put("name", dName); netStats.put("txDropped", "0"); netStats.put("txRate", Utils.rangeParsser(AppConfig.getInstance().getNetworkLoadValues())); netStats.put("rxErrors", "0"); netStats.put("rxRate", Utils.rangeParsser(AppConfig.getInstance().getNetworkLoadValues())); netStats.put("tx", Utils.rangeParsser(AppConfig.getInstance().getNetworkLoadValues())); netStats.put("rx", Utils.rangeParsser(AppConfig.getInstance().getNetworkLoadValues())); netStats.put("rxDropped", "0"); netStats.put("speed", "1000"); netStats.put("sampleTime", "4318787.08"); resultMap.put(dName, netStats); ++count; } return resultMap; }

Target:
Map getNetworkStatsMap(VM vm) { List<Device> nicDevices = vm.getDevicesByType(Device.DeviceType.NIC); String macAddress = vm.getMacAddress(); if( macAddress.equals(VM.NONE_STRING) ) { log.debug("no mac address for vm {}", vm.getId()); return map(); } Map resultMap = map(); int count = 0; for(Device device : nicDevices) { ArrayList loadValues = AppConfig.getInstance().getNetworkLoadValues(); Map netStats = map(); String dName = "vnet" + count; netStats.put("txErrors", "0"); netStats.put("state", "unknown"); netStats.put("macAddr", device.getMacAddr()); netStats.put("name", dName); netStats.put("txDropped", "0"); netStats.put("txRate", Utils.rangeParsser(loadValues)); netStats.put("rxErrors", "0"); netStats.put("rxRate", Utils.rangeParsser(loadValues)); netStats.put("tx", Utils.rangeParsser(loadValues)); netStats.put("rx", Utils.rangeParsser(loadValues)); netStats.put("rxDropped", "0"); netStats.put("speed", "1000"); netStats.put("sampleTime", "4318787.08"); resultMap.put(dName, netStats); ++count; } return resultMap; }
Source:
public void testSerializeCrateExecutableInfo() throws Throwable { Configuration configuration = new Configuration(); configuration.clusterName = "foo"; configuration.dataPath = "/mnt/ssd1/crate"; configuration.blobPath= "/mnt/data1/crate"; CrateInstances instances = new CrateInstances(); instances.addInstance(new CrateInstance("host1", "1", "0.48.0", 4300)); List<Protos.Attribute> attr = ImmutableList.of( Protos.Attribute.newBuilder() .setType(Protos.Value.Type.TEXT) .setName("zone") .setText(Protos.Value.Text.newBuilder().setValue("a").build()) .build() ); CrateExecutableInfo info = new CrateExecutableInfo(configuration, "host1", instances, attr); byte[] serializedInfo = info.toStream(); CrateExecutableInfo newInfo = CrateExecutableInfo.fromStream(serializedInfo); Protos.Environment.Variable heap = Protos.Environment.Variable.newBuilder() .setName("CRATE_HEAP_SIZE") .setValue(String.format("%sm", configuration.resHeap.longValue())) .build(); assertThat(newInfo.environment(), Matchers.hasItem(heap)); assertThat(newInfo.arguments(), Matchers.hasItem("-Des.cluster.name=foo")); assertThat(newInfo.arguments(), Matchers.hasItem("-Des.path.data=/mnt/ssd1/crate")); assertThat(newInfo.arguments(), Matchers.hasItem("-Des.path.blobs=/mnt/data1/crate")); }

Target:
public void testSerializeCrateExecutableInfo() throws Throwable { Configuration configuration = new Configuration(); configuration.clusterName = "foo"; configuration.dataPath = "/mnt/ssd1/crate"; configuration.blobPath= "/mnt/data1/crate"; CrateInstances instances = new CrateInstances(); instances.addInstance(new CrateInstance("host1", "1", "0.48.0", 4300)); List<Protos.Attribute> attr = ImmutableList.of( Protos.Attribute.newBuilder() .setType(Protos.Value.Type.TEXT) .setName("zone") .setText(Protos.Value.Text.newBuilder().setValue("a").build()) .build() ); CrateExecutableInfo info = new CrateExecutableInfo(configuration, "host1", instances, attr); byte[] serializedInfo = info.toStream(); CrateExecutableInfo newInfo = CrateExecutableInfo.fromStream(serializedInfo); Protos.Environment.Variable heap = Protos.Environment.Variable.newBuilder() .setName("CRATE_HEAP_SIZE") .setValue(String.format("%sm", configuration.resHeap.longValue())) .build(); assertThat(newInfo.environment(), Matchers.hasItem(heap)); assertThat(newInfo.arguments(), Matchers.hasItem("-Des.cluster.name=foo")); assertThat(newInfo.arguments(), Matchers.hasItem("-Des.path.data=/mnt/ssd1/crate")); assertThat(newInfo.arguments(), Matchers.hasItem("-Des.path.blobs=/mnt/data1/crate")); assertThat(newInfo.arguments(), Matchers.hasItem("-Des.node.mesos_zone=a")); }
Source:
public void setup() { LOG.info("Setting up worker context: " + this); File py4jDependencyFile = new File("./" + PY4J_SRC_ZIP_FILE_NAME); pythonEnvPath = System.getenv(ENV_VAR_PYTHONPATH); LOG.info("Found python environment path : " + pythonEnvPath); if (pythonEnvPath != null) { pythonEnvPath = py4jDependencyFile.getAbsolutePath() + ":" + pythonEnvPath; } else { pythonEnvPath = py4jDependencyFile.getAbsolutePath(); } LOG.debug("Final python environment path with Py4j depenency path: " + pythonEnvPath); LOG.info("FINAL DEPENDENCY PATH: " + environmentData.get(PY4J_DEPENDENCY_PATH)); if ((this.dependencyPath = environmentData.get(PY4J_DEPENDENCY_PATH)) == null) { this.dependencyPath = py4jDependencyFile.getAbsolutePath(); } LOG.info("FINAL WORKER PATH: " + environmentData.get(PYTHON_WORKER_PATH)); if ((this.workerFilePath = environmentData.get(PYTHON_WORKER_PATH)) == null) { File pythonWorkerFile = new File("./" + PYTHON_WORKER_FILE_NAME); this.workerFilePath = pythonWorkerFile.getAbsolutePath(); } LOG.info("Python dependency Path " + this.dependencyPath + " worker Path " + this.workerFilePath); }

Target:
public void setup() { LOG.info("Setting up worker context: {}", this); LOG.debug("Final python environment path with Py4j depenency path: {}", pythonEnvPath); if ((this.apexSourcePath = environmentData.get(PYTHON_APEX_PATH)) == null) { this.apexSourcePath = new File("./" + PYTHON_APEX_ZIP_NAME).getAbsolutePath(); } if ((this.py4jDependencyPath = environmentData.get(PY4J_DEPENDENCY_PATH)) == null) { this.py4jDependencyPath = new File("./" + PY4J_SRC_ZIP_FILE_NAME).getAbsolutePath(); } LOG.info("FINAL WORKER PATH: {}", environmentData.get(PYTHON_WORKER_PATH)); if ((this.workerFilePath = environmentData.get(PYTHON_WORKER_PATH)) == null) { File pythonWorkerFile = new File("./" + PYTHON_WORKER_FILE_NAME); this.workerFilePath = pythonWorkerFile.getAbsolutePath(); } List<String> dependencyFilePaths = new ArrayList<String>(); dependencyFilePaths.add(this.apexSourcePath); dependencyFilePaths.add(this.py4jDependencyPath); pythonEnvPath = System.getenv(ENV_VAR_PYTHONPATH); LOG.info("Found python environment path: {}", pythonEnvPath); if (pythonEnvPath != null) { dependencyFilePaths.add(pythonEnvPath); pythonEnvPath = StringUtils.join(dependencyFilePaths, ":"); } else { pythonEnvPath = StringUtils.join(dependencyFilePaths, ":"); } LOG.info("Python dependency Path worker Path {}", this.py4jDependencyPath, this.workerFilePath); }
Source:
public AnnotatedTypeMirror fromElement(Element elt) { if (shouldCache && elementCache.containsKey(elt)) { return elementCache.get(elt).deepCopy(); } if (elt.getKind() == ElementKind.PACKAGE) { return toAnnotatedType(elt.asType(), false); } AnnotatedTypeMirror type; Tree decl = declarationFromElement(elt); if (decl == null) { type = stubTypes.getAnnotatedTypeMirror(elt); if (type == null) { type = toAnnotatedType(elt.asType(), ElementUtils.isTypeDeclaration(elt)); ElementAnnotationApplier.apply(type, elt, this); } } else if (decl instanceof ClassTree) { type = fromClass((ClassTree) decl); } else if (decl instanceof VariableTree) { type = fromMember(decl); } else if (decl instanceof MethodTree) { type = fromMember(decl); } else if (decl.getKind() == Tree.Kind.TYPE_PARAMETER) { type = fromTypeTree(decl); } else { throw new BugInCF( "AnnotatedTypeFactory.fromElement: cannot be here. decl: " + decl.getKind() + " elt: " + elt); } if (checker.hasOption("prioritizeStubs")) { AnnotatedTypeMirror stubType = stubTypes.getAnnotatedTypeMirror(elt); boolean stubTypeHasAnAnnotation = stubType != null && stubType.toString().contains("@"); boolean typeHasAnAnnotation = type != null && type.toString().contains("@"); if (stubTypeHasAnAnnotation && !typeHasAnAnnotation) { type = stubType; } else if (stubTypeHasAnAnnotation && typeHasAnAnnotation) { AnnotatedTypeMerger.merge(stubType, type); } } if (shouldCache && !stubTypes.isParsing()) { elementCache.put(elt, type.deepCopy()); } return type; }

Target:
public AnnotatedTypeMirror fromElement(Element elt) { if (shouldCache && elementCache.containsKey(elt)) { return elementCache.get(elt).deepCopy(); } if (elt.getKind() == ElementKind.PACKAGE) { return toAnnotatedType(elt.asType(), false); } AnnotatedTypeMirror type; Tree decl = declarationFromElement(elt); if (decl == null) { type = stubTypes.getAnnotatedTypeMirror(elt); if (type == null) { type = toAnnotatedType(elt.asType(), ElementUtils.isTypeDeclaration(elt)); ElementAnnotationApplier.apply(type, elt, this); } } else if (decl instanceof ClassTree) { type = fromClass((ClassTree) decl); } else if (decl instanceof VariableTree) { type = fromMember(decl); } else if (decl instanceof MethodTree) { type = fromMember(decl); } else if (decl.getKind() == Tree.Kind.TYPE_PARAMETER) { type = fromTypeTree(decl); } else { throw new BugInCF( "AnnotatedTypeFactory.fromElement: cannot be here. decl: " + decl.getKind() + " elt: " + elt); } if (checker.hasOption("mergeStubsWithSource")) { type = mergeStubsIntoType(type, elt); } if (shouldCache && !stubTypes.isParsing()) { elementCache.put(elt, type.deepCopy()); } return type; }
Source:
public String send(String msg) { System.setProperty("drools-server", "abcd"); ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:/camel-client.xml"); System.out.println("REST URL :: "+springContext.getBean("restUrl")); String batch = ""; batch += "<batch-execution lookup=\"ksession1\">\n"; batch += " <insert out-identifier=\"message\">\n"; batch += " <org.drools.server.Message>\n"; batch += " <text>" + msg + "</text>\n"; batch += " </org.drools.server.Message>\n"; batch += " </insert>\n"; batch += "</batch-execution>\n"; CamelServerApp test = new CamelServerApp(); String response = test.execute( batch, ( CamelContext ) springContext.getBean( "camel" ) ); return response; }

Target:
public String send(String msg) { ClassPathXmlApplicationContext springContext = new ClassPathXmlApplicationContext("classpath:/src/main/filtered-resoures/camel-client.xml"); String batch = ""; batch += "<batch-execution lookup=\"ksession1\">\n"; batch += " <insert out-identifier=\"message\">\n"; batch += " <org.drools.server.Message>\n"; batch += " <text>" + msg + "</text>\n"; batch += " </org.drools.server.Message>\n"; batch += " </insert>\n"; batch += "</batch-execution>\n"; CamelServerApp test = new CamelServerApp(); String response = test.execute( batch, ( CamelContext ) springContext.getBean( "camel" ) ); return response; }
Source:
private void generateEnumReadOne(EnumType type) { JavaClassName typeName = javaTypes.getEnumName(type); javaBuffer.addImport(typeName); javaBuffer.addImport(JsonReader.class); javaBuffer.addImport(JsonParser.Event.class); javaBuffer.addLine("public static %1$s readOne(JsonReader reader) {", typeName.getSimpleName()); javaBuffer.addLine( "return readOne(reader, true);"); javaBuffer.addLine("}"); javaBuffer.addLine(); javaBuffer.addLine("public static %1$s readOne(JsonReader reader, boolean started) {", typeName.getSimpleName()); javaBuffer.addLine( "if (!started) {"); javaBuffer.addLine( "reader.expect(Event.START_OBJECT);"); javaBuffer.addLine( "}"); javaBuffer.addLine( "return %1$s.fromValue(reader.readString());", typeName.getSimpleName()); javaBuffer.addLine("}"); javaBuffer.addLine(); }

Target:
private void generateEnumReadOne(EnumType type) { JavaClassName typeName = javaTypes.getEnumName(type); javaBuffer.addImport(typeName); javaBuffer.addImport(JsonReader.class); javaBuffer.addImport(JsonParser.Event.class); javaBuffer.addLine("public static %1$s readOne(JsonReader reader) {", typeName.getSimpleName()); javaBuffer.addLine( "return %1$s.fromValue(reader.readString());", typeName.getSimpleName()); javaBuffer.addLine("}"); javaBuffer.addLine(); }
Source:
public void onRoutingTableChange(RoutingTableSnapshot routingTableSnapshot, Object context) { logger.info("Routing table change triggered from {}", dcName); synchronized (notificationLock) { dcToRoutingTableSnapshotRef.get(dcName).getAndSet(routingTableSnapshot); helixClusterManagerMetrics.routingTableChangeTriggerCount.inc(); } }

Target:
public void onRoutingTableChange(RoutingTableSnapshot routingTableSnapshot, Object context) { logger.info("Routing table change triggered from {}", dcName); dcToRoutingTableSnapshotRef.get(dcName).getAndSet(routingTableSnapshot); helixClusterManagerMetrics.routingTableChangeTriggerCount.inc(); }
Source:
public void onMessage(Message message) { try { log.infof("onMessage received message: %s '%s'", message, ((TextMessage) message).getText()); if(checker.getRolledback() > 0) { log.infof("Discarding message '%s' as onMessage called for second time", message); return; } final Destination replyTo = message.getJMSReplyTo(); if (replyTo == null) { throw new RuntimeException("ReplyTo info in message was not specified" + " and bean does not know where to reply to"); } TxTestUtil.enlistTestXAResource(tm.getTransaction()); try ( JMSContext context = factory.createContext() ) { context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, REPLY_PREFIX + ((TextMessage) message).getText()); } TxTestUtil.waitForTimeout(tm); } catch (Exception e) { throw new RuntimeException("onMessage method execution failed", e); } }

Target:
public void onMessage(Message message) { try { log.tracef("onMessage received message: %s '%s'", message, ((TextMessage) message).getText()); if(checker.getRolledback() > 0) { log.tracef("Discarding message '%s' as onMessage called for second time", message); return; } final Destination replyTo = message.getJMSReplyTo(); if (replyTo == null) { throw new RuntimeException("ReplyTo info in message was not specified" + " and bean does not know where to reply to"); } TxTestUtil.enlistTestXAResource(tm.getTransaction()); try ( JMSContext context = factory.createContext() ) { context.createProducer() .setJMSCorrelationID(message.getJMSMessageID()) .send(replyTo, REPLY_PREFIX + ((TextMessage) message).getText()); } TxTestUtil.waitForTimeout(tm); } catch (Exception e) { throw new RuntimeException("onMessage method execution failed", e); } }
Source:
public static boolean isBlockCompressed(final Path path) throws IOException { return isBlockCompressed(path, true); }

Target:
public static boolean isBlockCompressed(final Path path) throws IOException { return isBlockCompressed(path, false); }
Source:
public void should_fail_if_completable_future_has_failed() { CompletableFuture<String> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException()); assertThatThrownBy(() -> assertThat(future).hasNotFailed()).isInstanceOf(AssertionError.class) .hasMessageMatching(shouldNotHaveFailed(future).create(emptyDescription(), new FailedCompletableFutureRepresentation())); }

Target:
public void should_fail_if_completable_future_has_failed() { CompletableFuture<String> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException()); assertThatThrownBy(() -> assertThat(future).hasNotFailed()).isInstanceOf(AssertionError.class) .hasMessageStartingWith(format("%nExpecting%n <CompletableFuture[Failed: java.lang.RuntimeException]%n")) .hasMessageContaining("Caused by: java.lang.RuntimeException") .hasMessageEndingWith(format("to not have failed.%n%s", WARNING)); }
Source:
public void testSaveCredentials_resolution() { mHandler.getOperation().observeForever(mResultObserver); ResolvableApiException mockRae = mock(ResolvableApiException.class); when(mMockCredentials.save(any(Credential.class))) .thenReturn(AutoCompleteTask.<Void>forFailure(mockRae)); mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null); ArgumentCaptor<Resource<Void>> resolveCaptor = ArgumentCaptor.forClass(Resource.class); verify(mResultObserver, times(2)).onChanged(resolveCaptor.capture()); PendingIntentRequiredException e = ((PendingIntentRequiredException) resolveCaptor.getValue().getException()); mHandler.onActivityResult(e.getRequestCode(), Activity.RESULT_OK); verify(mResultObserver).onChanged(argThat(ResourceMatchers.<Void>isSuccess())); }

Target:
public void testSaveCredentials_resolution() { mHandler.getOperation().observeForever(mResultObserver); ResolvableApiException mockRae = mock(ResolvableApiException.class); when(mMockCredentials.save(any(Credential.class))) .thenReturn(AutoCompleteTask.<Void>forFailure(mockRae)); mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null); InOrder inOrder = inOrder(mResultObserver); inOrder.verify(mResultObserver).onChanged(argThat(ResourceMatchers.<Void>isLoading())); ArgumentCaptor<Resource<Void>> resolveCaptor = ArgumentCaptor.forClass(Resource.class); inOrder.verify(mResultObserver).onChanged(resolveCaptor.capture()); PendingIntentRequiredException e = ((PendingIntentRequiredException) resolveCaptor.getValue().getException()); mHandler.onActivityResult(e.getRequestCode(), Activity.RESULT_OK); inOrder.verify(mResultObserver).onChanged(argThat(ResourceMatchers.<Void>isSuccess())); }
Source:
HttpURLConnection getConnection(URL url) throws IOException { if (config.getProxyHost() != null) { SocketAddress socketAddress; if (config.getProxyPort() != -1) { socketAddress = new InetSocketAddress(config.getProxyHost(), config.getProxyPort()); } else { socketAddress = new InetSocketAddress(config.getProxyHost(), 80); } proxy = new Proxy(Proxy.Type.HTTP, socketAddress); if (config.getProxyUsername() != null && config.getProxyPassword() != null) { Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return (new PasswordAuthentication(config.getProxyUsername(), config.getProxyPassword().toCharArray())); } }; Authenticator.setDefault(authenticator); } } final HttpURLConnection connection; if (proxy != null) { connection = (HttpURLConnection) url.openConnection(proxy); } else { connection = (HttpURLConnection) url.openConnection(); } return connection; }

Target:
HttpURLConnection getConnection(URL url) throws IOException { final HttpURLConnection connection; if (proxy != null) { connection = (HttpURLConnection) url.openConnection(proxy); } else { connection = (HttpURLConnection) url.openConnection(); } return connection; }
Source:
private Set<Cookie> convertHttpToJavaCookies(Set<io.netty.handler.codec.http.Cookie> httpCookies) { Set<javax.servlet.http.Cookie> cookies = new HashSet<Cookie>(); for (io.netty.handler.codec.http.Cookie cookie : httpCookies) { try { javax.servlet.http.Cookie javaCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); cookies.add(javaCookie); } catch (IllegalArgumentException e) { logger.debug("Could not create cookie", e); } } return cookies; }

Target:
private Set<Cookie> convertHttpToJavaCookies(Set<io.netty.handler.codec.http.Cookie> httpCookies) { Set<javax.servlet.http.Cookie> cookies = new HashSet<Cookie>(); for (io.netty.handler.codec.http.Cookie cookie : httpCookies) { try { javax.servlet.http.Cookie javaCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); cookies.add(javaCookie); } catch (IllegalArgumentException e) { logger.debug("Could not create cookie with name [{}]", cookie.getName(), e); } } return cookies; }
Source:
public void getSetBits(int batchSize, boolean[] vector) throws IOException { for (int i = 0; i < batchSize; i++) { vector[i] = nextBit(); } }

Target:
public int getSetBits(int batchSize, boolean[] vector) throws IOException { int count = 0; for (int i = 0; i < batchSize; i++) { vector[i] = nextBit(); count += vector[i] ? 1 : 0; } return count; }
Source:
private String tokenFromRequest( HttpServletRequest request ) { final String authorizationInfo; final String authorizationHeader = getAuthorizationTokenFromHeader( request ); if ( authorizationHeader != null ) { authorizationInfo = authorizationHeader; } else { authorizationInfo = getRequestCookie( request, AUTHORIZATION_COOKIE ); final String csrfTokenFromCookie = getRequestCookie( request, CSRF_COOKIE ); final String csrfTokenFromParams = request.getParameter( CSRF_COOKIE ); if ( csrfTokenFromCookie == null || csrfTokenFromParams == null ) { return null; } if ( !StringUtils.equals( csrfTokenFromCookie, csrfTokenFromParams ) ) { return null; } } if ( authorizationInfo == null || !authorizationInfo.startsWith( BEARER_PREFIX ) ) { return null; } final String[] parts = authorizationInfo.split( " " ); if ( parts.length != 2 ) { return null; } return parts[ 1 ]; }

Target:
private String tokenFromRequest( HttpServletRequest request ) { final String authorizationInfo; final String authorizationHeader = getAuthorizationTokenFromHeader( request ); if ( authorizationHeader != null ) { authorizationInfo = authorizationHeader; } else { authorizationInfo = getRequestCookie( request, AUTHORIZATION_COOKIE ); final String csrfTokenFromCookie = getRequestCookie( request, CSRF_COOKIE ); final String csrfTokenFromParams = request.getParameter( CSRF_PARAM ); if ( csrfTokenFromCookie == null || csrfTokenFromParams == null ) { return null; } if ( !StringUtils.equals( csrfTokenFromCookie, csrfTokenFromParams ) ) { return null; } } if ( authorizationInfo == null || !authorizationInfo.startsWith( BEARER_PREFIX ) ) { return null; } final String[] parts = authorizationInfo.split( " " ); if ( parts.length != 2 ) { return null; } return parts[ 1 ]; }
Source:
public final void alterTable(final AlterTableDesc desc) throws UndefinedTableException, DuplicateColumnException, InsufficientPrivilegeException, DuplicateTableException { try { final BlockingInterface stub = getStub(); final ReturnState state = stub.alterTable(null, desc.getProto()); throwsIfThisError(state, DuplicateColumnException.class); throwsIfThisError(state, DuplicateTableException.class); throwsIfThisError(state, DuplicateColumnException.class); throwsIfThisError(state, UndefinedTableException.class); throwsIfThisError(state, InsufficientPrivilegeException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }

Target:
public final void alterTable(final AlterTableDesc desc) throws DuplicateDatabaseException, DuplicateTableException, DuplicateColumnException, DuplicatePartitionException, UndefinedDatabaseException, UndefinedTableException, UndefinedColumnException, UndefinedPartitionMethodException, InsufficientPrivilegeException, UndefinedPartitionException { try { final BlockingInterface stub = getStub(); final ReturnState state = stub.alterTable(null, desc.getProto()); throwsIfThisError(state, DuplicateTableException.class); throwsIfThisError(state, DuplicateColumnException.class); throwsIfThisError(state, DuplicatePartitionException.class); throwsIfThisError(state, UndefinedDatabaseException.class); throwsIfThisError(state, UndefinedTableException.class); throwsIfThisError(state, UndefinedColumnException.class); throwsIfThisError(state, UndefinedPartitionException.class); throwsIfThisError(state, UndefinedPartitionMethodException.class); throwsIfThisError(state, InsufficientPrivilegeException.class); ensureOk(state); } catch (ServiceException e) { throw new RuntimeException(e); } }
Source:
public Job annotateVariantsJob(JobBuilderFactory jobBuilderFactory) { logger.debug("Building '"+NAME_ANNOTATE_VARIANTS_JOB+"'"); JobBuilder jobBuilder = jobBuilderFactory .get(NAME_ANNOTATE_VARIANTS_JOB) .incrementer(new RunIdIncrementer()); return jobBuilder.start(annotation).build().build(); }

Target:
public Job annotateVariantsJob(JobBuilderFactory jobBuilderFactory) { logger.debug("Building '" + ANNOTATE_VARIANTS_JOB + "'"); JobBuilder jobBuilder = jobBuilderFactory .get(ANNOTATE_VARIANTS_JOB) .incrementer(new RunIdIncrementer()); return jobBuilder.start(annotation).build().build(); }
Source:
public static RealMatrix convertINDArrayToApacheMatrix(@Nonnull final INDArray matrix) { if (matrix.rank() != 2) { throw new IllegalArgumentException("Input rank is not 2 (not matrix)"); } final int[] shape = matrix.shape(); final BlockRealMatrix out = new BlockRealMatrix(shape[0], shape[1]); for (int i=0; i<shape[0]; i++) { for (int j=0; j<shape[1]; j++) { out.setEntry(i, j, matrix.getDouble(i, j)); } } return out; }

Target:
public static RealMatrix convertINDArrayToApacheMatrix(@Nonnull final INDArray matrix) { Utils.validateArg(matrix.rank() == 2, "Input rank is not 2 (not matrix)"); final int[] shape = matrix.shape(); final INDArray concreteMatrix = matrix.isView() ? matrix.dup() : matrix; final double[] data = concreteMatrix.data().asDouble(); final char ordering = concreteMatrix.ordering(); if (ordering == 'c') { return new BlockRealMatrix(monoToBiDiArrayRowMajor(data, shape[0], shape[1])); } else { return new BlockRealMatrix(monoToBiDiArrayColumnMajor(data, shape[0], shape[1])); } }
Source:
public void visitToken(final DetailAST node) { final DetailAST generic = DiamondOperatorCheck.getFirstChildNodeOfType( node.findFirstToken(TokenTypes.TYPE), TokenTypes.TYPE_ARGUMENTS ); final DetailAST assign = node.findFirstToken(TokenTypes.ASSIGN); final DetailAST instance; if (assign == null || generic == null) { instance = null; } else { instance = assign.getFirstChild().getFirstChild(); } if (instance != null && instance.getType() == TokenTypes.LITERAL_NEW && DiamondOperatorCheck.isNotObjectBlock(instance) && DiamondOperatorCheck.isNotArray(instance)) { final DetailAST type = DiamondOperatorCheck.getFirstChildNodeOfType( instance, TokenTypes.TYPE_ARGUMENTS ); if (generic.equalsTree(type)) { log( type, "Better to use diamond operator where possible" ); } } }

Target:
public void visitToken(final DetailAST node) { final DetailAST generic = DiamondOperatorCheck.getFirstChildNodeOfType( node.findFirstToken(TokenTypes.TYPE), TokenTypes.TYPE_ARGUMENTS ); final DetailAST assign = node.findFirstToken(TokenTypes.ASSIGN); final DetailAST instance; if (assign == null || generic == null) { instance = null; } else { instance = assign.getFirstChild().getFirstChild(); } if (instance != null && instance.getType() == TokenTypes.LITERAL_NEW && DiamondOperatorCheck.isNotObjectBlock(instance) && DiamondOperatorCheck.isNotArray(instance)) { final DetailAST type = DiamondOperatorCheck.getFirstChildNodeOfType( instance, TokenTypes.TYPE_ARGUMENTS ); if (generic.equalsTree(type)) { log(type, "Use diamond operator"); } } }
Source:
private void handleExecutorNotAliveCase( final Entry<Optional<Executor>, List<ExecutableFlow>> entry, final Executor executor, final ExecutorManagerException e) { this.logger.error("Failed to get update from executor " + executor.getId(), e); this.executorFailureCount.put(executor.getId(), this.executorFailureCount.getOrDefault (executor.getId(), 0) + 1); if (this.executorFailureCount.get(executor.getId()) % this.executorMaxFailureCount == 0 && !this.alertEmails.isEmpty()) { entry.getValue().stream().forEach(flow -> flow .getExecutionOptions().setFailureEmails(this.alertEmails)); this.alerterHolder.get("email").alertOnFailedUpdate(executor, entry.getValue(), e); } }

Target:
private void handleExecutorNotAliveCase( final Entry<Optional<Executor>, List<ExecutableFlow>> entry, final Executor executor, final ExecutorManagerException e) { logger.error("Failed to get update from executor " + executor.getId(), e); this.executorFailureCount.put(executor.getId(), this.executorFailureCount.getOrDefault (executor.getId(), 0) + 1); if (this.executorFailureCount.get(executor.getId()) % this.executorMaxFailureCount == 0 && !this.alertEmails.isEmpty()) { entry.getValue().stream().forEach(flow -> flow .getExecutionOptions().setFailureEmails(this.alertEmails)); logger.info(String.format("Executor failure count is %d. Sending alert emails to %s.", this.executorFailureCount.get(executor.getId()), this.alertEmails)); this.alerterHolder.get("email").alertOnFailedUpdate(executor, entry.getValue(), e); } }
Source:
protected IRuntimeClasspathEntry[] defaultEntries(ILaunchConfiguration config) { try { String server = new JBossLaunchConfigProperties().getServerId(config); IServer s = ServerCore.findServer(server); IControllableServerBehavior beh = JBossServerBehaviorUtils.getControllableBehavior(config); if( beh != null ) { ISubsystemController cont = beh.getController(IControllableServerBehavior.SYSTEM_LAUNCH); if( cont instanceof ILaunchConfigConfiguratorProvider ) { ILaunchConfigConfigurator c = ((ILaunchConfigConfiguratorProvider)cont).getLaunchConfigurator(); if( c != null ) { if( c instanceof IDefaultClasspathLaunchConfigurator ) { return ((IDefaultClasspathLaunchConfigurator)c).getDefaultClasspathEntries(config); } } } } return new IRuntimeClasspathEntry[0]; } catch (CoreException ce) { JBossServerCorePlugin.log(ce.getStatus()); } try { return super.computeUnresolvedClasspath(config); } catch (CoreException ce) { JBossServerCorePlugin.log(ce.getStatus()); } return new IRuntimeClasspathEntry[] {}; }

Target:
protected IRuntimeClasspathEntry[] defaultEntries(ILaunchConfiguration config) { try { String server = new JBossLaunchConfigProperties().getServerId(config); IServer s = ServerCore.findServer(server); IControllableServerBehavior beh = JBossServerBehaviorUtils.getControllableBehavior(config); if( beh != null ) { ISubsystemController cont = beh.getController(IControllableServerBehavior.SYSTEM_LAUNCH); if( cont instanceof ILaunchConfigConfiguratorProvider ) { ILaunchConfigConfigurator c = ((ILaunchConfigConfiguratorProvider)cont).getLaunchConfigurator(); if( c instanceof IDefaultClasspathLaunchConfigurator ) { return ((IDefaultClasspathLaunchConfigurator)c).getDefaultClasspathEntries(config); } } } return new IRuntimeClasspathEntry[0]; } catch (CoreException ce) { JBossServerCorePlugin.log(ce.getStatus()); } try { return super.computeUnresolvedClasspath(config); } catch (CoreException ce) { JBossServerCorePlugin.log(ce.getStatus()); } return new IRuntimeClasspathEntry[] {}; }
Source:
void addChanges(Collection<String> filesToUpdate, Collection<IResource> resourcesToUpdate) { synchronized (lock) { files.addAll(filesToUpdate); resources.addAll(resourcesToUpdate); } if (!filesToUpdate.isEmpty()) { schedule(defaultDelay); } }

Target:
void addChanges(Collection<String> filesToUpdate, Collection<IResource> resourcesToUpdate) { synchronized (lock) { files.addAll(filesToUpdate); resources.addAll(resourcesToUpdate); } if (!filesToUpdate.isEmpty()) schedule(defaultDelay); }
Source:
public void testUserAgentHeaderString() throws Exception { ClientBuilder builder = ClientBuilder.account("test"); Class clazz = builder.getClass(); Field interceptor = clazz.getDeclaredField("USER_AGENT_INTERCEPTOR"); interceptor.setAccessible(true); UserAgentInterceptor userAgentInterceptor = (UserAgentInterceptor) interceptor.get(builder); Class interceptorClazz = userAgentInterceptor.getClass(); Field uaField = interceptorClazz.getDeclaredField("userAgent"); uaField.setAccessible(true); String userAgentHeader = (String) uaField.get(userAgentInterceptor); assertTrue("The value of the User-Agent header: " + userAgentHeader + " should match the " + "format: " + userAgentFormat, userAgentHeader.matches(userAgentRegex)); }

Target:
public void testUserAgentHeaderString() throws Exception { String userAgentHeader = new UserAgentInterceptor(UserAgentInterceptor.class.getClassLoader(), "META-INF/com.cloudant.client.properties").getUserAgent(); assertTrue("The value of the User-Agent header: " + userAgentHeader + " should match the " + "format: " + userAgentFormat, userAgentHeader.matches(userAgentUnknownRegex)); }
Source:
public void putRequest(ExecuteRequest req) throws ExceptionReport { try { lock.tryLock(TIME_OUT_SECONDS, TimeUnit.SECONDS); UUID requestId = req.getUniqueId(); if (isRedundantRequestEnabled()) { if (hasRan(req)) { LOGGER.info("Current request has ran previously. Getting file response URI..."); String responseId = getPreviousResponseId(requestId); LOGGER.info("Response ID, " + responseId + " found for request with ID..." + requestId.toString()); } else { addRequest(req); } } else { LOGGER.info("Adding request to Throttle Queue with ID:" + requestId.toString()); addRequest(req); } } catch (InterruptedException e) { LOGGER.info("Attempt to acquire lock to add request to the throttle timed out: " + e.getMessage()); } finally { lock.unlock(); } }

Target:
public void putRequest(ExecuteRequest req) throws ExceptionReport { try { lock.tryLock(TIME_OUT_SECONDS, TimeUnit.SECONDS); UUID requestId = req.getUniqueId(); if (isRedundantRequestEnabled()) { if (hasRan(req)) { LOGGER.debug("Current request has ran previously. Getting file response URI..."); String responseId = getPreviousResponseId(requestId); LOGGER.debug("Response ID, " + responseId + " found for request with ID..." + requestId.toString()); } else { addRequest(req); } } else { LOGGER.debug("Adding request to Throttle Queue with ID:" + requestId.toString()); addRequest(req); } } catch (InterruptedException e) { LOGGER.debug("Attempt to acquire lock to add request to the throttle timed out: " + e.getMessage()); } finally { lock.unlock(); } }
Source:
final void releaseContextFromPool(final C context) { this.lock.lock(); try { if (this.cached == context) { return; } if (this.cached == null) { this.cached = context; return; } this.contextPool.push(context); } finally { this.lock.unlock(); } }

Target:
final void releaseContextFromPool(final C context) { if (Thread.currentThread() != context.createdTracker.getSidedThread()) { throw new IllegalStateException("Asynchronous Thread Access to PhaseTracker: " + context.createdTracker); } if (this.cached == context) { return; } if (this.cached == null) { this.cached = context; return; } context.createdTracker.getContextPoolFor(this).push(context); }
Source:
MetaFixer(MasterServices masterServices) { this.masterServices = masterServices; this.maxMergeCount = this.masterServices.getConfiguration(). getInt("hbase.master.metafixer.max.merge.count", 10); }

Target:
MetaFixer(MasterServices masterServices) { this.masterServices = masterServices; this.maxMergeCount = this.masterServices.getConfiguration(). getInt(MAX_MERGE_COUNT_KEY, MAX_MERGE_COUNT_DEFAULT); }
Source:
void foo() throws Exception { var a = 2; var list = new ArrayList<String>(); list.add("hello"); list.add("world"); for (var counter = 0; counter < list.size(); counter++) { var value = list.get(counter); } for (var value : list) { value.length(); } var url = new URL("<LINK_0>"); var conn = url.openConnection(); try (var reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { var stream = reader.lines(); } var myA = new A() { Object myField; @Override public void foo() { this.myField = bar(); } String bar() { return "42"; } }; myA.bar(); if (myA.myField != null) { myA.foo(); } Object var; }

Target:
void foo() throws Exception { var a = 2; var list = new ArrayList<String>(); list.add("hello"); list.add("world"); for (var counter = 0; counter < list.size(); counter++) { var value = list.get(counter); } for (var value : list) { value.length(); } var url = new URL("<LINK_0>"); var conn = url.openConnection(); try (var reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { var stream = reader.lines(); } var myA = new A() { Object myField; @Override public void foo() { this.myField = bar(); } String bar() { return "42"; } }; myA.bar(); if (myA.myField != null) { myA.foo(); } Object var; var x = new A(); java.util.function.BiConsumer<A, String> lambda = (var l1, var l2) -> l1.process(l2); }
Source:
ByteBuf encode( final ByteBufAllocator allocator, final int streamId, boolean fragmentFollows, boolean complete, boolean next, int requestN, @Nullable ByteBuf metadata, ByteBuf data) { int flags = 0; if (metadata != null) { flags |= FrameHeaderFlyweight.FLAGS_M; } if (fragmentFollows) { flags |= FrameHeaderFlyweight.FLAGS_F; } if (complete) { flags |= FrameHeaderFlyweight.FLAGS_C; } if (next) { flags |= FrameHeaderFlyweight.FLAGS_N; } ByteBuf header = FrameHeaderFlyweight.encode(allocator, streamId, frameType, flags); if (requestN > 0) { header.writeInt(requestN); } if (metadata != null & data != null) { return DataAndMetadataFlyweight.encode(allocator, header, metadata, data); } else if (data != null) { return DataAndMetadataFlyweight.encodeOnlyData(allocator, header, data); } else { return header; } }

Target:
ByteBuf encode( final ByteBufAllocator allocator, final int streamId, boolean fragmentFollows, boolean complete, boolean next, int requestN, @Nullable ByteBuf metadata, ByteBuf data) { int flags = 0; if (metadata != null) { flags |= FrameHeaderFlyweight.FLAGS_M; } if (fragmentFollows) { flags |= FrameHeaderFlyweight.FLAGS_F; } if (complete) { flags |= FrameHeaderFlyweight.FLAGS_C; } if (next) { flags |= FrameHeaderFlyweight.FLAGS_N; } ByteBuf header = FrameHeaderFlyweight.encode(allocator, streamId, frameType, flags); if (requestN > 0) { header.writeInt(requestN); } if (metadata != null) { return DataAndMetadataFlyweight.encode(allocator, header, metadata, data); } else { return DataAndMetadataFlyweight.encodeOnlyData(allocator, header, data); } }
Source:
public List<Comment> parseComments(int id) throws IOException { CommentVaultHtmlContentHandler commentVaultHtmlContentHandler = new CommentVaultHtmlContentHandler(); URL url = new URL(String.format(environment.getProperty("vault.mapCommentUrl"), id)); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); logger.info("Fetching comments from {}", url); try (BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))) { JsonReader jsonReader = new JsonReader(reader); jsonReader.beginObject(); while (jsonReader.hasNext()) { String key = jsonReader.nextName(); if (!"comments".equals(key)) { jsonReader.skipValue(); continue; } String comments = jsonReader.nextString(); return htmlParser.parse(comments, commentVaultHtmlContentHandler); } jsonReader.endObject(); } throw new IllegalStateException("Comment vault could not be read from " + url); }

Target:
public List<Comment> parseComments(int id) throws IOException { CommentVaultHtmlContentHandler commentVaultHtmlContentHandler = new CommentVaultHtmlContentHandler(); URL url = new URL(String.format(environment.getProperty("vault.mapCommentUrl"), id)); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); logger.debug("Fetching comments from {}", url); try (BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()))) { JsonReader jsonReader = new JsonReader(reader); jsonReader.beginObject(); while (jsonReader.hasNext()) { String key = jsonReader.nextName(); if (!"comments".equals(key)) { jsonReader.skipValue(); continue; } String comments = jsonReader.nextString(); return htmlParser.parse(comments, commentVaultHtmlContentHandler); } jsonReader.endObject(); } throw new IllegalStateException("Comment vault could not be read from " + url); }
Source:
private Object convertValue(Object value, Type type) { if (value == null) { return null; } if (BOOLEAN.equals(type) || Varchars.isVarcharType(type)) { return value; } if (BIGINT.equals(type)) { return ((Number) value).longValue(); } if (INTEGER.equals(type)) { return ((Number) value).intValue(); } if (DOUBLE.equals(type)) { return ((Number) value).doubleValue(); } if (DATE.equals(type)) { return value; } throw new AssertionError("unhandled type: " + type); }

Target:
private Object convertValue(Object value, Type type) { if (value == null) { return null; } if (BOOLEAN.equals(type) || Varchars.isVarcharType(type)) { return value; } if (BIGINT.equals(type)) { return ((Number) value).longValue(); } if (INTEGER.equals(type)) { return ((Number) value).intValue(); } if (DOUBLE.equals(type)) { return ((Number) value).doubleValue(); } if (DATE.equals(type)) { return value; } throw new IllegalArgumentException("unhandled type: " + type); }