auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean refineCoefficient(int coefIndex, double lowerBound, double upperBound, double[][] xValues, double[] yValues) throws Exception { boolean result = false; if (coefficient[coefIndex] < lowerBound || coefficient[coefIndex] > upperBound) { double value; if (coefficient[coefIndex] < lowerBound) { value = lowerBound; } else { value = upperBound; } int ptr = -1; if (validColumnIndices.size() >= 1 && validColumnIndices.get(validColumnIndices.size() - 1) == coefIndex) { ptr = validColumnIndices.size() - 1; } else if (validColumnIndices.size() >= 2 && validColumnIndices.get(validColumnIndices.size() - 2) == coefIndex) { ptr = validColumnIndices.size() - 2; } if (ptr != -1) { if (LOG.isDebugEnabled()) { LOG.debug("addRecord: coefficient at index " + coefIndex + " is wrong in the regression, setting it to " + value); } validColumnIndices.remove(ptr); fillXMatrix(dataSamples, validColumnIndices, xValues); for (int i = 0; i < memorySamples.size(); ++i) { yValues[i] -= value * dataSamples.get(i)[coefIndex]; } extreme[coefIndex] = value; mlr.newSampleData(yValues, xValues); calculateRegression(coefficient, validColumnIndices, mlr); result = true; } else { if (LOG.isDebugEnabled()) { LOG.debug( "addRecord: coefficient was not in the regression, " + "setting it to the lower bound"); } result = false; } coefficient[coefIndex] = value; } return result; }

Target:
private boolean refineCoefficient(int coefIndex, double lowerBound, double upperBound, double[][] xValues, double[] yValues) throws Exception { boolean result = false; if (coefficient[coefIndex] < lowerBound || coefficient[coefIndex] > upperBound) { double value; if (coefficient[coefIndex] < lowerBound) { value = lowerBound; } else { value = upperBound; } int ptr = -1; for (int i = validColumnIndices.size() - 1; i >= 0; --i) { if (validColumnIndices.get(i) == coefIndex) { ptr = i; break; } } if (ptr != -1) { if (LOG.isDebugEnabled()) { LOG.debug("addRecord: coefficient at index " + coefIndex + " is wrong in the regression, setting it to " + value); } validColumnIndices.remove(ptr); fillXMatrix(dataSamples, validColumnIndices, xValues); for (int i = 0; i < memorySamples.size(); ++i) { yValues[i] -= value * dataSamples.get(i)[coefIndex]; } extreme[coefIndex] = value; mlr.newSampleData(yValues, xValues); calculateRegression(coefficient, validColumnIndices, mlr); result = true; } else { if (LOG.isDebugEnabled()) { LOG.debug( "addRecord: coefficient was not in the regression, " + "setting it to the extreme of the bound"); } result = false; } coefficient[coefIndex] = value; } return result; }
Source:
String getUpdateLocation0(Module module) { ModuleRevision current = module.getCurrentRevision(); Generation generation = (Generation) current.getRevisionInfo(); String updateLocation = generation.getHeaders().get(Constants.BUNDLE_UPDATELOCATION); if (updateLocation == null) { updateLocation = module.getLocation(); } if (updateLocation.startsWith(INITIAL_LOCATION)) { updateLocation = updateLocation.substring(INITIAL_LOCATION.length()); } return updateLocation == null ? module.getLocation() : updateLocation; }

Target:
String getUpdateLocation0(Module module) { ModuleRevision current = module.getCurrentRevision(); Generation generation = (Generation) current.getRevisionInfo(); String updateLocation = generation.getHeaders().get(Constants.BUNDLE_UPDATELOCATION); if (updateLocation == null) { updateLocation = module.getLocation(); } if (updateLocation.startsWith(INITIAL_LOCATION)) { updateLocation = updateLocation.substring(INITIAL_LOCATION.length()); } return updateLocation; }
Source:
public static Container readContainer(final Version version, final InputStream inputStream, final long containerByteOffset) { Container container = readContainerInternal(version.major, inputStream, containerByteOffset); if (container == null) { CramVersionPolicies.eofNotFound(version); return readContainerInternal(version.major, new ByteArrayInputStream(CramIO.ZERO_B_EOF_MARKER), containerByteOffset); } if (container.isEOF()) { log.debug("EOF marker found, file/stream is complete."); } return container; }

Target:
private static Container readContainer(final Version version, final InputStream inputStream, final long containerByteOffset) { Container container = readContainerInternal(version.major, inputStream, containerByteOffset); if (container == null) { CramVersionPolicies.eofNotFound(version); return readContainerInternal(version.major, new ByteArrayInputStream(CramIO.ZERO_B_EOF_MARKER), containerByteOffset); } if (container.isEOF()) { log.debug("EOF marker found, file/stream is complete."); } return container; }
Source:
static ExecutorService startClientService(SystemMain system, ClientType clientType, AtomicInteger jobCounter) { switch (clientType) { case ALERT: return startAlertClientService(system, jobCounter); case COMMIT_SCHEMA: return startCommitSchemaClientService(system, jobCounter); case COMMIT_ANNOTATIONS: return startCommitAnnotationsClientService(system, jobCounter); case PROCESS_METRICS: return startProcessMetricsClientService(system, jobCounter); default: return startCommitMetricsClientService(system, jobCounter); } }

Target:
static ExecutorService startClientService(SystemMain system, ClientType clientType, AtomicInteger jobCounter) { switch (clientType) { case ALERT: return startAlertClientService(system, jobCounter); case COMMIT_SCHEMA: return startCommitSchemaClientService(system, jobCounter); case COMMIT_ANNOTATIONS: return startCommitAnnotationsClientService(system, jobCounter); case PROCESS_QUERIES: return startProcessMetricsClientService(system, jobCounter); default: return startCommitMetricsClientService(system, jobCounter); } }
Source:
public UfsClient getJournal(URI location) { synchronized (this) { if (mJournalUfsClientMap == null) { mJournalUfsClientMap = new HashMap<>(); } UfsClient ufsClient = mJournalUfsClientMap.get(location.getScheme()); if (ufsClient == null) { addMount(IdUtils.UFS_JOURNAL_MOUNT_ID, new AlluxioURI(location.toString()), UfsJournal.getJournalUfsConf()); try { ufsClient = get(IdUtils.UFS_JOURNAL_MOUNT_ID); mJournalUfsClientMap.put(location.getScheme(), ufsClient); } catch (NotFoundException | UnavailableException e) { throw new RuntimeException("We should never reach here", e); } } return ufsClient; } }

