auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void uploadPatientPhoto(final Patient patient) { RestApi apiService = RestServiceBuilder.createService(RestApi.class); PatientPhoto patientPhoto = new PatientPhoto(); patientPhoto.setPhoto(patient.getPerson().getPhoto()); patientPhoto.setPerson(patient.getPerson()); Call<PatientPhoto> personPhotoCall = apiService.uploadPatientPhoto(patient.getUuid(), patientPhoto); personPhotoCall.enqueue(new Callback<PatientPhoto>() { @Override public void onResponse(Call<PatientPhoto> call, Response<PatientPhoto> response) { if (!response.isSuccessful()) { ToastUtil.error("Patient[" + patient.getId() + "] photo cannot be synced due to server error"+ response.message()); } } @Override public void onFailure(Call<PatientPhoto> call, Throwable t) { ToastUtil.notify("Patient[" + patient.getId() + "] photo cannot be synced due to request error: " + t.toString()); } }); }

Target:
private void uploadPatientPhoto(final Patient patient) { RestApi apiService = RestServiceBuilder.createService(RestApi.class); PatientPhoto patientPhoto = new PatientPhoto(); patientPhoto.setPhoto(patient.getPerson().getPhoto()); patientPhoto.setPerson(patient.getPerson()); Call<PatientPhoto> personPhotoCall = apiService.uploadPatientPhoto(patient.getUuid(), patientPhoto); personPhotoCall.enqueue(new Callback<PatientPhoto>() { @Override public void onResponse(Call<PatientPhoto> call, Response<PatientPhoto> response) { logger.i(response.message()); if (!response.isSuccessful()) { ToastUtil.error("Patient photo cannot be synced due to server error: "+ response.message()); } } @Override public void onFailure(Call<PatientPhoto> call, Throwable t) { ToastUtil.notify("Patient photo cannot be synced due to error: " + t.toString() ); } }); }
Source:
private boolean hasReviewsIncoming(ITask task) { Set<String> reviewUrls = Collections.emptySet(); for (String reviewUrl : reviewUrls) { AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(reviewUrl); String taskId = connector.getTaskIdFromTaskUrl(reviewUrl); String repositoryUrl = connector.getRepositoryUrlFromTaskUrl(reviewUrl); ITask reviewTask = taskList.getTask(repositoryUrl, taskId); boolean anyIncomingReviews = (reviewTask.getSynchronizationState().isIncoming()); if (anyIncomingReviews) { return true; } } return false; }

Target:
private boolean hasReviewsIncoming(ITask task) { Set<String> reviewUrls = ImmutableSet.copyOf(taskReviewStore.getReviewUrls(task.getUrl())); for (String reviewUrl : reviewUrls) { AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager() .getConnectorForRepositoryTaskUrl(reviewUrl); String taskId = connector.getTaskIdFromTaskUrl(reviewUrl); String repositoryUrl = connector.getRepositoryUrlFromTaskUrl(reviewUrl); ITask reviewTask = taskList.getTask(repositoryUrl, taskId); if ((reviewTask.getSynchronizationState().isIncoming())) { return true; } } return false; }
Source:
private EntityId getMapEntityId(long id) { if (id < (1 << 41)) { if ((id % 2) == 0) { return new EntityId(EntityType.WAY, id >> (BinaryInspector.SHIFT_ID + 1)); } else { return new EntityId(EntityType.NODE, id >> (BinaryInspector.SHIFT_ID + 1)); } } return new EntityId(EntityType.RELATION, id >> (BinaryInspector.SHIFT_ID + 1)); }

Target:
private EntityId getMapEntityId(long id) { if (id < ID_MULTIPOLYGON_LIMIT) { if ((id % 2) == 0) { return new EntityId(EntityType.NODE, id >> (BinaryInspector.SHIFT_ID + 1)); } else { return new EntityId(EntityType.WAY, id >> (BinaryInspector.SHIFT_ID + 1)); } } return null; }
Source:
public void dispose() { if (diagram.eResource() != null) { diagram.eAdapters().remove(this); } diagram = null; session = null; }

Target:
public void dispose() { if (diagram != null && diagram.eResource() != null) { diagram.eAdapters().remove(this); } diagram = null; session = null; }
Source:
private static String normalizeMd5(String data) throws CorrelationAttributeNormalizationException { final String errorMessage = "Data purporting to be an MD5 was found not to comform to expected format: %s"; if(data == null){ throw new CorrelationAttributeNormalizationException(String.format(errorMessage, data)); } final String validMd5Regex = "^[a-fA-F0-9]{32}$"; final String dataLowered = data.toLowerCase(); if(dataLowered.matches(validMd5Regex)){ return dataLowered; } else { throw new CorrelationAttributeNormalizationException(String.format(errorMessage, data)); } }

Target:
private static String normalizeMd5(String data) throws CorrelationAttributeNormalizationException { final String validMd5Regex = "^[a-f0-9]{32}$"; final String dataLowered = data.toLowerCase(); if(dataLowered.matches(validMd5Regex)){ return dataLowered; } else { throw new CorrelationAttributeNormalizationException(String.format("Data purporting to be an MD5 was found not to comform to expected format: %s", data)); } }
Source:
public void testJobFailure() { String errorMsg = "error_msg"; doThrow(new InstallationException(errorMsg)).when(componentInstaller).install(any(), any()); ComponentInstallationJob job = service.install(new DigitalExchange(), "test"); assertThat(job).isNotNull(); try { Thread.sleep(500); } catch (InterruptedException ex) { } assertThat(job.getStatus()).isEqualTo(InstallationStatus.ERROR); assertThat(job.getErrorMessage()).isEqualTo(errorMsg); }

Target:
public void testJobFailure() { String errorMsg = "error_msg"; doThrow(new InstallationException(errorMsg)).when(componentInstaller).install(any(), any()); ComponentInstallationJob job = service.install(new DigitalExchange(), "test"); assertThat(job).isNotNull(); try { Thread.sleep(500); } catch (InterruptedException ignored) { } assertThat(job.getStatus()).isEqualTo(InstallationStatus.ERROR); assertThat(job.getErrorMessage()).isEqualTo(errorMsg); }
Source:
public void initialize() throws ParseException, RuntimeException { return; }

