auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean proceedVdsStats() { boolean returnValue = true; try { runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(getVds())); List<Guid> problematicDomainsIds = IrsBrokerCommand.fetchDomainsReportedAsProblematic(getVds().getStoragePoolId(), getVds().getDomains()); for (Guid domainId : problematicDomainsIds) { StorageDomainStatic domainInfo = getStorageDomainStaticDAO().get(domainId); log.errorFormat("Storage Domain {0} of pool {1} is in problem in host {1}", domainInfo != null ? domainInfo.getStorageName() : domainId, getStoragePool().getName(), getVds().getName()); if (domainInfo == null || domainInfo.getStorageDomainType().isDataDomain()) { returnValue = false; } } } catch (VdcBLLException e) { log.errorFormat("Could not get Host statistics for Host {0}, Error is {1}", getVds().getName(), e); returnValue = false; } return returnValue; }

Target:
protected boolean proceedVdsStats() { boolean returnValue = true; try { runVdsCommand(VDSCommandType.GetStats, new VdsIdAndVdsVDSCommandParametersBase(getVds())); List<Guid> problematicDomainsIds = IrsBrokerCommand.fetchDomainsReportedAsProblematic(getVds().getStoragePoolId(), getVds().getDomains()); for (Guid domainId : problematicDomainsIds) { StorageDomainStatic domainInfo = getStorageDomainStaticDAO().get(domainId); log.errorFormat("Storage Domain {0} of pool {1} is in problem in host {2}", domainInfo != null ? domainInfo.getStorageName() : domainId, getStoragePool().getName(), getVds().getName()); if (domainInfo == null || domainInfo.getStorageDomainType().isDataDomain()) { returnValue = false; } } } catch (VdcBLLException e) { log.errorFormat("Could not get Host statistics for Host {0}, Error is {1}", getVds().getName(), e); returnValue = false; } return returnValue; }
Source:
private void addSubmodule(String url, String name) throws SAXException { SubmoduleAddCommand add = new SubmoduleAddCommand(repo); try { Repository sub = add.setPath(name).setURI(url).call(); } catch (GitAPIException e) { throw new SAXException(e); } }

Target:
private void addSubmodule(String url, String name) throws SAXException { SubmoduleAddCommand add = new SubmoduleAddCommand(repo); if (monitor != null) add.setProgressMonitor(monitor); try { add.setPath(name).setURI(url).call(); } catch (GitAPIException e) { throw new SAXException(e); } }
Source:
public static int add(int a, int b) { return a + b; }

Target:
public int add(int a, int b) { return a + b; }
Source:
public void changeApiToken() throws IOException { user.checkPermission(Jenkins.ADMINISTER); LOGGER.log(Level.WARNING, "Deprecated usage of changeApiToken"); _changeApiToken(); tokenStore.generateTokenFromLegacy(apiToken); user.save(); }

Target:
public void changeApiToken() throws IOException { user.checkPermission(Jenkins.ADMINISTER); LOGGER.log(Level.FINE, "Deprecated usage of changeApiToken"); ApiTokenStore.HashedToken existingLegacyToken = tokenStore.getLegacyToken(); _changeApiToken(); tokenStore.regenerateTokenFromLegacy(apiToken); if(existingLegacyToken != null){ tokenStats.removeId(existingLegacyToken.getUuid()); } user.save(); }
Source:
public List<Programme> next() { ImmutableList.Builder<Programme> programmesBuilder = ImmutableList.builder(); int programmeCount = 0; while (programmeCount < 30 && hasNext()) { programmesBuilder.add(currentProgrammes.next()); programmeCount++; } return programmesBuilder.build(); }

Target:
public List<Programme> next() { try { return ImmutableList.copyOf(currentResponse.getNext().getResults()); } catch (GlycerinException e) { throw Throwables.propagate(e); } }
Source:
public void testBccSettingsSerialization() throws Exception { BccSettings settings = new BccSettings(); settings.setEnable(false); String jsonTwo = mapper.writeValueAsString(settings); System.out.println(jsonTwo); Assert.assertEquals(jsonTwo, "{\"enable\":false}"); }

Target:
public void testBccSettingsSerialization() throws Exception { BccSettings settings = new BccSettings(); settings.setEnable(false); String json = mapper.writeValueAsString(settings); System.out.println(json); Assert.assertEquals(json, "{\"enable\":false}"); }
Source:
private Schema getSchema(@Nonnull final SQLiteConnection sqliteConnection, @Nonnull final RelationKey relationKey) throws CatalogException { try { SQLiteStatement statement = sqliteConnection .prepare("SELECT col_name,col_type FROM relation_schema JOIN relations USING (user_name,program_name,relation_name) WHERE user_name=? AND program_name=? AND relation_name=? ORDER BY col_index ASC"); statement.bind(1, relationKey.getUserName()); statement.bind(2, relationKey.getProgramName()); statement.bind(3, relationKey.getRelationName()); ImmutableList.Builder<String> names = ImmutableList.builder(); ImmutableList.Builder<Type> types = ImmutableList.builder(); if (!statement.step()) { return null; } do { names.add(statement.columnString(0)); types.add(Type.valueOf(statement.columnString(1))); } while (statement.step()); statement.dispose(); return new Schema(types, names); } catch (final SQLiteException e) { throw new CatalogException(e); } }