Target:
public UfsClient getJournal(URI location) { synchronized (this) { if (mJournalUfsClient == null) { addMount(IdUtils.UFS_JOURNAL_MOUNT_ID, new AlluxioURI(location.toString()), UfsJournal.getJournalUfsConf()); try { mJournalUfsClient = get(IdUtils.UFS_JOURNAL_MOUNT_ID); } catch (NotFoundException | UnavailableException e) { throw new RuntimeException("We should never reach here", e); } } return mJournalUfsClient; } }
Source:
public boolean isPending() { return fScenarioInfo.getStatus().equals(ScenarioStatusType.PENDING); }

Target:
public boolean isPending() { return fScenarioInfo.getStatus() == ScenarioStatusType.PENDING; }
Source:
public String docs() { return "boolean {locationArray} Returns the name of the Command Block at the given location."; }

Target:
public String docs() { return "string {locationArray} Returns the name of the Command Block at the given location."; }
Source:
public <C extends Context> C unwrap(TypeToken<C> type) { checkArgument(checkNotNull(type, "type").isSupertypeOf(backendType), "backend type: %s not assignable to %s", backendType, type); return (C) backend; }

Target:
public <C extends Context> C unwrap(TypeToken<C> type) { checkArgument(TypeTokenUtils.isSupertypeOf(checkNotNull(type, "type"), backendType), "%s is not a supertype of backend type %s", type, backendType); return (C) backend; }
Source:
public static void withCustomerGroup(final BlockingSphereClient client, final UnaryOperator<CustomerGroup> consumer) { final String name = randomString(); final String key = randomKey(); final CustomerGroupDraft customerGroupDraft = CustomerGroupDraft.of(name,key); final CustomerGroup customerGroup = client.executeBlocking(CustomerGroupCreateCommand.of(customerGroupDraft)); CustomerGroup updatedCustomerGroup = consumer.apply(customerGroup); final Optional<CustomerGroup> customerGroupOptional = Optional.ofNullable(client.executeBlocking(CustomerGroupByIdGet.of(updatedCustomerGroup.getId()))); customerGroupOptional.ifPresent(group -> client.executeBlocking(CustomerGroupDeleteCommand.of(updatedCustomerGroup))); }

Target:
public static void withCustomerGroup(final BlockingSphereClient client, final UnaryOperator<CustomerGroup> consumer) { final String name = randomString(); final String key = randomKey(); final CustomerGroupDraft customerGroupDraft = CustomerGroupDraft.of(name,key); final CustomerGroup customerGroup = client.executeBlocking(CustomerGroupCreateCommand.of(customerGroupDraft)); final CustomerGroup updatedCustomerGroup = consumer.apply(customerGroup); final Optional<CustomerGroup> customerGroupOptional = Optional.ofNullable(client.executeBlocking(CustomerGroupByIdGet.of(updatedCustomerGroup.getId()))); customerGroupOptional.ifPresent(group -> client.executeBlocking(CustomerGroupDeleteCommand.of(updatedCustomerGroup))); }
Source:
public void testVolatilityModelAdjointRhoP1() { final double eps = 1e-5; final double tol = 1e-6; final SABRFormulaData data = DATA.withRho(1.0); testVolatilityModelAdjoint(F, CALL_ATM, data, eps, tol); double z = 0.975; double strike = strikeForZ(z, F, ALPHA, BETA, NU); double[] adjModel = FUNCTION.getVolatilityModelAdjoint(CALL_ATM.withStrike(strike), F, data); double[] adj = FUNCTION.getVolatilityAdjoint(CALL_ATM.withStrike(strike), F, data); testVolatilityModelAdjoint(F, CALL_ATM.withStrike(strike), data, eps, 5e-2); z = -2.0; strike = strikeForZ(z, F, ALPHA, BETA, NU); testVolatilityModelAdjoint(F, CALL_ATM.withStrike(strike), data, eps, 50 * tol); z = 2.0; strike = strikeForZ(z, F, ALPHA, BETA, NU); testVolatilityModelAdjoint(F, CALL_ATM.withStrike(strike), DATA.withRho(1 - 1e-3), eps, 5e-5); testVolatilityModelAdjoint(F, CALL_ATM.withStrike(strike), data, 1e-6, 1.0); }

Target:
public void testVolatilityModelAdjointRhoP1() { final double eps = 1e-5; final double tol = 1e-6; final SABRFormulaData data = DATA.withRho(1.0); testVolatilityModelAdjoint(F, CALL_ATM, data, eps, tol); double z = 0.975; double strike = strikeForZ(z, F, ALPHA, BETA, NU); testVolatilityModelAdjoint(F, CALL_ATM.withStrike(strike), data, eps, 5e-2); z = -2.0; strike = strikeForZ(z, F, ALPHA, BETA, NU); testVolatilityModelAdjoint(F, CALL_ATM.withStrike(strike), data, eps, 50 * tol); z = 2.0; strike = strikeForZ(z, F, ALPHA, BETA, NU); testVolatilityModelAdjoint(F, CALL_ATM.withStrike(strike), DATA.withRho(1 - 1e-3), eps, 5e-5); testVolatilityModelAdjoint(F, CALL_ATM.withStrike(strike), data, 1e-6, 1.0); }
Source:
public void success(PageCombo pageCombo, Response response) { L.v(response.getUrl()); if (pageCombo.hasError()) { onError(); return; } final Page page = pageCombo.toPage(title); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { new SavePageTask(WikipediaApp.getInstance(), page.getTitle(), page).execute(); } }); L.d("Downloaded page " + title.getDisplayText()); onComplete(); }

Target:
public void success(PageCombo pageCombo, Response response) { L.v(response.getUrl()); if (pageCombo.hasError()) { onError(); return; } final Page page = pageCombo.toPage(title); new SavePageTask(WikipediaApp.getInstance(), page.getTitle(), page).execute(); L.d("Downloaded page " + title.getDisplayText()); onComplete(); }
Source:
private static List<String> parseExcludedRules(Configuration configuration) { String excludeProperty = configuration.getProperty(GeneralOption.KTLINT_EXCLUDE); if (excludeProperty == null) { return new ArrayList<>(); } else { return Arrays.asList(excludeProperty.split(",")); } }