Target:
public void initialize() throws ParseException { return; }
Source:
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { this.bundleContext = bundleContext; String refreshIntervalString = (String) configuration.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } cmiAddress = (String) configuration.get("cmiAddress"); try { clientSocket = new DatagramSocket(cmiPort); } catch (SocketException e) { e.printStackTrace(); } setProperlyConfigured(true); }

Target:
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { this.bundleContext = bundleContext; String refreshIntervalString = (String) configuration.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } try { cmiAddress = InetAddress .getByName((String) configuration.get("cmiAddress")); } catch (UnknownHostException e1) { logger.error("Failed to get IP of CMI from configuration"); setProperlyConfigured(false); return; } try { clientSocket = new DatagramSocket(cmiPort); } catch (SocketException e) { logger.error("Failed to create Socket for receiving UDP packts from CMI"); setProperlyConfigured(true); return; } setProperlyConfigured(true); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Dependency that = (Dependency) o; return getArtifactCoordinates().equals(that.getArtifactCoordinates()); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Dependency that = (Dependency) o; return getArtifactCoordinates().equals(that.getArtifactCoordinates()); }
Source:
private void sendBase(String methodName, TBase<?, ?> args) throws TException { try { Method sendBase = TServiceClient.class.getDeclaredMethod( "sendBase", String.class, TBase.class); sendBase.setAccessible(true); sendBase.invoke(mClient, methodName, args); sendBase.setAccessible(false); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException("Unable to hack sendBase", e); } }

Target:
private void sendBase(String methodName, TBase<?, ?> args) throws TException { try { Method sendBase = TServiceClient.class.getDeclaredMethod( "sendBase", String.class, TBase.class); sendBase.setAccessible(true); sendBase.invoke(mClient, methodName, args); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException("Unable to invoke sendBase", e); } }
Source:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (user.isFlyClickJump()) { user.setRightClickJump(false); user.sendMessage("Flying wizard mode disabled"); } else { user.setRightClickJump(true); user.sendMessage("Enabling flying wizard mode"); } return; } Location loc; final Location cloc = user.getLocation(); try { loc = LocationUtil.getTarget(user.getBase()); loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); } catch (NullPointerException ex) { throw new Exception(tl("jumpError"), ex); } final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); user.getAsyncTeleport().teleport(loc, charge, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel), new CompletableFuture<>()); }

Target:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { if (user.isFlyClickJump()) { user.setRightClickJump(false); user.sendMessage("Flying wizard mode disabled"); } else { user.setRightClickJump(true); user.sendMessage("Enabling flying wizard mode"); } return; } Location loc; final Location cloc = user.getLocation(); try { loc = LocationUtil.getTarget(user.getBase()); loc.setYaw(cloc.getYaw()); loc.setPitch(cloc.getPitch()); loc.setY(loc.getY() + 1); } catch (NullPointerException ex) { throw new Exception(tl("jumpError"), ex); } final Trade charge = new Trade(this.getName(), ess); charge.isAffordableFor(user); user.getAsyncTeleport().teleport(loc, charge, TeleportCause.COMMAND, getNewExceptionFuture(user.getSource(), commandLabel)); }
Source:
public Set<Item> getAllMembers() { return Collections.unmodifiableSet(getMembers((Item i) -> !(i instanceof GroupItem))); }

Target:
public Set<Item> getAllMembers() { return Collections.unmodifiableSet(new LinkedHashSet<Item>(getMembers((Item i) -> !(i instanceof GroupItem)))); }
Source:
private static QueryError toQueryError(QueryInfo queryInfo) { FailureInfo failure = queryInfo.getFailureInfo(); if (failure == null) { QueryState state = queryInfo.getState(); if ((!state.isDone()) || (state == QueryState.FINISHED)) { return null; } log.warn("Query %s in state %s has no failure info", queryInfo.getQueryId(), state); failure = toFailure(new RuntimeException(format("Query is %s (reason unknown)", state))).toFailureInfo(); } ErrorCode errorCode; if (queryInfo.getErrorCode() != null) { errorCode = queryInfo.getErrorCode(); } else { errorCode = GENERIC_INTERNAL_ERROR.toErrorCode(); log.warn("Failed query %s has no error code", queryInfo.getQueryId()); } return new QueryError( failure.getMessage() == null ? "Internal error" : failure.getMessage(), null, errorCode.getCode(), errorCode.getName(), errorCode.getType().toString(), failure.getErrorLocation(), failure); }

Target:
private static QueryError toQueryError(QueryInfo queryInfo) { FailureInfo failure = queryInfo.getFailureInfo(); if (failure == null) { QueryState state = queryInfo.getState(); if ((!state.isDone()) || (state == QueryState.FINISHED)) { return null; } log.warn("Query %s in state %s has no failure info", queryInfo.getQueryId(), state); failure = toFailure(new RuntimeException(format("Query is %s (reason unknown)", state))).toFailureInfo(); } ErrorCode errorCode; if (queryInfo.getErrorCode() != null) { errorCode = queryInfo.getErrorCode(); } else { errorCode = GENERIC_INTERNAL_ERROR.toErrorCode(); log.warn("Failed query %s has no error code", queryInfo.getQueryId()); } return new QueryError( firstNonNull(failure.getMessage(), "Internal error"), null, errorCode.getCode(), errorCode.getName(), errorCode.getType().toString(), failure.getErrorLocation(), failure); }
Source:
private <P, R> void handle(final RetryContextImpl<P, R> retryContext) { final RetryStrategy retryStrategy = getRetryOperation(retryContext).apply(retryContext); if (retryStrategy.getStrategy() == RetryStrategy.Strategy.RESUME) { retryContext.getResult().completeExceptionally(retryStrategy.getError()); } else if (retryStrategy.getStrategy() == RetryStrategy.Strategy.STOP) { final CompletableFuture<R> result = retryContext.getResult(); result.completeExceptionally(retryStrategy.getError()); try { retryContext.getService().close(); } catch (final Exception e) { logger.error("Error occurred while closing service in retry strategy.", e); } } else { final Function<P, CompletionStage<R>> function = retryContext.getFunction(); if (retryStrategy.getStrategy() == RetryStrategy.Strategy.RETRY_IMMEDIATELY) { final Object parameter = retryStrategy.getParameter(); final CompletionStage<R> completionStage = forceApply(function, parameter); handleResultAndEnqueueErrorHandlingAgain(completionStage, parameter, retryContext); } else if (retryStrategy.getStrategy() == RetryStrategy.Strategy.RETRY_SCHEDULED) { final Duration duration = retryStrategy.getDuration(); final Object parameter = retryStrategy.getParameter(); retryContext.schedule(() -> { final CompletionStage<R> completionStage = forceApply(function, parameter); handleResultAndEnqueueErrorHandlingAgain(completionStage, parameter, retryContext); }, duration); } else { throw new IllegalStateException("illegal state for " + retryStrategy); } } }