Target:
private Schema getSchema(@Nonnull final SQLiteConnection sqliteConnection, @Nonnull final RelationKey relationKey) throws CatalogException { try { SQLiteStatement statement = sqliteConnection .prepare("SELECT col_name,col_type FROM relation_schema WHERE user_name=? AND program_name=? AND relation_name=? ORDER BY col_index ASC"); statement.bind(1, relationKey.getUserName()); statement.bind(2, relationKey.getProgramName()); statement.bind(3, relationKey.getRelationName()); ImmutableList.Builder<String> names = ImmutableList.builder(); ImmutableList.Builder<Type> types = ImmutableList.builder(); if (!statement.step()) { return null; } do { names.add(statement.columnString(0)); types.add(Type.valueOf(statement.columnString(1))); } while (statement.step()); statement.dispose(); return new Schema(types, names); } catch (final SQLiteException e) { throw new CatalogException(e); } }
Source:
public Object instantiate(Class actualType, JSONObject json) { if (Modifier.isAbstract(actualType.getModifiers())) { LOGGER.log(Level.FINE, "ignoring abstract {0} {1}", new Object[] {actualType, json}); return oldInterceptor.instantiate(actualType, json); } if (!Describable.class.isAssignableFrom(actualType)) { LOGGER.log(Level.FINE, "ignoring non-Describable {0} {1}", new Object[] {actualType, json}); return oldInterceptor.instantiate(actualType, json); } if (Boolean.TRUE.equals(processed.put(json, true))) { LOGGER.log(Level.FINE, "already processed {0} {1}", new Object[] {actualType, json}); return oldInterceptor.instantiate(actualType, json); } LOGGER.log(Level.FINE, "switching to newInstance {0} {1}", new Object[] {actualType, json}); try { return Jenkins.getActiveInstance().getDescriptor(actualType).newInstance(Stapler.getCurrentRequest(), json); } catch (Exception x) { LOGGER.log(Level.WARNING, "falling back to default instantiation " + actualType + " " + json, x); return oldInterceptor.instantiate(actualType, json); } }

Target:
public Object instantiate(Class actualType, JSONObject json) { if (isApplicable(actualType, json)) { LOGGER.log(Level.FINE, "switching to newInstance {0} {1}", new Object[] {actualType.getName(), json}); try { return Jenkins.getActiveInstance().getDescriptor(actualType).newInstance(Stapler.getCurrentRequest(), json); } catch (Exception x) { LOGGER.log(Level.WARNING, "falling back to default instantiation " + actualType.getName() + " " + json, x); } } return oldInterceptor.instantiate(actualType, json); }
Source:
default Set<Long> getNonTransferredAddresses(LogUnitClient client, ImmutableList<Long> addressesToTransfer) { if (addressesToTransfer.isEmpty()) { return new HashSet<>(); } long start = addressesToTransfer.get(0); long end = addressesToTransfer.get(addressesToTransfer.size() - 1); Set<Long> knownAddresses = CFUtils.getUninterruptibly(client.requestKnownAddresses(start, end)).getKnownAddresses(); return Sets.difference(new HashSet<>(addressesToTransfer), knownAddresses); }

Target:
default Set<Long> getNonTransferredAddresses(LogUnitClient client, ImmutableList<Long> addressesToTransfer) throws TimeoutException { if (addressesToTransfer.isEmpty()) { return new HashSet<>(); } long start = addressesToTransfer.get(0); long end = addressesToTransfer.get(addressesToTransfer.size() - 1); if (start > end) { throw new IllegalArgumentException("Entries are not in sequential order."); } Set<Long> knownAddresses = CFUtils.getUninterruptibly(client.requestKnownAddresses(start, end), TimeoutException.class, NetworkException.class).getKnownAddresses(); return Sets.difference(new HashSet<>(addressesToTransfer), knownAddresses); }
Source:
public void registerStateMachineWithManager(ByteBuffer requestedInitialState) throws InterruptedException { setRequestedInitialState(requestedInitialState); ListenableFuture<Boolean> initComplete = registerStateMachine(this, false); if (initComplete == null) { return; } try { Boolean initSuccussful = initComplete.get(); assert(initSuccussful); } catch (ExecutionException e) { Throwables.throwIfUnchecked(e); throw new RuntimeException(e.getCause()); } }

Target:
public void registerStateMachineWithManager(ByteBuffer requestedInitialState) throws InterruptedException { setRequestedInitialState(requestedInitialState); ListenableFuture<Boolean> initComplete = registerStateMachine(this, false); if (initComplete == null) { return; } try { Boolean initSuccessful = initComplete.get(); assert(initSuccessful); } catch (ExecutionException e) { Throwables.throwIfUnchecked(e); throw new RuntimeException(e.getCause()); } }
Source:
public Snippet createSnippet(String title, String fileName, String content, Visibility visibility, String description) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("title", title) .withParam("file_name", fileName) .withParam("content", content) .withParam("visibility", visibility) .withParam("description", description); Response response = post(Response.Status.CREATED, formData, "snippets"); return (response.readEntity(Snippet.class)); }

Target:
public Snippet createSnippet(String title, String fileName, String content, Visibility visibility, String description) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("title", title, true) .withParam("file_name", fileName, true) .withParam("content", content, true) .withParam("visibility", visibility) .withParam("description", description); Response response = post(Response.Status.CREATED, formData, "snippets"); return (response.readEntity(Snippet.class)); }
Source:
public TObject maxKey(String key, AccessToken creds, TransactionToken transaction, String environment) throws TException { checkAccess(creds, transaction); AtomicSupport store = getStore(transaction, environment); AtomicOperation atomic = null; TObject max = null; while (atomic == null || !atomic.commit()) { atomic = store.startAtomicOperation(); try { Map<TObject, Set<Long>> data = atomic.browse(key); int size = data.size(); int c = 0; for (Entry<TObject, Set<Long>> entry : data.entrySet()) { if(c == size - 1) { TObject tobject = entry.getKey(); max = tobject; break; } c++; } } catch (AtomicStateException e) { atomic = null; max = null; } } return max; }

Target:
public TObject maxKey(String key, AccessToken creds, TransactionToken transaction, String environment) throws TException { checkAccess(creds, transaction); AtomicSupport store = getStore(transaction, environment); AtomicOperation atomic = null; TObject max = null; while (atomic == null || !atomic.commit()) { atomic = store.startAtomicOperation(); try { Map<TObject, Set<Long>> data = atomic.browse(key); max = Iterables.getLast(data.keySet(), max); } catch (AtomicStateException e) { atomic = null; max = null; } } return max; }
Source:
private String supportedVersionsToString(Set<Version> versionSet) { if (versionSet == null) { return null; } StringBuilder sb = new StringBuilder(); for (Version version : versionSet) { sb.append(version.toString()); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); }

Target:
private String supportedVersionsToString(Set<Version> versionSet) { if (versionSet == null) { return null; } StringBuilder sb = new StringBuilder(); boolean first = true; for (Version version : versionSet) { if (first) { first = false; } else { sb.append(","); } sb.append(version.toString()); } return sb.toString(); }
Source:
private static Map<String, String> normalizeHeaderValues(final Map<String, String> headerValues) { final HashMap<String, String> headers = new HashMap<>(); for (final Map.Entry<String, String> entry : headerValues.entrySet()) { headers.put(entry.getKey().toLowerCase(), entry.getValue()); } return headers; }