Target:
private List<String> parseExcludedRules(Configuration configuration) { String excludeProperty = configuration.getProperty(GeneralOption.KTLINT_EXCLUDE); if (excludeProperty == null) { return new ArrayList<>(); } return Arrays.asList(excludeProperty.split(",")); }
Source:
private TableScanNode tableScan(String id, String... symbols) { List<Symbol> symbolsList = Arrays.stream(symbols).map(Symbol::new).collect(toImmutableList()); ImmutableMap.Builder<Symbol, ColumnHandle> assignments = ImmutableMap.builder(); for (Symbol symbol : symbolsList) { assignments.put(symbol, new TpchColumnHandle("orderkey", BIGINT)); } TpchTableHandle tableHandle = new TpchTableHandle("orders", 1.0); return new TableScanNode( new PlanNodeId(id), new TableHandle( new ConnectorId("tpch"), tableHandle, TpchTransactionHandle.INSTANCE, Optional.of(new TpchTableLayoutHandle(tableHandle, TupleDomain.all()))), symbolsList, assignments.build(), TupleDomain.all(), TupleDomain.all()); }

Target:
private TableScanNode tableScan(String id, String... symbols) { List<VariableReferenceExpression> variables = Arrays.stream(symbols) .map(symbol -> new VariableReferenceExpression(symbol, BIGINT)) .collect(toImmutableList()); return tableScan(id, variables); }
Source:
public boolean tryLock() { if (!isInUse.compareAndSet(false, true)) { return false; } final String path; try { path = createAndGetLockPath(); } catch (InterruptedException e) { log.log( java.util.logging.Level.WARNING, "InterruptedException while trying to get lock path " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.WARNING, "KeeperException while trying to get lock path " + absoluteLockPath, e); return false; } try { absoluteLockPath = zk.create( path.toString(), null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); log.log( java.util.logging.Level.INFO, "Created lock node with path: " + absoluteLockPath); final long noTimeout = 0; final boolean noWait = false; return attemptToLock(noTimeout, noWait); } catch (InterruptedException e) { log.log( java.util.logging.Level.INFO, "InterruptedException while trying to create lock " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.INFO, "KeeperException while trying to create lock " + absoluteLockPath, e); return false; } }

Target:
public boolean tryLock() { if (!isInUse.compareAndSet(false, true)) { return false; } final String path; try { path = createAndGetLockPath(); } catch (InterruptedException e) { log.log( java.util.logging.Level.WARNING, "InterruptedException while trying to get lock path " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.WARNING, "KeeperException while trying to get lock path " + absoluteLockPath, e); return false; } try { absoluteLockPath = zk.create( path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); log.log( java.util.logging.Level.INFO, "Created lock node with path: " + absoluteLockPath); final long noTimeout = 0; final boolean noWait = false; return attemptToLock(noTimeout, noWait); } catch (InterruptedException e) { log.log( java.util.logging.Level.INFO, "InterruptedException while trying to create lock " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.INFO, "KeeperException while trying to create lock " + absoluteLockPath, e); return false; } }
Source:
public void builderWorks() { CriteriaContext context = new CriteriaContext.Builder() .withStudyIdentifier(TestConstants.TEST_STUDY) .withUserId(USER_ID) .withClientInfo(CLIENT_INFO) .withUserDataGroups(TestConstants.USER_DATA_GROUPS) .withUserSubstudyIds(TestConstants.USER_SUBSTUDY_IDS).build(); assertEquals(CLIENT_INFO, context.getClientInfo()); assertEquals(TestConstants.USER_DATA_GROUPS, context.getUserDataGroups()); assertEquals(TestConstants.USER_SUBSTUDY_IDS, context.getUserSubstudyIds()); CriteriaContext copy = new CriteriaContext.Builder().withContext(context).build(); assertEquals(CLIENT_INFO, copy.getClientInfo()); assertEquals(TestConstants.USER_DATA_GROUPS, copy.getUserDataGroups()); }

Target:
public void builderWorks() { CriteriaContext context = new CriteriaContext.Builder() .withStudyIdentifier(TestConstants.TEST_STUDY) .withUserId(USER_ID) .withClientInfo(CLIENT_INFO) .withUserDataGroups(TestConstants.USER_DATA_GROUPS) .withUserSubstudyIds(TestConstants.USER_SUBSTUDY_IDS).build(); assertEquals(CLIENT_INFO, context.getClientInfo()); assertEquals(TestConstants.USER_DATA_GROUPS, context.getUserDataGroups()); assertEquals(TestConstants.USER_SUBSTUDY_IDS, context.getUserSubstudyIds()); CriteriaContext copy = new CriteriaContext.Builder().withContext(context).build(); assertEquals(CLIENT_INFO, copy.getClientInfo()); assertEquals(TestConstants.TEST_STUDY, copy.getStudyIdentifier()); assertEquals(USER_ID, copy.getUserId()); assertEquals(TestConstants.USER_DATA_GROUPS, copy.getUserDataGroups()); assertEquals(TestConstants.USER_SUBSTUDY_IDS, copy.getUserSubstudyIds()); }
Source:
private static Format getFormat(String delimiter) { if (",".equals(delimiter)) { return Format.CSV; } else if (delimiter != null && delimiter.length() > 0) { Format.CustomizeSV.setDelimiter(delimiter, null); return Format.CustomizeSV; } else { return Format.TSV; } }

Target:
private static Format getFormat(String delimiter) { if (",".equals(delimiter)) { return Format.CSV; } else if ("\t".equals(delimiter)) { return Format.TSV; } else { Format.CustomizeSV.setDelimiter(delimiter, null); return Format.CustomizeSV; } }
Source:
public void updateSystemMemoryUsage(long deltaMemoryInBytes) { if (taskContext == null) { Optional<TaskContext> taskContext = queryContext.getTaskContextByTaskId(taskId); verify(taskContext.isPresent(), "task does not exist"); this.taskContext = taskContext.get(); } if (deltaMemoryInBytes > 0) { taskContext.reserveSystemMemory(deltaMemoryInBytes); } else { taskContext.freeSystemMemory(-deltaMemoryInBytes); } }