Target:
private <P, R> void handle(final RetryContextImpl<P, R> retryContext) { final RetryStrategy retryStrategy = applyContext(retryContext); final StrategyType strategyType = retryStrategy.getStrategyType(); if (strategyType == StrategyType.RESUME || strategyType == StrategyType.STOP) { retryContext.getResult().completeExceptionally(retryStrategy.getError()); if (strategyType == StrategyType.STOP) { closeService(retryContext); } } else { final Function<P, CompletionStage<R>> function = retryContext.getFunction(); final Object parameter = retryStrategy.getParameter(); if (strategyType == StrategyType.RETRY_IMMEDIATELY) { retry(retryContext, function, parameter); } else if (strategyType == StrategyType.RETRY_SCHEDULED) { final Duration duration = retryStrategy.getDuration(); retryContext.schedule(() -> retry(retryContext, function, parameter), duration); } else { throw new IllegalStateException("illegal state for " + retryStrategy); } } }
Source:
public AsyncCleanerService(Elide elide, Integer maxRunTimeMinutes, Integer queryCleanupDays, AsyncQueryDAO asyncQueryDao) { int queryRunTimeThresholdMinutes = maxRunTimeMinutes * 2; ScheduledExecutorService cleaner = AsyncCleanerService.getInstance().getExecutorService(); AsyncQueryCleanerThread cleanUpTask = new AsyncQueryCleanerThread(queryRunTimeThresholdMinutes, elide, queryCleanupDays, asyncQueryDao); Random random = new Random(); int initialDelayMinutes = random.ints(0, MAX_CLEANUP_INTIAL_DELAY_MINUTES).limit(1).findFirst().getAsInt(); log.debug("Initial Delay for cleaner service is {}", initialDelayMinutes); cleaner.scheduleWithFixedDelay(cleanUpTask, initialDelayMinutes, Math.max(DEFAULT_CLEANUP_DELAY_MINUTES, queryRunTimeThresholdMinutes), TimeUnit.MINUTES); }

Target:
private AsyncCleanerService(Elide elide, Integer maxRunTimeMinutes, Integer queryCleanupDays, AsyncQueryDAO asyncQueryDao) { int queryRunTimeThresholdMinutes = maxRunTimeMinutes * 2; ScheduledExecutorService cleaner = Executors.newSingleThreadScheduledExecutor(); AsyncQueryCleanerThread cleanUpTask = new AsyncQueryCleanerThread(queryRunTimeThresholdMinutes, elide, queryCleanupDays, asyncQueryDao); Random random = new Random(); int initialDelayMinutes = random.ints(0, maxCleanupInitialDelayMinutes).limit(1).findFirst().getAsInt(); log.debug("Initial Delay for cleaner service is {}", initialDelayMinutes); cleaner.scheduleWithFixedDelay(cleanUpTask, initialDelayMinutes, Math.max(defaultCleanupDelayMinutes, queryRunTimeThresholdMinutes), TimeUnit.MINUTES); }
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { if (data instanceof Hashtable) { Hashtable<?, ?> table = (Hashtable<?, ?>) data; color = (String) table.get("color"); } }

Target:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) { if (data instanceof Hashtable<?, ?>) { Hashtable<?, ?> map = (Hashtable<?, ?>) data; color = (String) map.get("color"); } }
Source:
public void stitch() { for (Todo todo : getTodoList()) { Object entityInstance = todo.getEntityInstance(); String relationshipName = todo.getRelationshipName(); Object foreignKey = todo.getForeignKey(); Class<?> relationshipType = getEntityDictionary().getType(entityInstance, relationshipName); Object relationshipValue = getObjectLookups().get(relationshipType).get(foreignKey); getEntityDictionary().setValue(entityInstance, relationshipName, relationshipValue); } }