Target:
private static Map<String, String> normalizeHeaderValues(final Map<String, String> headerValues) { final Map<String, String> headers = new HashMap<>(); for (final Map.Entry<String, String> entry : headerValues.entrySet()) { headers.put(entry.getKey().toLowerCase(), entry.getValue()); } return headers; }
Source:
public CloudConfig(String cluster, boolean enabled, CloudProvider cloudProvider, String cloudID, List<String> cloudInfoSource, String cloudProcessorName) { super(cluster); _record.setBooleanField(CloudConfigProperty.CLOUD_ENABLED.name(), enabled); _record.setSimpleField(CloudConfigProperty.CLOUD_PROVIDER.name(), cloudProvider.name()); _record.setSimpleField(CloudConfigProperty.CLOUD_ID.name(), cloudID); _record.setSimpleField(CloudConfigProperty.CLOUD_INFO_PROCESSOR_NAME.name(), cloudProcessorName); _record.setListField(CloudConfigProperty.CLOUD_INFO_SOURCE.name(), cloudInfoSource); }

Target:
public CloudConfig(String cluster, boolean enabled, CloudProvider cloudProvider, String cloudID, List<String> cloudInfoSource, String cloudProcessorName) { super(cluster); _record.setBooleanField(CloudConfigProperty.CLOUD_ENABLED.name(), enabled); _record.setSimpleField(CloudConfigProperty.CLOUD_PROVIDER.name(), cloudProvider.name()); _record.setSimpleField(CloudConfigProperty.CLOUD_ID.name(), cloudID); if (cloudProvider.equals(CloudProvider.CUSTOMIZED)) { _record .setSimpleField(CloudConfigProperty.CLOUD_INFO_PROCESSOR_NAME.name(), cloudProcessorName); _record.setListField(CloudConfigProperty.CLOUD_INFO_SOURCE.name(), cloudInfoSource); } }
Source:
public List<String> retrieveAllArtifacts(String label) throws ArtifactSynchronizerException { List<String> gatewayRuntimeArtifactsArray = new ArrayList<>(); try { String baseURL = APIConstants.HTTPS_PROTOCOL_URL_PREFIX + System.getProperty(APIConstants.KEYMANAGER_HOSTNAME) + ":" + System.getProperty(APIConstants.KEYMANAGER_PORT) + APIConstants.INTERNAL_WEB_APP_EP; String endcodedgatewayLabel= URLEncoder.encode(label, APIConstants.DigestAuthConstants.CHARSET); String path = APIConstants.GatewayArtifactSynchronizer.GATEAY_SYNAPSE_ARTIFACTS + "?gatewayLabel="+ endcodedgatewayLabel; String endpoint = baseURL + path; HttpResponse httpResponse = invokeService(endpoint); String responseString = EntityUtils.toString(httpResponse.getEntity(), APIConstants.DigestAuthConstants.CHARSET); JSONObject artifactObject = new JSONObject(responseString); JSONArray jArray = (JSONArray)artifactObject.get("list"); if (jArray != null) { for (int i = 0; i < jArray.length(); i++) { gatewayRuntimeArtifactsArray.add(jArray.get(i).toString()); } } return gatewayRuntimeArtifactsArray; } catch (IOException e) { String msg = "Error while executing the http client " ; log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } }

Target:
public List<String> retrieveAllArtifacts(String label) throws ArtifactSynchronizerException { List<String> gatewayRuntimeArtifactsArray = new ArrayList<>(); CloseableHttpResponse httpResponse = null; try { String endcodedgatewayLabel= URLEncoder.encode(label, APIConstants.DigestAuthConstants.CHARSET); String path = APIConstants.GatewayArtifactSynchronizer.GATEAY_SYNAPSE_ARTIFACTS + "?gatewayLabel="+ endcodedgatewayLabel; String endpoint = baseURL + path; httpResponse = invokeService(endpoint); String responseString; if (httpResponse.getEntity() != null ) { responseString = EntityUtils.toString(httpResponse.getEntity(), APIConstants.DigestAuthConstants.CHARSET); httpResponse.close(); } else { throw new ArtifactSynchronizerException("HTTP response is empty"); } JSONObject artifactObject = new JSONObject(responseString); JSONArray jArray = (JSONArray)artifactObject.get("list"); if (jArray != null) { for (int i = 0; i < jArray.length(); i++) { gatewayRuntimeArtifactsArray.add(jArray.get(i).toString()); } } return gatewayRuntimeArtifactsArray; } catch (IOException e) { String msg = "Error while executing the http client"; log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } }
Source:
public PrologEnvironment newPrologEnvironment() { PrologEnvironment env = envFactory.create(getClass().getClassLoader()); ObjectStream ruleStream = getPrologRules(); if (ruleStream != null) { try { PushbackReader in = new PushbackReader(new InputStreamReader(ruleStream, Charset.forName("UTF-8")), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.makeSymbol("submitrules"), streamObject)) { throw new CompileException("Cannot consult" + streamObject.toString()); } } catch (CompileException err) { log.error("Cannot consult provided submit_rules.pl", err); } finally { try { ruleStream.close(); } catch (IOException err) { log.error("Close of ruleStream failed", err); } } } else { VariableTerm var = new VariableTerm(); StructureTerm head = new StructureTerm("submit_rule", var); StructureTerm defaultRule= new StructureTerm(":", SymbolTerm.makeSymbol("com.google.gerrit.rules.common"), new StructureTerm("default_submit", var)); StructureTerm clause = new StructureTerm(":-", head, defaultRule); env.execute(Prolog.BUILTIN, "assertz", clause); } return env; }