Target:
public void updateSystemMemoryUsage(long deltaMemoryInBytes) { if (taskContext == null) { taskContext = queryContext.getTaskContextByTaskId(taskId); } if (deltaMemoryInBytes > 0) { taskContext.reserveSystemMemory(deltaMemoryInBytes); } else { taskContext.freeSystemMemory(-deltaMemoryInBytes); } }
Source:
public void testUserManagedDestination() throws Exception { int numberOfPartitions = 2; String destinationTopic = "userManaged_" + UUID.randomUUID().toString(); _datastreamCluster = initializeTestDatastreamServerWithFileConnector(1, BROADCAST_STRATEGY_FACTORY, numberOfPartitions); int totalEvents = 10; _datastreamCluster.startup(); String fileName1 = "/tmp/testFile1_" + UUID.randomUUID().toString(); ZkClient zkClient = new ZkClient(_datastreamCluster.getZkConnection()); ZkConnection zkConnection = new ZkConnection(_datastreamCluster.getZkConnection()); ZkUtils zkUtils = new ZkUtils(zkClient, zkConnection, false); AdminUtils.createTopic(zkUtils, destinationTopic, numberOfPartitions, 1, new Properties()); Datastream fileDatastream1 = createFileDatastream(fileName1, destinationTopic, 2); Assert.assertEquals((int) fileDatastream1.getDestination().getPartitions(), 2); Collection<String> eventsWritten1 = TestUtils.generateStrings(totalEvents); FileUtils.writeLines(new File(fileName1), eventsWritten1); Collection<String> eventsReceived1 = readFileDatastreamEvents(fileDatastream1, 0, 9); Collection<String> eventsReceived2 = readFileDatastreamEvents(fileDatastream1, 1, 1); eventsReceived1.addAll(eventsReceived2); LOG.info("Events Received " + eventsReceived1); LOG.info("Events Written to file " + eventsWritten1); Assert.assertTrue(eventsReceived1.containsAll(eventsWritten1)); }

Target:
public void testUserManagedDestination() throws Exception { int numberOfPartitions = 2; String destinationTopic = "userManaged_" + UUID.randomUUID().toString(); _datastreamCluster = initializeTestDatastreamServerWithFileConnector(1, BROADCAST_STRATEGY_FACTORY, numberOfPartitions); int totalEvents = 10; _datastreamCluster.startup(); String fileName1 = "/tmp/testFile1_" + UUID.randomUUID().toString(); ZkClient zkClient = new ZkClient(_datastreamCluster.getZkConnection()); ZkConnection zkConnection = new ZkConnection(_datastreamCluster.getZkConnection()); ZkUtils zkUtils = new ZkUtils(zkClient, zkConnection, false); AdminUtils.createTopic(zkUtils, destinationTopic, numberOfPartitions, 1, new Properties()); Datastream fileDatastream1 = createFileDatastream(fileName1, destinationTopic, 2); Assert.assertEquals((int) fileDatastream1.getDestination().getPartitions(), 2); Collection<String> eventsWritten1 = TestUtils.generateStrings(totalEvents); FileUtils.writeLines(new File(fileName1), eventsWritten1); Collection<String> eventsReceived1 = readFileDatastreamEvents(fileDatastream1, 0, 5); Collection<String> eventsReceived2 = readFileDatastreamEvents(fileDatastream1, 1, 5); eventsReceived1.addAll(eventsReceived2); LOG.info("Events Received " + eventsReceived1); LOG.info("Events Written to file " + eventsWritten1); Assert.assertTrue(eventsReceived1.containsAll(eventsWritten1)); }
Source:
public void testPeanutButterDidntTurnIntoWine() { Wine wine = new Wine(); assertNotEquals(wine.getBackendType(), typeToken(PeanutButter.class)); try { wine.unwrap(typeToken(PeanutButter.class)); fail(); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "backend type: org.jclouds.internal.BaseViewTest$Water is not a supertype of org.jclouds.internal.BaseViewTest$PeanutButter"); } }