Target:
public void stitch() { for (Todo todo : getTodoList()) { Object entityInstance = todo.getEntityInstance(); String relationshipName = todo.getRelationshipName(); Object foreignKey = todo.getForeignKey(); Class<?> relationshipType = getEntityDictionary().getParameterizedType(entityInstance, relationshipName); Object relationshipValue = getObjectLookups().get(relationshipType).get(foreignKey); getEntityDictionary().setValue(entityInstance, relationshipName, relationshipValue); } }
Source:
protected void navigateToAbsoluteUrl(String url, String domain, String login, String password) { if (isIE() && !isLocalFile(url)) { url = makeUniqueUrlToAvoidIECaching(url, System.nanoTime()); if (!domain.isEmpty()) domain += "\\"; } else { if (!domain.isEmpty()) domain += "%5C"; if (!login.isEmpty()) login += ":"; if (!password.isEmpty()) password += "@"; int idx1 = url.indexOf(" url = url.substring(0, idx1 - 2) + " + domain + login + password + url.substring(idx1); } SelenideLog log = SelenideLogger.beginStep("open", url); try { WebDriver webdriver = getAndCheckWebDriver(); webdriver.navigate().to(url); if (isIE()) Selenide.switchTo().alert().authenticateUsing(new UserAndPassword(domain + login, password)); collectJavascriptErrors((JavascriptExecutor) webdriver); SelenideLogger.commitStep(log, PASS); } catch (WebDriverException e) { SelenideLogger.commitStep(log, e); e.addInfo("selenide.url", url); e.addInfo("selenide.baseUrl", baseUrl); throw e; } catch (RuntimeException e) { SelenideLogger.commitStep(log, e); throw e; } catch (Error e) { SelenideLogger.commitStep(log, e); throw e; } }

Target:
protected void navigateToAbsoluteUrl(String url, String domain, String login, String password) { if (isIE() && !isLocalFile(url)) { url = makeUniqueUrlToAvoidIECaching(url, System.nanoTime()); if (!domain.isEmpty()) domain += "\\"; } else { if (!domain.isEmpty()) domain += "%5C"; if (!login.isEmpty()) login += ":"; if (!password.isEmpty()) password += "@"; int idx1 = url.indexOf("://") + 3; url = (idx1 < 3 ? "" : (url.substring(0, idx1 - 3) + "://")) + domain + login + password + (idx1 < 3 ? url : url.substring(idx1)); } SelenideLog log = SelenideLogger.beginStep("open", url); try { WebDriver webdriver = getAndCheckWebDriver(); webdriver.navigate().to(url); if (isIE()) Selenide.switchTo().alert().authenticateUsing(new UserAndPassword(domain + login, password)); collectJavascriptErrors((JavascriptExecutor) webdriver); SelenideLogger.commitStep(log, PASS); } catch (WebDriverException e) { SelenideLogger.commitStep(log, e); e.addInfo("selenide.url", url); e.addInfo("selenide.baseUrl", baseUrl); throw e; } catch (RuntimeException e) { SelenideLogger.commitStep(log, e); throw e; } catch (Error e) { SelenideLogger.commitStep(log, e); throw e; } }
Source:
public void setUp(TestUtils setup, TestReference testReference) throws Exception { setup.loginAsSuperAdmin(); setup.deletePage(testReference); setup.createPageWithAttachment(testReference, "", "Test Attachments", "deletedFile1.txt", new ByteArrayInputStream("attachment content1".getBytes()), TestUtils.SUPER_ADMIN_CREDENTIALS); ViewPage testPage = setup.gotoPage(testReference); AttachmentsPane attachmentsPane = testPage.openAttachmentsDocExtraPane(); attachmentsPane.deleteAttachmentByFileByName("deletedFile1.txt"); }

Target:
void setUp(TestUtils setup, TestReference testReference) throws Exception { setup.loginAsSuperAdmin(); setup.deletePage(testReference); setup.createPageWithAttachment(testReference, "", "Test Attachments", "deletedFile1.txt", new ByteArrayInputStream("attachment content1".getBytes())); ViewPage testPage = setup.gotoPage(testReference); AttachmentsPane attachmentsPane = testPage.openAttachmentsDocExtraPane(); attachmentsPane.deleteAttachmentByFileByName("deletedFile1.txt"); }
Source:
public void testEmptySimpleText_ACK() throws Exception { Path file1 = new Path(source.toString() + "/file_empty.txt"); createTextFile(file1, 0); Path file2 = new Path(source.toString() + "/file.txt"); createTextFile(file2, 5); try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) { HdfsSpout spout = closeableSpout.spout; spout.setCommitFrequencyCount(1); spout.setCommitFrequencySec(1); Map<String, Object> conf = getCommonConfigs(); conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, "1"); openSpout(spout, 0, conf); runSpout(spout, "r6"); Path arc1 = new Path(archive.toString() + "/file_empty.txt"); checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1); runSpout(spout, "r5", "a0", "a1", "a2", "a3", "a4"); Path arc2 = new Path(archive.toString() + "/file.txt"); checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1, arc2); } }

Target:
public void testEmptySimpleText_ACK() throws Exception { Path file1 = new Path(source.toString() + "/file_empty.txt"); createTextFile(file1, 0); Path file2 = new Path(source.toString() + "/file.txt"); createTextFile(file2, 5); try (AutoCloseableHdfsSpout closeableSpout = makeSpout(Configs.TEXT, TextFileReader.defaultFields)) { HdfsSpout spout = closeableSpout.spout; spout.setCommitFrequencyCount(1); Map<String, Object> conf = getCommonConfigs(); conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, "1"); openSpout(spout, 0, conf); runSpout(spout, "r1"); Path arc1 = new Path(archive.toString() + "/file_empty.txt"); checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1); runSpout(spout, "r5", "a0", "a1", "a2", "a3", "a4"); Path arc2 = new Path(archive.toString() + "/file.txt"); checkCollectorOutput_txt((MockCollector) spout.getCollector(), arc1, arc2); } }
Source:
private void raiseAlert( HttpMessage msg, String name, int id, String description, String param, int risk, String evidence, boolean multipleCsp, boolean hasReportUri, String policy) { String alertName = StringUtils.isEmpty(name) ? getName() : getName() + ": " + name; String otherInfo = ""; if (multipleCsp) { otherInfo = Constant.messages.getString(MESSAGE_PREFIX + "otherinfo", policy); } if (hasReportUri) { otherInfo = Constant.messages.getString(MESSAGE_PREFIX + "otherinfo.nomerge"); } newAlert() .setName(alertName) .setRisk(risk) .setConfidence(Alert.CONFIDENCE_MEDIUM) .setDescription(description) .setParam(param) .setOtherInfo(otherInfo) .setSolution(getSolution()) .setReference(getReference()) .setEvidence(evidence) .setCweId(16) .setWascId(15) .raise(); }

Target:
private void raiseAlert( HttpMessage msg, String name, int id, String description, String param, int risk, String evidence, boolean multipleCsp, boolean hasReportUri, String policy) { String alertName = StringUtils.isEmpty(name) ? getName() : getName() + ": " + name; String otherInfo = ""; if (hasReportUri) { otherInfo = Constant.messages.getString(MESSAGE_PREFIX + "otherinfo.nomerge"); } else if (multipleCsp) { otherInfo = Constant.messages.getString(MESSAGE_PREFIX + "otherinfo", policy); } newAlert() .setName(alertName) .setRisk(risk) .setConfidence(Alert.CONFIDENCE_MEDIUM) .setDescription(description) .setParam(param) .setOtherInfo(otherInfo) .setSolution(getSolution()) .setReference(getReference()) .setEvidence(evidence) .setCweId(16) .setWascId(15) .raise(); }
Source:
private static Map<String, String> fromJson(String json) { Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); try { return gson.fromJson(decode(json, UTF_8.name()), JSON_MAP_TYPE); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } }

Target:
private static Map<String, String> fromJson(String json) { Gson gson = new GsonBuilder().create(); try { return gson.fromJson(decode(json, UTF_8.name()), JSON_MAP_TYPE); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } }
Source:
public RealmResults<DynamicRealmObject> linkingObjects(String srcClassName, String srcFieldName) { final DynamicRealm realm = (DynamicRealm) proxyState.getRealm$realm(); realm.checkIfValid(); proxyState.getRow$realm().checkIfAttached(); final RealmSchema schema = realm.getSchema(); final RealmObjectSchema realmObjectSchema = schema.get(srcClassName); if (realmObjectSchema == null) { throw new IllegalArgumentException("Class not found: " + srcClassName); } if (srcFieldName == null) { throw new IllegalArgumentException("Non-null 'srcFieldName' required."); } if (srcFieldName.contains(".")) { throw new IllegalArgumentException(MSG_LINK_QUERY_NOT_SUPPORTED); } final RealmFieldType fieldType = realmObjectSchema.getFieldType(srcFieldName); if (fieldType != RealmFieldType.OBJECT && fieldType != RealmFieldType.LIST) { throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Unexpected field type: %1$s. Field type should be either %2$s.%3$s or %2$s.%4$s.", fieldType.name(), RealmFieldType.class.getSimpleName(), RealmFieldType.OBJECT.name(), RealmFieldType.LIST.name())); } return RealmResults.createDynamicBacklinkResults(realm, proxyState.getRow$realm(), realmObjectSchema.getTable(), srcFieldName); }

Target:
public RealmResults<DynamicRealmObject> linkingObjects(String srcClassName, String srcFieldName) { final DynamicRealm realm = (DynamicRealm) proxyState.getRealm$realm(); realm.checkIfValid(); proxyState.getRow$realm().checkIfAttached(); final RealmSchema schema = realm.getSchema(); final RealmObjectSchema realmObjectSchema = schema.get(srcClassName); if (realmObjectSchema == null) { throw new IllegalArgumentException("Class not found: " + srcClassName); } if (srcFieldName == null) { throw new IllegalArgumentException("Non-null 'srcFieldName' required."); } if (srcFieldName.contains(".")) { throw new IllegalArgumentException(MSG_LINK_QUERY_NOT_SUPPORTED); } final RealmFieldType fieldType = realmObjectSchema.getFieldType(srcFieldName); if (fieldType != RealmFieldType.OBJECT && fieldType != RealmFieldType.LIST) { throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Unexpected field type: %1$s. Field type should be either %2$s.%3$s or %2$s.%4$s.", fieldType.name(), RealmFieldType.class.getSimpleName(), RealmFieldType.OBJECT.name(), RealmFieldType.LIST.name())); } return RealmResults.createDynamicBacklinkResults(realm, (CheckedRow) proxyState.getRow$realm(), realmObjectSchema.getTable(), srcFieldName); }
Source:
public EventHandler<ActiveContext> getFirstContextActiveHandlerForWorker(final boolean addedEval) { return new EventHandler<ActiveContext>() { @Override public void onNext(final ActiveContext activeContext) { LOG.log(Level.INFO, "Worker-side DataLoad context - {0}", activeContext); rootContexts.put(activeContext.getId(), activeContext); final int workerIndex = workerContextIndexCounter.getAndIncrement(); final String contextId = WORKER_CONTEXT_ID + "-" + workerIndex; final Configuration contextConf = Configurations.merge( ContextConfiguration.CONF .set(ContextConfiguration.IDENTIFIER, contextId) .build(), psDriver.getWorkerContextConfiguration(), workerEMWrapper.getConf().getContextConfiguration(), aggregationManager.getContextConfiguration()); final Configuration serviceConf = Configurations.merge( psDriver.getWorkerServiceConfiguration(contextId), getEMServiceConfForWorker(contextId, addedEval), aggregationManager.getServiceConfigurationWithoutNameResolver(), MetricsCollectionService.getServiceConfiguration()); final Configuration traceConf = traceParameters.getConfiguration(); final Configuration otherParamConf = Tang.Factory.getTang().newConfigurationBuilder() .bindNamedParameter(NumWorkerThreads.class, Integer.toString(numWorkerThreads)) .build(); activeContext.submitContextAndService(contextConf, Configurations.merge(serviceConf, traceConf, paramConf, otherParamConf, emWorkerClientConf)); } }; }

Target:
public EventHandler<ActiveContext> getFirstContextActiveHandlerForWorker(final boolean addedEval) { return new EventHandler<ActiveContext>() { @Override public void onNext(final ActiveContext activeContext) { LOG.log(Level.INFO, "Worker-side DataLoad context - {0}", activeContext); contextIdToRootContexts.put(activeContext.getId(), activeContext); final int workerIndex = workerContextIndexCounter.getAndIncrement(); final String contextId = getWorkerContextId(workerIndex); final Configuration contextConf = Configurations.merge( ContextConfiguration.CONF .set(ContextConfiguration.IDENTIFIER, contextId) .build(), psDriver.getWorkerContextConfiguration(), workerEMWrapper.getConf().getContextConfiguration(), aggregationManager.getContextConfiguration()); final Configuration serviceConf = Configurations.merge( psDriver.getWorkerServiceConfiguration(contextId), getEMServiceConfForWorker(contextId, addedEval), aggregationManager.getServiceConfigurationWithoutNameResolver(), MetricsCollectionService.getServiceConfiguration()); final Configuration traceConf = traceParameters.getConfiguration(); final Configuration otherParamConf = Tang.Factory.getTang().newConfigurationBuilder() .bindNamedParameter(NumWorkerThreads.class, Integer.toString(numWorkerThreads)) .build(); activeContext.submitContextAndService(contextConf, Configurations.merge(serviceConf, traceConf, paramConf, otherParamConf, workerConf, emWorkerClientConf)); } }; }
Source:
public void moreMdevs() { vm.setCustomProperties(String.format("key=value;mdev_type=%s;key2=value", MDEV_NAME_1, MDEV_NAME_3)); List<VDS> result = filter(); assertEquals(2, result.size()); assertThat(result.contains(vdsWithMdevs)); assertThat(result.contains(vdsWithMixedMdevs)); }

Target:
public void moreMdevs() { vm.setCustomProperties(String.format("key=value;mdev_type=%s,%s;key2=value", MDEV_NAME_1, MDEV_NAME_3)); List<VDS> result = filter(); assertEquals(2, result.size()); assertThat(result.contains(vdsWithMdevs)); assertThat(result.contains(vdsWithMixedMdevs)); }
Source:
public Page<ModuleMetadata> findAllByModuleId(String moduleId) { try { return new PageImpl<ModuleMetadata>(findAll(moduleId)); } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } }

Target:
public Page<ModuleMetadata> findAllByModuleId(String moduleId) { try { List<ModuleMetadata> results = new ArrayList<ModuleMetadata>(); for (String containerId : getAvailableContainerIds()) { ModuleMetadata metadata = findOne(containerId, moduleId); if (metadata != null) { results.add(metadata); } } return new PageImpl<ModuleMetadata>(results); } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } }
Source:
protected void SyncSearch() { super.SyncSearch(); Frontend.RunQuery(VdcQueryType.GetAllVmsAndVmPools, new VdcQueryParametersBase(), new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object returnValue) { UserPortalListModel userPortalListModel = (UserPortalListModel) model; ArrayList<VM> vms = new ArrayList<VM>(); ArrayList<vm_pools> pools = new ArrayList<vm_pools>(); VdcQueryReturnValue retValue = (VdcQueryReturnValue) returnValue; if (retValue != null && retValue.getSucceeded()) { List<Object> list = (ArrayList<Object>) retValue.getReturnValue(); for (Object object : list) { if (object instanceof VM) { vms.add((VM) object); } else if (object instanceof vm_pools) { pools.add((vm_pools) object); } } } userPortalListModel.setvms(vms); userPortalListModel.setpools(pools); userPortalListModel.OnVmAndPoolLoad(); } })); }