Target:
public PrologEnvironment newPrologEnvironment() throws CompileException, IOException{ PrologEnvironment env = envFactory.create(getClass().getClassLoader()); ObjectStream ruleStream; ruleStream = getPrologRules(); if (ruleStream != null) { try { PushbackReader in = new PushbackReader(new InputStreamReader(ruleStream, Charset.forName("UTF-8")), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.makeSymbol("rules.pl"), streamObject)) { throw new CompileException("Cannot consult " + getProject().getName() + " " + getConfig().getRevision()); } } finally { ruleStream.close(); } } else { VariableTerm var = new VariableTerm(); StructureTerm head = new StructureTerm("submit_rule", var); StructureTerm defaultRule = new StructureTerm(":", SymbolTerm.makeSymbol("com.google.gerrit.rules.common"), new StructureTerm("default_submit", var)); StructureTerm clause = new StructureTerm(":-", head, defaultRule); env.execute(Prolog.BUILTIN, "assertz", clause); } return env; }
Source:
public void sendMessage(String message, boolean success) { if (uuid == null || uuid.isEmpty()) { return; } else if (hookURL == null || hookURL.isEmpty()) { System.err.println("Notifications UUID is specified but no notifications webhook URL found in config file"); } else { LOG.debug("Sending notifications message"); String messageToSend = createText(message, success); String jsonMessage; if (this.hookURL.contains("://hooks.slack.com")) { SlackMessage slackPojo = new SlackMessage(); slackPojo.setText(messageToSend); Gson gson = new Gson(); jsonMessage = gson.toJson(slackPojo); } else { LOG.debug("Can not resolve webhook URL"); return; } if (jsonMessage != null && !jsonMessage.isEmpty()) { generalSendMessage(jsonMessage); } } }

Target:
public void sendMessage(String message, boolean success) { if (disabled) { return; } else { LOG.debug("Sending notifications message."); String messageToSend = createText(message, success); String jsonMessage; if (this.hookURL.contains("://hooks.slack.com")) { LOG.warn("Destination is Slack. Message is not 100% compatible."); } Message messageObject = new Message(); messageObject.setText(messageToSend); messageObject.setUuid(this.uuid); Gson gson = new Gson(); jsonMessage = gson.toJson(messageObject); if (jsonMessage != null && !jsonMessage.isEmpty()) { generalSendMessage(jsonMessage); } } }
Source:
protected List<OSProcess> processSort(List<OSProcess> processes, int limit, ProcessSort sort) { if (sort != null) { switch (sort) { case CPU: Collections.sort(processes, CPU_DESC_SORT); break; case MEMORY: Collections.sort(processes, RSS_DESC_SORT); break; case OLDEST: Collections.sort(processes, UPTIME_DESC_SORT); break; case NEWEST: Collections.sort(processes, UPTIME_ASC_SORT); break; case PID: Collections.sort(processes, PID_ASC_SORT); break; case PARENTPID: Collections.sort(processes, PARENTPID_ASC_SORT); break; case NAME: Collections.sort(processes, NAME_ASC_SORT); break; default: throw new IllegalArgumentException("Unimplemented enum type: " + sort.toString()); } } if (limit == 0) return processes; int maxProcs = processes.size(); if (limit > 0 && maxProcs > limit) { maxProcs = limit; } List<OSProcess> procs = new ArrayList<>(); for (int i = 0; i < maxProcs; i++) { procs.add(processes.get(i)); } return procs; }

Target:
protected List<OSProcess> processSort(List<OSProcess> processes, int limit, ProcessSort sort) { if (sort != null) { switch (sort) { case CPU: Collections.sort(processes, CPU_DESC_SORT); break; case MEMORY: Collections.sort(processes, RSS_DESC_SORT); break; case OLDEST: Collections.sort(processes, UPTIME_DESC_SORT); break; case NEWEST: Collections.sort(processes, UPTIME_ASC_SORT); break; case PID: Collections.sort(processes, PID_ASC_SORT); break; case PARENTPID: Collections.sort(processes, PARENTPID_ASC_SORT); break; case NAME: Collections.sort(processes, NAME_ASC_SORT); break; default: throw new IllegalArgumentException("Unimplemented enum type: " + sort.toString()); } } if (limit == 0 || limit >= processes.size()) return processes; int maxProcs = processes.size(); if (limit > 0 && maxProcs > limit) { maxProcs = limit; } List<OSProcess> procs = new ArrayList<>(); for (int i = 0; i < maxProcs; i++) { procs.add(processes.get(i)); } return procs; }
Source:
public void retryTimesPredicateWithMatchingPredicate() { final AtomicInteger atomicInteger = new AtomicInteger(3); Completable.fromAction(new Action() { @Override public void run() throws Exception { if (atomicInteger.decrementAndGet() != 0) { throw new RuntimeException(); } throw new IllegalArgumentException(); } }) .retry(Integer.MAX_VALUE, new Predicate<Throwable>() { @Override public boolean test(final Throwable throwable) throws Exception { return !(throwable instanceof IllegalArgumentException); } }) .test() .assertFailure(IllegalArgumentException.class); }

Target:
public void retryTimesPredicateWithMatchingPredicate() { final AtomicInteger atomicInteger = new AtomicInteger(3); final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0); Completable.fromAction(new Action() { @Override public void run() throws Exception { numberOfSubscribeCalls.incrementAndGet(); if (atomicInteger.decrementAndGet() != 0) { throw new RuntimeException(); } throw new IllegalArgumentException(); } }) .retry(Integer.MAX_VALUE, new Predicate<Throwable>() { @Override public boolean test(final Throwable throwable) throws Exception { return !(throwable instanceof IllegalArgumentException); } }) .test() .assertFailure(IllegalArgumentException.class); assertEquals(3, numberOfSubscribeCalls.get()); }
Source:
public void edit(final GlusterVolumeGeoRepActionConfirmationModel object) { driver.edit(object); forceEditor.setLabel(object.getForceLabel() == null ? constants.notAvailableLabel() : object.getMessage()); messageLabel.setText(object.getMessage() == null ? constants.notAvailableLabel() : object.getMessage()); }

Target:
public void edit(final GlusterVolumeGeoRepActionConfirmationModel object) { driver.edit(object); }
Source:
public void validate(AbstractLauncherSettings settings) { for (SettingsValidationRule rule : validationRules) { if (rule.isBrokenBy(settings)) { logger.warn(rule.getInvalidationMessage()); rule.correct(settings); } } }