Target:
public void testPeanutButterDidntTurnIntoWine() { Wine wine = new Wine(); assertNotEquals(wine.getBackendType(), typeToken(PeanutButter.class)); try { wine.unwrap(typeToken(PeanutButter.class)); fail(); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "org.jclouds.internal.BaseViewTest$PeanutButter is not a supertype of backend type org.jclouds.internal.BaseViewTest$Water"); } }
Source:
public static void refreshMetadata(String username, String email) { AnalyticsMetadata metadata = new AnalyticsMetadata(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(WordPress.getContext()); metadata.setSessionCount(preferences.getInt(AnalyticsTrackerMixpanel.SESSION_COUNT, 0)); metadata.setUserConnected(AccountHelper.isSignedIn()); metadata.setWordPressComUser(AccountHelper.isSignedInWordPressDotCom()); metadata.setJetpackUser(AccountHelper.isJetPackUser()); metadata.setNumBlogs(WordPress.wpDB.getNumBlogs()); metadata.setVersionCode(PackageUtils.getVersionCode(WordPress.getContext())); metadata.setUsername(username); metadata.setEmail(email); AnalyticsTracker.refreshMetadata(metadata); }

Target:
public static void refreshMetadata(String username, String email) { AnalyticsMetadata metadata = new AnalyticsMetadata(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(WordPress.getContext()); metadata.setSessionCount(preferences.getInt(AnalyticsTrackerMixpanel.SESSION_COUNT, 0)); metadata.setUserConnected(AccountHelper.isSignedIn()); metadata.setWordPressComUser(AccountHelper.isSignedInWordPressDotCom()); metadata.setJetpackUser(AccountHelper.isJetPackUser()); metadata.setNumBlogs(WordPress.wpDB.getNumBlogs()); metadata.setUsername(username); metadata.setEmail(email); AnalyticsTracker.refreshMetadata(metadata); }
Source:
private boolean audioDescribedOrFalse(Encoding encoding) { return Optional.fromNullable(encoding.getAudioDescribed()).or(false); }

Target:
private boolean audioDescribedOrFalse(Encoding encoding) { return Boolean.TRUE.equals(encoding.getAudioDescribed()); }
Source:
public void downloadURL(URL url, int index) { sleep(500); if (getHost().contains("buttsmithy.com") == true || getHost().contains("www.totempole666.com") == true || getHost().contains("themonsterunderthebed.net") == true) { addURLToDownload(url, pageTitle + "_"); } addURLToDownload(url, getPrefix(index)); }

Target:
public void downloadURL(URL url, int index) { if (getHost().contains("buttsmithy.com") || getHost().contains("www.totempole666.com") || getHost().contains("themonsterunderthebed.net")) { addURLToDownload(url, pageTitle + "_"); } addURLToDownload(url, getPrefix(index)); }
Source:
public DataWord shiftLeft(DataWord arg) { BigInteger result = value().shiftLeft(arg.value().intValue()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); }

Target:
public DataWord shiftLeft(DataWord arg) { if (arg.value().compareTo(BigInteger.valueOf(MAX_POW)) >= 0) { return DataWord.ZERO; } BigInteger result = value().shiftLeft(arg.intValueSafe()); return new DataWord(ByteUtil.copyToArray(result.and(MAX_VALUE))); }
Source:
public void stopMonitoring() { super.stopMonitoring(); try { prometheusClient.close(); } catch (IOException e) { } }

Target:
public void stopMonitoring() { super.stopMonitoring(); try { if (prometheusClient != null) { prometheusClient.close(); } } catch (IOException e) { } }
Source:
private UpdaterConfiguration makeFiveConfiguration() { return UpdaterConfiguration.builder() .withSource(FIVE) .withItemEquivalenceUpdater( FIVE_ITEM, MoreSets.add(TARGET_SOURCES, LOVEFILM) ) .withTopLevelContainerEquivalenceUpdater( STANDARD_TOP_LEVEL_CONTAINER, MoreSets.add(TARGET_SOURCES, LOVEFILM) ) .withNonTopLevelContainerEquivalenceUpdater( STANDARD_SERIES, TARGET_SOURCES ) .build(); }

Target:
private UpdaterConfiguration makeFiveConfiguration() { return UpdaterConfiguration.builder() .withSource(FIVE) .withItemEquivalenceUpdater( STRICT_ITEM, TARGET_SOURCES ) .withTopLevelContainerEquivalenceUpdater( STANDARD_TOP_LEVEL_CONTAINER, TARGET_SOURCES ) .withNonTopLevelContainerEquivalenceUpdater( STANDARD_SERIES, TARGET_SOURCES ) .build(); }
Source:
void putUnlessValueExists(long sequenceNumber, T value) { Preconditions.checkState( sequenceNumber > 0, "Only positive sequence numbers are supported, but found %s", sequenceNumber); try { kvs.putUnlessExists(AtlasDbConstants.COORDINATION_TABLE, ImmutableMap.of(getCellForSequence(sequenceNumber), serializeData(value, VALUE_DESCRIPTION))); } catch (KeyAlreadyExistsException e) { throw new IllegalStateException("The coordination store failed a putUnlessExists. This is unexpected" + " as it implies timestamps may have been reused, or a writer to the store behaved badly.", e); } }

Target:
void putUnlessValueExists(long sequenceNumber, T value) { Preconditions.checkState( sequenceNumber > 0, "Only positive sequence numbers are supported, but found %s", sequenceNumber); try { kvs.putUnlessExists(AtlasDbConstants.COORDINATION_TABLE, ImmutableMap.of(getCellForSequence(sequenceNumber), serializeValue(value))); } catch (KeyAlreadyExistsException e) { throw new SafeIllegalStateException("The coordination store failed a putUnlessExists. This is unexpected" + " as it implies timestamps may have been reused, or a writer to the store behaved badly." + " The offending sequence number was {}. " + " Please contact support - DO NOT ATTEMPT TO FIX THIS YOURSELF.", e, SafeArg.of("sequenceNumber", sequenceNumber)); } }
Source:
public int warmUpConnections(List<DataNodeId> dataNodeIds, int connectionWarmUpPercentagePerDataNode, long timeForWarmUp, List<ResponseInfo> responseInfoList) { NetworkClient client = childNetworkClients.get(ReplicaType.DISK_BACKED); if (client != null) { return client.warmUpConnections(dataNodeIds, connectionWarmUpPercentagePerDataNode, timeForWarmUp, responseInfoList); } else { return 0; } }

Target:
public int warmUpConnections(List<DataNodeId> dataNodeIds, int connectionWarmUpPercentagePerDataNode, long timeForWarmUp, List<ResponseInfo> responseInfoList) { return childNetworkClients.values() .stream() .mapToInt(client -> client.warmUpConnections(dataNodeIds, connectionWarmUpPercentagePerDataNode, timeForWarmUp, responseInfoList)) .sum(); }
Source:
public LanguageServerWrapper(@Nullable IProject project, @NonNull LanguageServerDefinition serverDefinition, @Nullable IPath initialPath) { this.initialProject = project; this.initialPath = initialPath; this.allWatchedProjects = new HashSet<>(); this.serverDefinition = serverDefinition; this.connectedDocuments = new HashMap<>(); }

Target:
private LanguageServerWrapper(@Nullable IProject project, @NonNull LanguageServerDefinition serverDefinition, @Nullable IPath initialPath) { this.initialProject = project; this.initialPath = initialPath; this.allWatchedProjects = new HashSet<>(); this.serverDefinition = serverDefinition; this.connectedDocuments = new HashMap<>(); }
Source:
public static ColumnStatisticsObj createMetastoreColumnStatistics(String columnName, HiveType columnType, HiveColumnStatistics statistics, OptionalLong rowCount) { TypeInfo typeInfo = columnType.getTypeInfo(); if (typeInfo.getCategory() == PRIMITIVE) { switch (((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory()) { case BOOLEAN: return createBooleanStatistics(columnName, columnType, statistics); case BYTE: case SHORT: case INT: case LONG: return createLongStatistics(columnName, columnType, statistics); case FLOAT: case DOUBLE: return createDoubleStatistics(columnName, columnType, statistics); case STRING: case VARCHAR: case CHAR: return createStringStatistics(columnName, columnType, statistics, rowCount); case DATE: return createDateStatistics(columnName, columnType, statistics); case TIMESTAMP: return createLongStatistics(columnName, columnType, statistics); case BINARY: return createBinaryStatistics(columnName, columnType, statistics, rowCount); case DECIMAL: return createDecimalStatistics(columnName, columnType, statistics); default: throw new IllegalArgumentException(format("unsupported type: %s", columnType)); } } else if (typeInfo.getCategory() == STRUCT || typeInfo.getCategory() == MAP) { return new ColumnStatisticsObj(); } else { throw new IllegalArgumentException(format("unsupported type: %s", columnType)); } }

Target:
public static ColumnStatisticsObj createMetastoreColumnStatistics(String columnName, HiveType columnType, HiveColumnStatistics statistics, OptionalLong rowCount) { TypeInfo typeInfo = columnType.getTypeInfo(); checkArgument(typeInfo.getCategory() == PRIMITIVE, "unsupported type: %s", columnType); switch (((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory()) { case BOOLEAN: return createBooleanStatistics(columnName, columnType, statistics); case BYTE: case SHORT: case INT: case LONG: return createLongStatistics(columnName, columnType, statistics); case FLOAT: case DOUBLE: return createDoubleStatistics(columnName, columnType, statistics); case STRING: case VARCHAR: case CHAR: return createStringStatistics(columnName, columnType, statistics, rowCount); case DATE: return createDateStatistics(columnName, columnType, statistics); case TIMESTAMP: return createLongStatistics(columnName, columnType, statistics); case BINARY: return createBinaryStatistics(columnName, columnType, statistics, rowCount); case DECIMAL: return createDecimalStatistics(columnName, columnType, statistics); default: throw new IllegalArgumentException(format("unsupported type: %s", columnType)); } }
Source:
public void startTest(Test test) { this.current = test; message("%TESTS ", test); try { BundleContext context = targetBundle.getBundleContext(); MethodHandle mh; try { Method m = test.getClass() .getMethod("setBundleContext", BundleContext.class); m.setAccessible(true); mh = publicLookup().unreflect(m); if (!Modifier.isStatic(m.getModifiers())) { mh = mh.bindTo(test); } } catch (NoSuchMethodException | IllegalAccessException e) { try { Field f = test.getClass() .getField("context"); f.setAccessible(true); mh = publicLookup().unreflectSetter(f); if (!Modifier.isStatic(f.getModifiers())) { mh = mh.bindTo(test); } } catch (NoSuchFieldException | IllegalAccessException e1) { mh = null; } } if (mh != null) { mh.invoke(context); } } catch (Error e) { throw e; } catch (Throwable t) { } }

Target:
public void startTest(Test test) { this.current = test; message("%TESTS ", test); BundleContext context = targetBundle.getBundleContext(); try { MethodHandle mh; try { Method m = test.getClass() .getMethod("setBundleContext", BundleContext.class); m.setAccessible(true); mh = publicLookup().unreflect(m); if (!Modifier.isStatic(m.getModifiers())) { mh = mh.bindTo(test); } } catch (NoSuchMethodException | IllegalAccessException e) { try { Field f = test.getClass() .getField("context"); f.setAccessible(true); mh = publicLookup().unreflectSetter(f); if (!Modifier.isStatic(f.getModifiers())) { mh = mh.bindTo(test); } } catch (NoSuchFieldException | IllegalAccessException e1) { mh = null; } } if (mh != null) { mh.invoke(context); } } catch (Error e) { throw e; } catch (Throwable t) { } }
Source:
protected void destroyStore(RecordStore store) { assertRunningOnPartitionThread(); ((DefaultRecordStore) store).clearAndDestroyStorage(false, true); }

Target:
protected void destroyStore(RecordStore store) { assertRunningOnPartitionThread(); ((DefaultRecordStore) store).destroyStorageAfterClear(false, true); }
Source:
protected void drawMarker(IMarkerEvent marker, Rectangle bounds, ITimeDataProvider timeProvider, int nameSpace, GC gc) { Rectangle rect = Utils.clone(bounds); if (marker.getEntry() != null) { int index = fItemData.findItemIndex(marker.getEntry()); if (index == -1) { return; } rect = getStatesRect(bounds, index, nameSpace); if (rect.y < 0 || rect.y > bounds.height) { return; } } int x0 = getXForTime(marker.getTime()); int x1 = getXForTime(marker.getTime() + marker.getDuration()); if (x0 > bounds.width || x1 < nameSpace) { return; } rect.x = Math.max(nameSpace, Math.min(bounds.width, x0)); rect.width = Math.max(1, Math.min(bounds.width, x1) - rect.x); gc.setBackground(marker.getColor()); gc.setAlpha(marker.getColor().getAlpha()); gc.fillRectangle(rect); gc.setAlpha(255); String label = marker.getLabel(); if (label != null && marker.getEntry() != null) { label = label.substring(0, Math.min(256, label.length())); gc.setForeground(marker.getColor()); Utils.drawText(gc, label, rect.x - gc.textExtent(label).x, rect.y, true); } }

Target:
protected void drawMarker(IMarkerEvent marker, Rectangle bounds, ITimeDataProvider timeProvider, int nameSpace, GC gc) { Rectangle rect = Utils.clone(bounds); if (marker.getEntry() != null) { int index = fItemData.findItemIndex(marker.getEntry()); if (index == -1) { return; } rect = getStatesRect(bounds, index, nameSpace); if (rect.y < 0 || rect.y > bounds.height) { return; } } int x0 = getXForTime(marker.getTime()); int x1 = getXForTime(marker.getTime() + marker.getDuration()); if (x0 > bounds.width || x1 < nameSpace) { return; } rect.x = Math.max(nameSpace, Math.min(bounds.width, x0)); rect.width = Math.max(1, Math.min(bounds.width, x1) - rect.x); gc.setBackground(marker.getColor()); gc.setAlpha(marker.getColor().getAlpha()); gc.fillRectangle(rect); gc.setAlpha(255); String label = marker.getLabel(); if (label != null && marker.getEntry() != null) { label = label.substring(0, Math.min(label.indexOf('\n') != -1 ? label.indexOf('\n') : label.length(), MAX_LABEL_LENGTH)); gc.setForeground(marker.getColor()); Utils.drawText(gc, label, rect.x - gc.textExtent(label).x, rect.y, true); } }
Source:
private void putBlob(MessageInfo messageInfo, ByteBuffer messageBuf, long size) throws CloudStorageException { boolean performUpload = messageInfo.getExpirationTimeInMs() == Utils.Infinite_Time && !messageInfo.isDeleted(); if (performUpload) { BlobId blobId = (BlobId) messageInfo.getStoreKey(); CloudBlobMetadata blobMetadata = new CloudBlobMetadata(blobId, messageInfo.getOperationTimeMs(), messageInfo.getSize()); blobMetadata.setExpirationTime(messageInfo.getExpirationTimeInMs()); cloudDestination.uploadBlob(blobId, size, blobMetadata, new ByteBufferInputStream(messageBuf)); } }

Target:
private void putBlob(MessageInfo messageInfo, ByteBuffer messageBuf, long size) throws CloudStorageException { boolean performUpload = messageInfo.getExpirationTimeInMs() == Utils.Infinite_Time && !messageInfo.isDeleted(); if (performUpload) { BlobId blobId = (BlobId) messageInfo.getStoreKey(); CloudBlobMetadata blobMetadata = new CloudBlobMetadata(blobId, messageInfo.getOperationTimeMs(), messageInfo.getExpirationTimeInMs(), messageInfo.getSize()); cloudDestination.uploadBlob(blobId, size, blobMetadata, new ByteBufferInputStream(messageBuf)); } }
Source:
private Table readTableOrView(String tableName) { final List<Schema> schemas = new ArrayList<>(); if (schemaName != null) { schemas.add(getSchema()); Table table = schemas.get(0).resolveTableOrView(session, tableName); if (table != null) { return table; } } else { schemas.add(database.getSchema(session.getCurrentSchemaName())); Table table = schemas.get(0).resolveTableOrView(session, tableName); if (table != null) { return table; } String[] schemaNames = session.getSchemaSearchPath(); if (schemaNames != null) { for (String name : schemaNames) { Schema s = database.getSchema(name); table = s.resolveTableOrView(session, tableName); if (table != null) { return table; } schemas.add(s); } } } if (isDualTable(tableName)) { return new DualTable(database); } throw getTableOrViewNotFoundDbException(schemas, tableName); }

Target:
private Table readTableOrView(String tableName) { if (schemaName != null) { Table table = getSchema().resolveTableOrView(session, tableName); if (table != null) { return table; } } else { Table table = database.getSchema(session.getCurrentSchemaName()) .resolveTableOrView(session, tableName); if (table != null) { return table; } String[] schemaNames = session.getSchemaSearchPath(); if (schemaNames != null) { for (String name : schemaNames) { Schema s = database.getSchema(name); table = s.resolveTableOrView(session, tableName); if (table != null) { return table; } } } } if (isDualTable(tableName)) { return new DualTable(database); } throw getTableOrViewNotFoundDbException(tableName); }
Source:
void clean(K key) { List<V> data = getDataMap().get(key); if (data != null) { data.clear(); } getDataMap().remove(key); }

Target:
void clean(K key) { getDataMap().remove(key); }
Source:
protected boolean synchronizeModel(IDocument doc) { if (doc == null) { return false; } IFeatureModel model = (IFeatureModel) getModel(); String text = doc.get(); try (InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8))) { model.reload(stream, false); } catch (CoreException e) { return false; } catch (IOException e) { } return true; }

Target:
protected boolean synchronizeModel(IDocument doc) { if (doc == null) { return false; } IFeatureModel model = (IFeatureModel) getModel(); String text = doc.get(); try (InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8))) { model.reload(stream, false); } catch (CoreException | IOException e) { return false; } return true; }
Source:
public void shouldThrowExceptionForInvalidOrganisation() throws Exception{ expectedEx.expect(IllegalArgumentException.class); expectedEx.expectMessage("Invalid syntax"); validator.validateEntity("ORG-Test"); }

Target:
public void shouldThrowExceptionForInvalidOrganisation() { when(rdapExceptionMapper.badRequest("Invalid syntax.")) .thenReturn(new BadRequestException("Invalid syntax.")); expectedEx.expect(BadRequestException.class); expectedEx.expectMessage("Invalid syntax"); validator.validateEntity("ORG-Test"); }
Source:
protected void showBundleFilter() { final Collection<String> bundleIds; if (getCollector() instanceof TargetPlatformClassContributionCollector) { bundleIds = TargetPlatformClassContributionCollector.getInstance().getBundleIds(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { bundleIds = TargetPlatformIconContributionCollector.getInstance().getBundleIds(); } else { return; } final ArrayList<String> sorted = new ArrayList<String>(bundleIds); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the bundle to filter on."); setTitle("Bundle Filter"); getShell().setText("Bundle Filter"); try { setTitleImage(new Image(getShell().getDisplay(), getClass().getResourceAsStream("/icons/full/wizban/plugin_wiz.gif"))); } catch (Exception e) { e.printStackTrace(); } return ret; } }; if (dlg.open() == Dialog.OK) { setFilterBundles((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }

Target:
protected void showBundleFilter() { final Collection<String> bundleIds; if (getCollector() instanceof TargetPlatformClassContributionCollector) { bundleIds = TargetPlatformClassContributionCollector.getInstance().getBundleIds(); } else if (getCollector() instanceof TargetPlatformIconContributionCollector) { bundleIds = TargetPlatformIconContributionCollector.getInstance().getBundleIds(); } else { return; } final ArrayList<String> sorted = new ArrayList<String>(bundleIds); Collections.sort(sorted); TitleAreaFilterDialog dlg = new TitleAreaFilterDialog(getShell(), new ColumnLabelProvider()) { @Override protected Control createContents(Composite parent) { Control ret = super.createContents(parent); getViewer().setInput(sorted); setMessage("Select the bundle to filter on."); setTitle("Bundle Filter"); getShell().setText("Bundle Filter"); try { setTitleImage(imageCache.create("/icons/full/wizban/plugin_wiz.gif")); } catch (Exception e) { e.printStackTrace(); } return ret; } }; if (dlg.open() == Dialog.OK) { setFilterBundles((List<String>) dlg.asList()); refreshSearch(); } updateUiState(); }
Source:
private void updateSavePageMenuItem(MenuItem menuItemSavePage) { if (!savedPageCheckComplete) { menuItemSavePage.setEnabled(false); } else if (refreshedIfSaved) { menuItemSavePage.setEnabled(false); menuItemSavePage.setTitle(getString(R.string.menu_page_saved)); } else if (pageSaved) { menuItemSavePage.setEnabled(true); menuItemSavePage.setTitle(getString(R.string.menu_refresh_saved_page)); } else { menuItemSavePage.setEnabled(true); menuItemSavePage.setTitle(getString(R.string.menu_save_page)); } }

Target:
public void updateSavePageMenuItem(MenuItem menuItemSavePage) { if (!savedPageCheckComplete) { menuItemSavePage.setEnabled(false); } else if (pageRefreshed) { menuItemSavePage.setEnabled(false); menuItemSavePage.setTitle(getString(R.string.menu_page_saved)); } else if (pageSaved) { menuItemSavePage.setEnabled(true); menuItemSavePage.setTitle(getString(R.string.menu_refresh_saved_page)); } else { menuItemSavePage.setEnabled(true); menuItemSavePage.setTitle(getString(R.string.menu_page_save)); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ReplicationFactor)) return false; ReplicationFactor that = (ReplicationFactor) o; return allReplicas == that.allReplicas && fullReplicas == that.fullReplicas; }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ReplicationFactor)) { return false; } ReplicationFactor that = (ReplicationFactor) o; return allReplicas == that.allReplicas && fullReplicas == that.fullReplicas; }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RosterGroupElement other = (RosterGroupElement) obj; if (!Arrays.equals(children, other.children)) return false; if (groupName == null) { if (other.groupName != null) return false; } else if (!groupName.equals(other.groupName)) return false; return true; }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RosterGroupElement other = (RosterGroupElement) obj; return Objects.equals(groupName, other.groupName); }
Source:
private static List<Integer> findMatchName(String name, ITmfTrace trace) { Map<Integer, String> executableNames = getExecutableNames(trace); List<Integer> TIDS = new ArrayList<>(); Pattern checkRegex = Pattern.compile(name); for (Entry<Integer, String> entry : executableNames.entrySet()) { Matcher regexMatcher = checkRegex.matcher(entry.getValue()); if (regexMatcher.find()) { TIDS.add(entry.getKey()); } } return TIDS; }