Target:
protected void SyncSearch() { super.SyncSearch(); Frontend.RunQuery(VdcQueryType.GetAllVmsAndVmPools, new VdcQueryParametersBase(), new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object model, Object returnValue) { UserPortalListModel userPortalListModel = (UserPortalListModel) model; ArrayList<VM> vms = new ArrayList<VM>(); ArrayList<vm_pools> pools = new ArrayList<vm_pools>(); VdcQueryReturnValue retValue = (VdcQueryReturnValue) returnValue; if (retValue != null && retValue.getSucceeded()) { List<Object> list = (ArrayList<Object>) retValue.getReturnValue(); if (list != null) { for (Object object : list) { if (object instanceof VM) { vms.add((VM) object); } else if (object instanceof vm_pools) { pools.add((vm_pools) object); } } } } userPortalListModel.setvms(vms); userPortalListModel.setpools(pools); userPortalListModel.OnVmAndPoolLoad(); } })); }
Source:
public static WaypointType convertWaypointSym2Type(final String sym) { if ("parking area".equals(sym)) return WaypointType.PKG; else if ("stages of a multicache".equals(sym)) return WaypointType.STAGE; else if ("question to answer".equals(sym)) return WaypointType.PUZZLE; else if ("trailhead".equals(sym)) return WaypointType.TRAILHEAD; else if ("final location".equals(sym)) return WaypointType.FLAG; else return WaypointType.WAYPOINT; }

Target:
public static WaypointType convertWaypointSym2Type(final String sym) { if ("parking area".equalsIgnoreCase(sym)) { return WaypointType.PKG; } else if ("stages of a multicache".equalsIgnoreCase(sym)) { return WaypointType.STAGE; } else if ("question to answer".equalsIgnoreCase(sym)) { return WaypointType.PUZZLE; } else if ("trailhead".equalsIgnoreCase(sym)) { return WaypointType.TRAILHEAD; } else if ("final location".equalsIgnoreCase(sym)) { return WaypointType.FLAG; } else { return WaypointType.WAYPOINT; } }
Source:
private void initializeViews() { mProjectLayout = (LinearLayout) findViewById(R.id.project_list_layout); mNewProjectButton = (Button) findViewById(R.id.new_project_button); mAddProject = (ImageView) findViewById(R.id.new_project_fab); mProjectList = (ListView) findViewById(R.id.project_list); mAddProject.setOnClickListener(btnClick); mNewProjectButton.setOnClickListener(btnClick); hideProjectsIfEmpty(mNumProjects); if (mNumProjects > 0) { calculateProjectsProgress(); Project recent = initializeRecentProject(); populateProjectList(recent); } }

Target:
private void initializeViews() { mProjectLayout = (LinearLayout) findViewById(R.id.project_list_layout); mNewProjectButton = (Button) findViewById(R.id.new_project_button); mAddProject = (ImageView) findViewById(R.id.new_project_fab); mProjectList = (ListView) findViewById(R.id.project_list); mAddProject.setOnClickListener(btnClick); mNewProjectButton.setOnClickListener(btnClick); hideProjectsIfEmpty(mNumProjects); if (mNumProjects > 0) { Project recent = initializeRecentProject(); populateProjectList(recent); } }
Source:
public void testGenerateFilesinPuppetMaster() throws InstallatorException, NodeExecutionException, KeyManagementException, NoSuchAlgorithmException, IOException { when(statusLine.getStatusCode()).thenReturn(200); when(httpsClient.doHttpsPost(Mockito.anyString(), Mockito.anyString(),(Map<String,String>)Mockito.anyObject())).thenReturn(200); when(httpsClient.doHttpsGet(Mockito.anyString(), Mockito.anyString(),(Map<String,String>)Mockito.anyObject())).thenReturn(200); puppetInstallator.generateFilesinPuppetMaster(host, "test", productRelease, "install", "token"); }