Target:
public static void validate(AbstractLauncherSettings settings) { for (SettingsValidationRule rule : RULES) { if (rule.isBrokenBy(settings)) { logger.warn(rule.getInvalidationMessage()); rule.correct(settings); } } }
Source:
public static long decodeTimestamp(long seconds, long serializedNanos, long baseTimestampInSeconds) { long millis = (seconds + baseTimestampInSeconds) * MILLIS_PER_SECOND; long nanos = parseNanos(serializedNanos); if (nanos > 999999999 || nanos < 0) { throw new IllegalArgumentException("nanos > 999999999 or < 0"); } if (millis < 0 && nanos != 0) { millis -= 1000; } return millis + (nanos / 1_000_000); }

Target:
public static long decodeTimestamp(long seconds, long serializedNanos, long baseTimestampInSeconds) { long millis = (seconds + baseTimestampInSeconds) * MILLIS_PER_SECOND; long nanos = parseNanos(serializedNanos); if (nanos > 999999999 || nanos < 0) { throw new IllegalArgumentException("nanos field of an encoded timestamp in ORC must be between 0 and 999999999 inclusive, got " + nanos); } if (millis < 0 && nanos != 0) { millis -= 1000; } return millis + (nanos / 1_000_000); }
Source:
public ByteBuffer getBlob(final int row) { if (type == Type.BLOB_TYPE) { return byteValue; } throw new UnsupportedOperationException(); }

Target:
public ByteBuffer getBlob(final int row) { if (type == Type.BLOB_TYPE) { return blobValue; } throw new UnsupportedOperationException(); }
Source:
public void onHarvest(ActivateEvent event, EntityRef entity, BushDefinitionComponent bushComponent, BlockComponent blockComponent) { EntityRef harvester = event.getInstigator(); if (!event.isConsumed() && areValidHarvestEntities(entity, harvester) && harvester.hasComponent(PlayerCharacterComponent.class)) { if (isInLastStage(bushComponent)) { dropProduce(bushComponent.produce, event.getTargetLocation(), harvester, entity); if (bushComponent.sustainable) { doBushGrowth(blockComponent.getPosition(), bushComponent, -1); } else { entity.send(new DoDestroyPlant()); worldProvider.setBlock(blockComponent.getPosition(), blockManager.getBlock(BlockManager.AIR_ID)); entity.destroy(); } event.consume(); } } }

Target:
public void onHarvest(ActivateEvent event, EntityRef entity, BushDefinitionComponent bushComponent, BlockComponent blockComponent) { EntityRef harvester = event.getInstigator(); if (!event.isConsumed() && areValidHarvestEntities(entity, harvester)) { if (isInLastStage(bushComponent)) { dropProduce(bushComponent.produce, event.getTargetLocation(), harvester, entity); if (bushComponent.sustainable) { doBushGrowth(blockComponent.getPosition(), bushComponent, -1); } else { entity.send(new DoDestroyPlant()); worldProvider.setBlock(blockComponent.getPosition(), blockManager.getBlock(BlockManager.AIR_ID)); entity.destroy(); } event.consume(); } } }
Source:
private int commonPrefixLength(List<String> classNames) { int size = Math.min(classNames.size(), typeSpecStack.size()); for (int i = 0; i < size; i++) { String a = classNames.get(i); String b = typeSpecStack.get(i).name; if (!a.equals(b)) { for (; i > 0; i--) { if (!parentTypeHasMemberType(classNames.get(i), i)) { return i; } } return 0; } } return size; }

Target:
private int commonPrefixLength(List<String> classNames) { int size = Math.min(classNames.size(), typeSpecStack.size()); for (int i = 0; i < size; i++) { String a = classNames.get(i); String b = typeSpecStack.get(i).name; if (!a.equals(b)) return i; } return size; }
Source:
boolean topologyChanged(TopologySnapshot prev) { return prev != null && !prev.nids.equals(nids) && !Collections.disjoint(nids, prev.nids); }

Target:
boolean topologyChanged(TopologySnapshot prev) { return prev != null && !prev.nids.equals(nids); }
Source:
public final Response uploadTempResourceMulti(@Context final HttpServletRequest request, @Context final HttpServletResponse response, final FormDataMultiPart body) { try { if (!Config.getBooleanProperty(TempFileAPI.TEMP_RESOURCE_ENABLED, true)) { final String message = "Temp Files Resource is not enabled, please change the TEMP_RESOURCE_ENABLED to true in your properties file"; Logger.error(this, message); throw new DoesNotExistException(message); } final boolean allowAnonToUseTempFiles = !Config .getBooleanProperty(TempFileAPI.TEMP_RESOURCE_ALLOW_ANONYMOUS, true); final InitDataObject initDataObject = this.webResource .init(false, request, allowAnonToUseTempFiles); final User user = initDataObject.getUser(); final String uniqueKey = request.getSession().getId(); if (!new SecurityUtils().validateReferer(request)) { throw new BadRequestException("Invalid Origin or referer"); } final List<DotTempFile> tempFiles = new ArrayList<DotTempFile>(); for (final BodyPart part : body.getBodyParts()) { InputStream in = (part.getEntity() instanceof InputStream) ? InputStream.class .cast(part.getEntity()) : Try.of(() -> part.getEntityAs(InputStream.class)).getOrNull(); if (in == null) { continue; } final ContentDisposition meta = part.getContentDisposition(); if (meta == null) { continue; } final String fileName = meta.getFileName(); if (fileName == null || fileName.startsWith(".") || fileName.contains("/.")) { continue; } tempFiles.add(tempApi.createTempFile(fileName, user, uniqueKey, in)); } return Response.ok(ImmutableMap.of("tempFiles", tempFiles)).build(); } catch (Exception e) { Logger.warnAndDebug(this.getClass(), e); return ResponseUtil.mapExceptionResponse(e); } }