Target:
private static List<Integer> findMatchName(String name, ITmfTrace trace) { Map<Integer, String> executableNames = getExecutableNames(trace); List<Integer> tids = new ArrayList<>(); Pattern checkRegex = Pattern.compile(name); for (Entry<Integer, String> entry : executableNames.entrySet()) { Matcher regexMatcher = checkRegex.matcher(entry.getValue()); if (regexMatcher.find()) { tids.add(entry.getKey()); } } return tids; }
Source:
private Set<DSemanticDecorator> getDElementToClearWithXref(final EObject root, final Set<EObject> semanticElements, final ECrossReferenceAdapter xref) { final Set<DSemanticDecorator> decoratorsToDestroy = new HashSet<DSemanticDecorator>(); for (EObject semElt : semanticElements) { for (Setting setting : xref.getInverseReferences(semElt)) { EObject eObj = setting.getEObject(); EReference targetReference = ViewpointPackage.Literals.DSEMANTIC_DECORATOR__TARGET; EReference semanticElementsReference = ViewpointPackage.Literals.DREPRESENTATION_ELEMENT__SEMANTIC_ELEMENTS; if (eObj instanceof DRepresentationElement && setting.getEStructuralFeature().equals(semanticElementsReference) && EcoreUtil.isAncestor(root, eObj)) { decoratorsToDestroy.add((DSemanticDecorator) eObj); } else if (eObj instanceof DSemanticDecorator && setting.getEStructuralFeature().equals(targetReference) && EcoreUtil.isAncestor(root, eObj)) { decoratorsToDestroy.add((DSemanticDecorator) eObj); } } } return decoratorsToDestroy; }