Target:
public void testGenerateFilesinPuppetMaster() throws InstallatorException, NodeExecutionException, KeyManagementException, NoSuchAlgorithmException, IOException { when(statusLine.getStatusCode()).thenReturn(200); when( httpsClient.doHttps(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), (Map<String, String>) Mockito.anyObject())).thenReturn(200); puppetInstallator.generateFilesinPuppetMaster(host, "test", productRelease, "install", "token"); }
Source:
private static void writeConvertTable(Repository repo, ReftableWriter w, boolean writeLogs) throws IOException { int size = 0; List<Ref> refs = repo.getRefDatabase().getRefs(); if (writeLogs) { for (Ref r : refs) { ReflogReader rlr = repo.getReflogReader(r.getName()); size = Math.max( rlr == null ? 0 : rlr.getReverseEntries().size(), size); } } w.setMinUpdateIndex(1).setMaxUpdateIndex(size + 1).begin(); try (RevWalk rw = new RevWalk(repo)) { List<Ref> toWrite = new ArrayList<>(refs.size()); for (Ref r : refs) { toWrite.add(refForWrite(rw, r)); } w.sortAndWriteRefs(toWrite); } if (writeLogs) { for (Ref r : refs) { long idx = size; ReflogReader reader = repo.getReflogReader(r.getName()); if (reader == null) { continue; } for (ReflogEntry e : reader.getReverseEntries()) { w.writeLog(r.getName(), idx, e.getWho(), e.getOldId(), e.getNewId(), e.getComment()); idx--; } } } }

Target:
private static void writeConvertTable(Repository repo, ReftableWriter w, boolean writeLogs) throws IOException { int size = 0; List<Ref> refs = repo.getRefDatabase().getRefs(); if (writeLogs) { for (Ref r : refs) { ReflogReader rlr = repo.getReflogReader(r.getName()); if (rlr != null) { size = Math.max(rlr.getReverseEntries().size(), size); } } } w.setMinUpdateIndex(1).setMaxUpdateIndex(size + 1).begin(); try (RevWalk rw = new RevWalk(repo)) { List<Ref> toWrite = new ArrayList<>(refs.size()); for (Ref r : refs) { toWrite.add(refForWrite(rw, r)); } w.sortAndWriteRefs(toWrite); } if (writeLogs) { for (Ref r : refs) { long idx = size; ReflogReader reader = repo.getReflogReader(r.getName()); if (reader == null) { continue; } for (ReflogEntry e : reader.getReverseEntries()) { w.writeLog(r.getName(), idx, e.getWho(), e.getOldId(), e.getNewId(), e.getComment()); idx--; } } } }
Source:
public synchronized void writeIssues(Iterator<Issue> issues, File file) { while (issues.hasNext()) { Issue issue = issues.next(); IssueEntry entry = IssueEntry.from(issue, file); if (expectedIssues.expects(entry)) { continue; } output.accept(entry.createExcerpt()); } }

Target:
public synchronized void writeIssues(Iterator<Issue> issues, File file) { while (issues.hasNext()) { Issue issue = issues.next(); IssueEntry entry = IssueEntry.from(issue, file); if (!expectedIssues.expects(entry)) { output.accept(entry.createExcerpt()); } } }
Source:
public CoapClient useExecutor() { boolean failed = true; ExecutorService executor = ExecutorsUtil.newFixedThreadPool(1, new NamedThreadFactory("CoapClient(main)#")); ScheduledThreadPoolExecutor secondaryExecutor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("CoapClient(secondary)#")); synchronized (this) { if (this.executor == null && this.secondaryExecutor == null) { this.executor = executor; this.secondaryExecutor = secondaryExecutor; this.detachExecutor = false; failed = false; } } if (failed) { executor.shutdownNow(); throw new IllegalStateException("Executor already set or used!"); } executor.execute(new Runnable() { public void run() { LOGGER.info("using a SingleThreadExecutor for the CoapClient"); }; }); return this; }