Target:
public final Response uploadTempResourceMulti(@Context final HttpServletRequest request, @Context final HttpServletResponse response, final FormDataMultiPart body) { try { verifyTempResourceEnabled(); final boolean allowAnonToUseTempFiles = !Config .getBooleanProperty(TempFileAPI.TEMP_RESOURCE_ALLOW_ANONYMOUS, true); final InitDataObject initDataObject = this.webResource .init(false, request, allowAnonToUseTempFiles); final User user = initDataObject.getUser(); final String uniqueKey = request.getSession().getId(); if (!new SecurityUtils().validateReferer(request)) { throw new BadRequestException("Invalid Origin or referer"); } final List<DotTempFile> tempFiles = new ArrayList<DotTempFile>(); for (final BodyPart part : body.getBodyParts()) { InputStream in = (part.getEntity() instanceof InputStream) ? InputStream.class .cast(part.getEntity()) : Try.of(() -> part.getEntityAs(InputStream.class)).getOrNull(); if (in == null) { continue; } final ContentDisposition meta = part.getContentDisposition(); if (meta == null) { continue; } final String fileName = meta.getFileName(); if (fileName == null || fileName.startsWith(".") || fileName.contains("/.")) { continue; } tempFiles.add(tempApi.createTempFile(fileName, user, uniqueKey, in)); } return Response.ok(ImmutableMap.of("tempFiles", tempFiles)).build(); } catch (Exception e) { Logger.warnAndDebug(this.getClass(), e); return ResponseUtil.mapExceptionResponse(e); } }
Source:
public void testPropertiesFrom(File configFile, String[] supportedCipherSuites) throws Exception { try { TlsConfiguration tlsConfiguration = new TlsConfiguration(DEFAULT_KEYSTORE); tlsConfiguration.initialise(true, JSSE_NAMESPACE); SSLSocket socket = (SSLSocket) tlsConfiguration.getSocketFactory().createSocket(); SSLServerSocket serverSocket = (SSLServerSocket) tlsConfiguration.getServerSocketFactory().createServerSocket(); Assert.assertEquals(new HashSet<String>(Arrays.asList(supportedCipherSuites)), new HashSet<String>(Arrays.asList(socket.getEnabledCipherSuites()))); Assert.assertEquals(new HashSet<String>(Arrays.asList(supportedCipherSuites)), new HashSet<String>(Arrays.asList(socket.getEnabledCipherSuites()))); } finally { deleteFile(configFile); } }

Target:
public void testPropertiesFrom(File configFile, String[] supportedCipherSuites) throws Exception { try { TlsConfiguration tlsConfiguration = new TlsConfiguration(DEFAULT_KEYSTORE); tlsConfiguration.initialise(true, JSSE_NAMESPACE); SSLSocket socket = (SSLSocket) tlsConfiguration.getSocketFactory().createSocket(); SSLServerSocket serverSocket = (SSLServerSocket) tlsConfiguration.getServerSocketFactory().createServerSocket(); assertThat(socket.getEnabledCipherSuites(), arrayContainingInAnyOrder(supportedCipherSuites)); assertThat(serverSocket.getEnabledCipherSuites(), arrayContainingInAnyOrder(supportedCipherSuites)); } finally { deleteFile(configFile); } }
Source:
private boolean containsAcl(OzoneAcl ozoneAcl, List<OzoneAcl> ozoneAcls) { for (OzoneAcl acl : ozoneAcls) { if (acl.getType().equals(ozoneAcl.getType()) && acl.getName().equals(ozoneAcl.getName()) && acl.getAclBitSet().equals(ozoneAcl.getAclBitSet()) && acl.getAclScope().equals(ozoneAcl.getAclScope())) { return true; } } return false; }

Target:
private boolean containsAcl(OzoneAcl ozoneAcl, List<OzoneAcl> ozoneAcls) { for (OzoneAcl acl : ozoneAcls) { boolean result = compareAcls(ozoneAcl, acl); if (result) { return result; } } return false; }
Source:
private boolean mountGlusterMetaVolume() { VDSReturnValue retVal = runVdsCommand(VDSCommandType.MountGlusterMetaVolume, new VdsIdVDSCommandParametersBase(getVdsId())); if (!retVal.getSucceeded()) { log.error("Failed to mount gluster meta volume on server {}: {}", getVdsName(), retVal.getVdsError().getMessage()); } return true; }

Target:
private boolean mountGlusterMetaVolume() { if (getGlusterVolumeDao().getByName(getVdsGroupId(), Config.<String> getValue(ConfigValues.GlusterMetaVolumeName)) != null) { VDSReturnValue retVal = runVdsCommand(VDSCommandType.MountGlusterMetaVolume, new VdsIdVDSCommandParametersBase(getVdsId())); if (!retVal.getSucceeded()) { log.error("Failed to mount gluster meta volume on server {}: {}", getVdsName(), retVal.getVdsError().getMessage()); } } return true; }
Source:
public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); final CreateJobResponse createIdMismatch = client.createJob( new Job(JobId.fromString("bad:job:deadbeef"), "busyBox", IDLE_COMMAND, EMPTY_ENV, EMPTY_PORTS, EMPTY_REGISTRATION, EMPTY_VOLUMES, null)).get(); assertEquals(CreateJobResponse.Status.INVALID_JOB_DEFINITION, createIdMismatch.getStatus()); }

Target:
public void test() throws Exception { startDefaultMaster(); final HeliosClient client = defaultClient(); final CreateJobResponse createIdMismatch = client.createJob( new Job(JobId.fromString("bad:job:deadbeef"), "busyBox", IDLE_COMMAND, EMPTY_ENV, EMPTY_PORTS, EMPTY_REGISTRATION, EMPTY_VOLUMES, EMPTY_EXPIRES)).get(); assertEquals(CreateJobResponse.Status.INVALID_JOB_DEFINITION, createIdMismatch.getStatus()); }
Source:
public void testHighlight() { final Rectangle cellBounds = SWTBotUtils.getCellBounds(fTableBot.widget, ROW, COLUMN); Map<RGB, Integer> colorBefore = ImageHelper.getScreenGrab(cellBounds).getHistogram(); fTableBot.click(0, COLUMN); fBot.text().typeText("HostF\n", 100); fTableBot.select(4); Map<RGB, Integer> colorAfter = ImageHelper.getScreenGrab(cellBounds).getHistogram(); assertTrue(colorBefore.containsKey(BLACK)); assertTrue(colorBefore.containsKey(WHITE)); assertFalse(colorBefore.containsKey(YELLOW)); assertTrue(colorAfter.containsKey(BLACK)); assertTrue(colorAfter.containsKey(WHITE)); assertTrue(colorAfter.containsKey(YELLOW)); Map<RGB, Integer> diff = new HashMap<>(); for (Entry<RGB, Integer> entry : colorAfter.entrySet()) { RGB key = entry.getKey(); if (colorBefore.containsKey(key)) { diff.put(key, entry.getValue() - colorBefore.get(key)); } else { diff.put(key, entry.getValue()); } } assertTrue(diff.get(WHITE).equals(-diff.get(YELLOW))); }