Target:
private Set<DSemanticDecorator> getDElementToClearWithXref(final EObject root, final Set<EObject> semanticElements, final ECrossReferenceAdapter xref) { final Set<DSemanticDecorator> decoratorsToDestroy = new HashSet<DSemanticDecorator>(); for (EObject semElt : semanticElements) { for (Setting setting : xref.getInverseReferences(semElt)) { EObject eObj = setting.getEObject(); if (setting.getEStructuralFeature().equals(DSEMANTIC_DECORATOR__TARGET) && EcoreUtil.isAncestor(root, eObj)) { decoratorsToDestroy.add((DSemanticDecorator) eObj); } else if (!decoratorsToDestroy.contains(eObj) && setting.getEStructuralFeature().equals(DREPRESENTATION_ELEMENT__SEMANTIC_ELEMENTS) && EcoreUtil.isAncestor(root, eObj)) { DRepresentationElement repElt = (DRepresentationElement) eObj; if (semanticElements.containsAll(repElt.getSemanticElements())) { decoratorsToDestroy.add(repElt); } } } } return decoratorsToDestroy; }
Source:
public static ObjectNode unflattenObjectNode(ObjectNode flatObject, char seperator) { ObjectNode root = mapper.createObjectNode(); Iterator<Map.Entry<String, JsonNode>> iter = flatObject.fields(); while (iter.hasNext()) { Map.Entry<String, JsonNode> item = iter.next(); String fullKey = item.getKey(); if( !fullKey.contains(Character.valueOf(seperator).toString())) { root.put(item.getKey(), item.getValue()); } else { ObjectNode currentNode = root; List<String> keyParts = Lists.newArrayList(); Iterables.addAll(keyParts, Splitter.on(seperator).split(item.getKey())); Iterator<String> keyPartIterator = Iterables.limit(Splitter.on(seperator).split(item.getKey()), keyParts.size()-1).iterator(); while( keyPartIterator.hasNext()) { String part = keyPartIterator.next(); if( currentNode.has(part) && currentNode.get(part).isObject() ) { currentNode = (ObjectNode) currentNode.get(part); } else { ObjectNode newNode = mapper.createObjectNode(); currentNode.put(part, newNode); currentNode = newNode; } }; currentNode.put(keyParts.get(keyParts.size()-1), item.getValue()); } } return root; }

Target:
public static ObjectNode unflattenObjectNode(ObjectNode flatObject, char seperator) { ObjectNode root = mapper.createObjectNode(); Iterator<Map.Entry<String, JsonNode>> iter = flatObject.fields(); while (iter.hasNext()) { Map.Entry<String, JsonNode> item = iter.next(); String fullKey = item.getKey(); if( !fullKey.contains(Character.valueOf(seperator).toString())) { root.put(item.getKey(), item.getValue()); } else { ObjectNode currentNode = root; List<String> keyParts = new ArrayList<>(Arrays.asList(StringUtils.split(item.getKey(), seperator))); keyParts.remove(keyParts.size()-1); Iterator<String> keyPartIterator = keyParts.iterator(); while( keyPartIterator.hasNext()) { String part = keyPartIterator.next(); if( currentNode.has(part) && currentNode.get(part).isObject() ) { currentNode = (ObjectNode) currentNode.get(part); } else { ObjectNode newNode = mapper.createObjectNode(); currentNode.put(part, newNode); currentNode = newNode; } }; currentNode.put(keyParts.get(keyParts.size()-1), item.getValue()); } } return root; }