Target:
public CoapClient useExecutor() { boolean failed = true; ExecutorService executor = ExecutorsUtil.newFixedThreadPool(1, new NamedThreadFactory("CoapClient(main)#")); ScheduledThreadPoolExecutor secondaryExecutor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("CoapClient(secondary)#")); synchronized (this) { if (this.executor == null && this.secondaryExecutor == null) { this.executor = executor; this.secondaryExecutor = secondaryExecutor; this.detachExecutor = false; failed = false; } } if (failed) { executor.shutdownNow(); secondaryExecutor.shutdown(); throw new IllegalStateException("Executor already set or used!"); } executor.execute(new Runnable() { public void run() { LOGGER.info("using a SingleThreadExecutor for the CoapClient"); }; }); return this; }
Source:
public void notifyLeaderAddress(LeaderInformation leaderInformation) { final UUID newLeaderSessionID = leaderInformation.getLeaderSessionID(); final String newLeaderAddress = leaderInformation.getLeaderAddress(); synchronized (lock) { if (running) { if (!Objects.equals(newLeaderAddress, lastLeaderAddress) || !Objects.equals(newLeaderSessionID, lastLeaderSessionID)) { if (LOG.isDebugEnabled()) { if (newLeaderAddress == null && newLeaderSessionID == null) { LOG.debug("Leader information was lost: The listener will be notified accordingly."); } else { LOG.debug( "New leader information: Leader={}, session ID={}.", newLeaderAddress, newLeaderSessionID); } } lastLeaderAddress = newLeaderAddress; lastLeaderSessionID = newLeaderSessionID; leaderListener.notifyLeaderAddress(newLeaderAddress, newLeaderSessionID); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring notification since the has already been closed.", leaderRetrievalDriver); } } } }

Target:
public void notifyLeaderAddress(LeaderInformation leaderInformation) { final UUID newLeaderSessionID = leaderInformation.getLeaderSessionID(); final String newLeaderAddress = leaderInformation.getLeaderAddress(); synchronized (lock) { if (running) { if (!Objects.equals(newLeaderAddress, lastLeaderAddress) || !Objects.equals(newLeaderSessionID, lastLeaderSessionID)) { if (LOG.isDebugEnabled()) { if (newLeaderAddress == null && newLeaderSessionID == null) { LOG.debug("Leader information was lost: The listener will be notified accordingly."); } else { LOG.debug( "New leader information: Leader={}, session ID={}.", newLeaderAddress, newLeaderSessionID); } } lastLeaderAddress = newLeaderAddress; lastLeaderSessionID = newLeaderSessionID; } } else { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring notification since the has already been closed.", leaderRetrievalDriver); } } } leaderListener.notifyLeaderAddress(newLeaderAddress, newLeaderSessionID); }
Source:
public void addPartitions(String databaseName, String tableName, List<Partition> partitions) { try { List<List<Partition>> batchedPartitions = Lists.partition(partitions, BATCH_CREATE_PARTITION_MAX_PAGE_SIZE); List<Future<BatchCreatePartitionResult>> futures = new ArrayList<>(); for (List<Partition> partitionBatch : batchedPartitions) { List<PartitionInput> partitionInputs = partitionBatch.stream().map(GlueInputConverter::convertPartition).collect(toList()); futures.add(glueClient.batchCreatePartitionAsync(new BatchCreatePartitionRequest() .withDatabaseName(databaseName) .withTableName(tableName) .withPartitionInputList(partitionInputs))); } for (Future<BatchCreatePartitionResult> future : futures) { BatchCreatePartitionResult result = future.get(); propagatePartitionErrorToPrestoException(databaseName, tableName, result.getErrors()); } } catch (AmazonServiceException | InterruptedException | ExecutionException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }

Target:
public void addPartitions(String databaseName, String tableName, List<Partition> partitions) { try { List<List<Partition>> batchedPartitions = Lists.partition(partitions, BATCH_CREATE_PARTITION_MAX_PAGE_SIZE); List<Future<BatchCreatePartitionResult>> futures = new ArrayList<>(); for (List<Partition> partitionBatch : batchedPartitions) { List<PartitionInput> partitionInputs = partitionBatch.stream().map(GlueInputConverter::convertPartition).collect(toList()); futures.add(glueClient.batchCreatePartitionAsync(new BatchCreatePartitionRequest() .withDatabaseName(databaseName) .withTableName(tableName) .withPartitionInputList(partitionInputs))); } for (Future<BatchCreatePartitionResult> future : futures) { BatchCreatePartitionResult result = future.get(); propagatePartitionErrorToPrestoException(databaseName, tableName, result.getErrors()); } } catch (AmazonServiceException | InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw new PrestoException(HIVE_METASTORE_ERROR, e); } }
Source:
public Response doImport(Action action) { validateParameters(action, "cluster.id|name", "storageDomain.id|name"); Guid destStorageDomainId = getDestStorageDomainId(action); ImportVmTemplateParameters params = new ImportVmTemplateParameters(parent.getDataCenterId(destStorageDomainId), parent.getStorageDomainId(), destStorageDomainId, getClusterId(action), getEntity()); params.setImageToDestinationDomainMap(getDiskToDestinationMap(action)); params.setForceOverride(action.isSetExclusive() ? action.isExclusive() : false); if (action.isSetClone()){ params.setImportAsNewEntity(action.isClone()); if(action.isSetTemplate() && action.getTemplate().isSetName()) { params.getVmTemplate().setName(action.getTemplate().getName()); } } return doAction(VdcActionType.ImportVmTemplate, params, action); }

Target:
public Response doImport(Action action) { validateParameters(action, "cluster.id|name"); Guid destStorageDomainId = getDestStorageDomainId(action); ImportVmTemplateParameters params = new ImportVmTemplateParameters(parent.getDataCenterId(destStorageDomainId), parent.getStorageDomainId(), destStorageDomainId, getClusterId(action), getEntity()); params.setImageToDestinationDomainMap(getDiskToDestinationMap(action)); params.setForceOverride(action.isSetExclusive() ? action.isExclusive() : false); if (action.isSetClone()){ params.setImportAsNewEntity(action.isClone()); if(action.isSetTemplate() && action.getTemplate().isSetName()) { params.getVmTemplate().setName(action.getTemplate().getName()); } } return doAction(VdcActionType.ImportVmTemplate, params, action); }
Source:
public void testRDotTxtEntryCompareTo() { ImmutableList<RDotTxtEntry> entries = ImmutableList.of( new RDotTxtEntry(IdType.INT_ARRAY, RType.STYLEABLE, "ActionBar", null), new RDotTxtEntry(IdType.INT_ARRAY, RType.STYLEABLE, "ActionBarLayout", "0x7f060008"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_background", "2"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_contentInsetEnd", "0"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBarLayout_android", "0"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_backgroundStack", "1") ); ImmutableList<RDotTxtEntry> sortedEntries = ImmutableList.copyOf( Ordering.natural().sortedCopy(entries) ); assertEquals( sortedEntries, ImmutableList.of( new RDotTxtEntry(IdType.INT_ARRAY, RType.STYLEABLE, "ActionBar", null), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_background", "2"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_backgroundStack", "1"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_contentInsetEnd", "0"), new RDotTxtEntry(IdType.INT_ARRAY, RType.STYLEABLE, "ActionBarLayout", "0x7f060008"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBarLayout_android", "0") ) ); }

Target:
public void testRDotTxtEntryCompareTo() { ImmutableList<RDotTxtEntry> entries = ImmutableList.of( new RDotTxtEntry(IdType.INT_ARRAY, RType.STYLEABLE, "ActionBar", null), new RDotTxtEntry(IdType.INT_ARRAY, RType.STYLEABLE, "ActionBarLayout", "0x7f060008"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_background", "2"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_contentInsetEnd", "0"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBarLayout_android", "0"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_backgroundStack", "1") ); ImmutableList<RDotTxtEntry> sortedEntries = ImmutableList.copyOf( Ordering.natural().sortedCopy(entries) ); assertEquals( ImmutableList.of( new RDotTxtEntry(IdType.INT_ARRAY, RType.STYLEABLE, "ActionBar", null), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_background", "2"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_backgroundStack", "1"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBar_contentInsetEnd", "0"), new RDotTxtEntry(IdType.INT_ARRAY, RType.STYLEABLE, "ActionBarLayout", "0x7f060008"), new RDotTxtEntry(IdType.INT, RType.STYLEABLE, "ActionBarLayout_android", "0") ), sortedEntries ); }