Target:
public void testHighlight() { final Rectangle cellBounds = SWTBotUtils.getCellBounds(fTableBot.widget, ROW, SOURCE_COLUMN); Map<RGB, Integer> colorBefore = ImageHelper.getScreenGrab(cellBounds).getHistogram(); fTableBot.click(0, SOURCE_COLUMN); fBot.text().typeText("HostF\n", 100); fTableBot.select(ROW - 1); Map<RGB, Integer> colorAfter = ImageHelper.getScreenGrab(cellBounds).getHistogram(); assertTrue(colorBefore.containsKey(fBackground)); assertTrue(colorBefore.containsKey(fForeground)); assertFalse(colorBefore.containsKey(YELLOW)); assertTrue(colorAfter.containsKey(fBackground)); assertTrue(colorAfter.containsKey(fForeground)); assertTrue(colorAfter.containsKey(YELLOW)); Map<RGB, Integer> diff = new HashMap<>(); for (Entry<RGB, Integer> entry : colorAfter.entrySet()) { RGB key = entry.getKey(); if (colorBefore.containsKey(key)) { diff.put(key, entry.getValue() - colorBefore.get(key)); } else { diff.put(key, entry.getValue()); } } assertTrue(diff.get(fBackground).equals(-diff.get(YELLOW))); }
Source:
private void createTrim(MUIElement element) { MWindow win = getWindowFor(element); if (win instanceof MTrimmedWindow) { MTrimmedWindow window = (MTrimmedWindow) win; Shell winShell = (Shell) window.getWidget(); String trimId = element.getElementId() + getMinimizedElementSuffix(element); MToolControl trimStack = (MToolControl) modelService.find(trimId, window); if (trimStack == null) { trimStack = MenuFactoryImpl.eINSTANCE.createToolControl(); trimStack.setElementId(trimId); trimStack.setContributionURI(TrimStack.CONTRIBUTION_URI); trimStack.getTags().add("TrimStack"); MTrimBar bar = getBarForElement(element, window); int index = getCachedIndex(element); if (index == -1 || index >= bar.getChildren().size()) bar.getChildren().add(trimStack); else bar.getChildren().add(index, trimStack); bar.setVisible(true); if (bar.getWidget() == null) { bar.setToBeRendered(true); context.get(IPresentationEngine.class).createGui(bar, winShell, window.getContext()); } } else { MUIElement parent = trimStack.getParent(); parent.setVisible(true); if (parent.getWidget() == null) { parent.setToBeRendered(true); context.get(IPresentationEngine.class).createGui(parent, winShell, window.getContext()); } trimStack.setToBeRendered(true); } } }

Target:
private void createTrim(MUIElement element) { MWindow win = getWindowFor(element); if (!(win instanceof MTrimmedWindow)) { return; } MTrimmedWindow window = (MTrimmedWindow) win; Shell winShell = (Shell) window.getWidget(); String trimId = element.getElementId() + getMinimizedElementSuffix(element); MToolControl trimStack = (MToolControl) modelService.find(trimId, window); if (trimStack == null) { trimStack = MenuFactoryImpl.eINSTANCE.createToolControl(); trimStack.setElementId(trimId); trimStack.setContributionURI(TrimStack.CONTRIBUTION_URI); trimStack.getTags().add("TrimStack"); MTrimBar bar = getBarForElement(element, window); int index = getCachedIndex(element); if (index == -1 || index >= bar.getChildren().size()) bar.getChildren().add(trimStack); else bar.getChildren().add(index, trimStack); bar.setVisible(true); if (bar.getWidget() == null) { bar.setToBeRendered(true); context.get(IPresentationEngine.class) .createGui(bar, winShell, window.getContext()); } } else { MUIElement parent = trimStack.getParent(); parent.setVisible(true); if (parent.getWidget() == null) { parent.setToBeRendered(true); context.get(IPresentationEngine.class).createGui(parent, winShell, window.getContext()); } trimStack.setToBeRendered(true); } }
Source:
protected void setAnyRouter() { setAttribute(MongoDBRouterCluster.ANY_ROUTER, Iterables.tryFind(getRouters(), new Predicate<MongoDBRouter>() { @Override public boolean apply(MongoDBRouter input) { return input.getAttribute(Startable.SERVICE_UP); }}).orNull()); }

Target:
protected void setAnyRouter() { setAttribute(MongoDBRouterCluster.ANY_ROUTER, Iterables.tryFind(getRouters(), EntityPredicates.attributeEqualTo(Startable.SERVICE_UP, true)).orNull()); setAttribute(MongoDBRouterCluster.ANY_RUNNING_ROUTER, Iterables.tryFind(getRouters(), new Predicate<MongoDBRouter>() { @Override public boolean apply(MongoDBRouter input) { return input.getAttribute(MongoDBRouter.RUNNING); }}).orNull()); }
Source:
public Object call(Properties bindings, Object[] args) { if (args.length == 3) { Object v = args[0]; Object targetProjectName = args[1]; Object targetColumnName = args[2]; long targetProjectID; ProjectLookup lookup; if ((v instanceof String || v instanceof Long || v instanceof Integer || v instanceof WrappedCell) && (targetProjectName instanceof String && targetColumnName instanceof String)) { try { targetProjectID = ProjectManager.singleton.getProjectID((String) targetProjectName); } catch (GetProjectIDException e) { return new EvalError(e.getMessage()); } try { lookup = ProjectManager.singleton.getLookupCacheManager().getLookup(targetProjectID, (String) targetColumnName); } catch (LookupException e) { return new EvalError(e.getMessage()); } if (v instanceof WrappedCell) { return lookup.getRows(((WrappedCell) v).cell.value); } else { return lookup.getRows(v); } } } return new EvalError(ControlFunctionRegistry.getFunctionName(this) + " expects a string or long or int or cell, a project name to look up, and a column name in that project"); }

Target:
public Object call(Properties bindings, Object[] args) { if (args.length == 3) { Object v = args[0]; Object targetProjectName = args[1]; Object targetColumnName = args[2]; long targetProjectID; ProjectLookup lookup; if (v != null && targetProjectName instanceof String && targetColumnName instanceof String) { try { targetProjectID = ProjectManager.singleton.getProjectID((String) targetProjectName); } catch (GetProjectIDException e) { return new EvalError(e.getMessage()); } try { lookup = ProjectManager.singleton.getLookupCacheManager().getLookup(targetProjectID, (String) targetColumnName); } catch (LookupException e) { return new EvalError(e.getMessage()); } if (v instanceof WrappedCell) { return lookup.getRows(((WrappedCell) v).cell.value); } else { return lookup.getRows(v); } } } return new EvalError(ControlFunctionRegistry.getFunctionName(this) + " expects a cell or cell value, a project name to look up, and a column name in that project"); }
Source:
public DeleteManager(ClusterMap clusterMap, ResponseHandler responseHandler, NotificationSystem notificationSystem, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, Time time) { this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.notificationSystem = notificationSystem; this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.time = time; deleteOperations = new HashSet<DeleteOperation>(); correlationIdToDeleteOperation = new HashMap<Integer, DeleteOperation>(); }

Target:
DeleteManager(ClusterMap clusterMap, ResponseHandler responseHandler, NotificationSystem notificationSystem, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, Time time) { this.clusterMap = clusterMap; this.responseHandler = responseHandler; this.notificationSystem = notificationSystem; this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.time = time; deleteOperations = Collections.newSetFromMap(new ConcurrentHashMap<DeleteOperation, Boolean>()); correlationIdToDeleteOperation = new HashMap<Integer, DeleteOperation>(); }
Source:
public Aggregator factorize(ColumnSelectorFactory metricFactory) { return new DoubleLastAggregator( name, metricFactory.makeFloatColumnSelector(fieldName), metricFactory.makeLongColumnSelector(Column.TIME_COLUMN_NAME) ); }

Target:
public Aggregator factorize(ColumnSelectorFactory metricFactory) { return new DoubleLastAggregator( name, metricFactory.makeLongColumnSelector(Column.TIME_COLUMN_NAME), metricFactory.makeFloatColumnSelector(fieldName) ); }
Source:
public static QueryPostprocessDataContext createCassandraDataContext(Cluster cluster, String keySpaceName) { return new CassandraDataContext(cluster, keySpaceName); }

Target:
public static DataContext createCassandraDataContext(Cluster cluster, String keySpaceName) { return new CassandraDataContext(cluster, keySpaceName); }
Source:
private static DataSize writeOrcColumnPresto(File outputFile, Format format, CompressionKind compression, Type type, Iterator<?> values) throws Exception { ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("columns", "test"); metadata.put("columns.types", createSettableStructObjectInspector("test", type).getTypeName()); OutputStream outputStream = new FileOutputStream(outputFile); OrcWriter writer; writer = new OrcWriter( outputStream, ImmutableList.of("test"), ImmutableList.of(type), format.getOrcEncoding(), compression, new OrcWriterOptions(), ImmutableMap.of(), HIVE_STORAGE_TIME_ZONE, true, new OrcWriterStats()); BlockBuilder blockBuilder = type.createBlockBuilder(new BlockBuilderStatus(), 1024); while (values.hasNext()) { Object value = values.next(); writeValue(type, blockBuilder, value); } writer.write(new Page(blockBuilder.build())); writer.close(); writer.validate(new FileOrcDataSource(outputFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true)); return new DataSize(new OutputStreamSliceOutput(outputStream).longSize(), Unit.BYTE); }

Target:
private static void writeOrcColumnPresto(File outputFile, Format format, CompressionKind compression, Type type, Iterator<?> values) throws Exception { ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("columns", "test"); metadata.put("columns.types", createSettableStructObjectInspector("test", type).getTypeName()); OrcWriter writer; writer = new OrcWriter( new FileOutputStream(outputFile), ImmutableList.of("test"), ImmutableList.of(type), format.getOrcEncoding(), compression, new OrcWriterOptions(), ImmutableMap.of(), HIVE_STORAGE_TIME_ZONE, true, new OrcWriterStats()); BlockBuilder blockBuilder = type.createBlockBuilder(new BlockBuilderStatus(), 1024); while (values.hasNext()) { Object value = values.next(); writeValue(type, blockBuilder, value); } writer.write(new Page(blockBuilder.build())); writer.close(); writer.validate(new FileOrcDataSource(outputFile, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true)); }
Source:
public void canSerialize() throws Exception { Phone phone = new Phone("408.258.8569", "US"); assertEquals("(408) 258-8569", phone.getNationalFormat()); JsonNode node = BridgeObjectMapper.get().valueToTree(phone); assertEquals("+14082588569", node.get("number").textValue()); assertEquals("US", node.get("regionCode").textValue()); assertEquals("Phone", node.get("type").textValue()); assertEquals(4, node.size()); Phone deser = BridgeObjectMapper.get().readValue(node.toString(), Phone.class); assertEquals(phone.getNumber(), deser.getNumber()); assertEquals(phone.getRegionCode(), deser.getRegionCode()); assertEquals("(408) 258-8569", deser.getNationalFormat()); }

Target:
public void canSerialize() throws Exception { Phone phone = new Phone("408.258.8569", "US"); assertEquals("+14082588569", phone.getNumber()); JsonNode node = BridgeObjectMapper.get().valueToTree(phone); assertEquals("+14082588569", node.get("number").textValue()); assertEquals("US", node.get("regionCode").textValue()); assertEquals("(408) 258-8569", node.get("nationalFormat").textValue()); assertEquals("Phone", node.get("type").textValue()); assertEquals(4, node.size()); Phone deser = BridgeObjectMapper.get().readValue(node.toString(), Phone.class); assertEquals(phone.getNumber(), deser.getNumber()); assertEquals(phone.getRegionCode(), deser.getRegionCode()); assertEquals("(408) 258-8569", deser.getNationalFormat()); }