auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testBuilderWithPositionalParameters() { final ParsedSql parsedSql = ParsedSql.builder() .append("insert into test (a, b, c) values (") .appendPositionalParameter() .append(", ") .appendPositionalParameter() .append(", ") .appendPositionalParameter() .append(")") .build(); assertThat(parsedSql).isNotNull(); assertThat(parsedSql.getSql()).isEqualTo("insert into test (a, b, c) values (?, ?, ?)"); assertThat(parsedSql.getParameters().isPositional()).isTrue(); assertThat(parsedSql.getParameters().getParameterNames()).contains("?", "?", "?"); }

Target:
public void testBuilderWithPositionalParameters() { final ParsedSql parsedSql = ParsedSql.builder() .append("insert into test (a, b, c) values (") .appendPositionalParameter() .append(", ") .appendPositionalParameter() .append(", ") .appendPositionalParameter() .append(")") .build(); assertThat(parsedSql).isNotNull(); assertThat(parsedSql.getSql()).isEqualTo("insert into test (a, b, c) values (?, ?, ?)"); assertThat(parsedSql.getParameters().isPositional()).isTrue(); assertThat(parsedSql.getParameters().getParameterNames()).containsOnly("?"); }
Source:
public SpliceCatalogUpgradeScripts(SpliceDataDictionary sdd,Splice_DD_Version catalogVersion,TransactionController tc){ this.sdd=sdd; this.catalogVersion=catalogVersion; this.tc=tc; ddComparator=new Comparator<Splice_DD_Version>(){ @Override public int compare(Splice_DD_Version version1,Splice_DD_Version version2){ long v1=version1.toLong(); long v2=version2.toLong(); if(v1<v2) return -1; else if(v1==v2) return 0; else return 1; } }; scripts=new TreeMap<>(ddComparator); scripts.put(new Splice_DD_Version(sdd,1,0,0),new UpgradeScriptForFuji(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,1,1,1),new LassenUpgradeScript(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,2,6,0, 9999),new UpgradeScriptFor260(sdd,tc)); }

Target:
public SpliceCatalogUpgradeScripts(SpliceDataDictionary sdd,Splice_DD_Version catalogVersion,TransactionController tc){ this.sdd=sdd; this.catalogVersion=catalogVersion; this.tc=tc; ddComparator=new Comparator<Splice_DD_Version>(){ @Override public int compare(Splice_DD_Version version1,Splice_DD_Version version2){ long v1=version1.toLong(); long v2=version2.toLong(); if(v1<v2) return -1; else if(v1==v2) return 0; else return 1; } }; scripts=new TreeMap<>(ddComparator); scripts.put(new Splice_DD_Version(sdd,1,0,0),new UpgradeScriptForFuji(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,1,1,1),new LassenUpgradeScript(sdd,tc)); scripts.put(new Splice_DD_Version(sdd,2,6,0),new UpgradeScriptFor260(sdd,tc)); }
Source:
public static Boolean updateHistoryForProcess(Process inProc) { Boolean updated; try { updated = updateHistory(inProc); updated = updateHistoryForSteps(inProc); } catch (Exception ex) { logger.warn("Updating history failed.", ex); logger.error(ex.getStackTrace()); updated = false; } return updated; }

Target:
public static Boolean updateHistoryForProcess(Process inProc) { Boolean updated; try { updated = updateHistory(inProc); updated = updateHistoryForSteps(inProc); } catch (Exception ex) { logger.warn("Updating history failed.", ex); updated = false; } return updated; }
Source:
protected void onFinishInflate() { mLockPatternUtils = new LockPatternUtils(mContext); mSecurityMessageDisplay = (KeyguardMessageArea) KeyguardMessageArea.findSecurityMessageDisplay(this); mEcaView = findViewById(R.id.keyguard_selector_fade_container); EmergencyButton button = (EmergencyButton) findViewById(R.id.emergency_call_button); if (button != null) { button.setCallback(this); } }

Target:
protected void onFinishInflate() { mLockPatternUtils = new LockPatternUtils(mContext); mSecurityMessageDisplay = KeyguardMessageArea.findSecurityMessageDisplay(this); mEcaView = findViewById(R.id.keyguard_selector_fade_container); EmergencyButton button = (EmergencyButton) findViewById(R.id.emergency_call_button); if (button != null) { button.setCallback(this); } }
Source:
public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { throw new ServletException("Only HTTP requests are supported"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String userIdParam = httpRequest.getParameter(AuthorizationConstants.USER_ID_PARAM); if (userIdParam==null) { HttpAuthUtil.reject(httpResponse, "Missing user id.", HttpStatus.INTERNAL_SERVER_ERROR); return; } Long userId = Long.parseLong(userIdParam); if (!BOOTSTRAP_PRINCIPAL.ANONYMOUS_USER.getPrincipalId().equals(userId)) { if (!authenticationService.hasUserAcceptedTermsOfUse(userId)) { HttpAuthUtil.reject(httpResponse, TOU_UNSIGNED_REASON, HttpStatus.FORBIDDEN); return; } } filterChain.doFilter(httpRequest, httpResponse); }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { throw new ServletException("Only HTTP requests are supported"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String userIdParam = httpRequest.getParameter(AuthorizationConstants.USER_ID_PARAM); if (userIdParam==null) { HttpAuthUtil.reject(httpResponse, "Missing user id.", HttpStatus.INTERNAL_SERVER_ERROR); return; } Long userId = Long.parseLong(userIdParam); if (!BOOTSTRAP_PRINCIPAL.ANONYMOUS_USER.getPrincipalId().equals(userId)) { if (!authenticationService.hasUserAcceptedTermsOfUse(userId)) { HttpAuthUtil.reject(httpResponse, TOU_UNSIGNED_REASON, HttpStatus.FORBIDDEN); return; } } filterChain.doFilter(httpRequest, httpResponse); }
Source:
public Attribute getAttributeValue(PerunSessionImpl perunSession, User user, AttributeDefinition attributeDefinition) throws InternalErrorException { Map<String, String> userOrganizations = new LinkedHashMap<>(); List<Vo> vos = perunSession.getPerunBl().getUsersManagerBl().getVosWhereUserIsMember(perunSession, user); for (Vo vo : vos) { try { Member member = perunSession.getPerunBl().getMembersManagerBl().getMemberByUser(perunSession, vo, user); String value = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, member, A_M_organization).valueAsString(); userOrganizations.put(vo.getShortName(), value); } catch (MemberNotExistsException e) { throw new ConsistencyErrorException(e); } catch (WrongAttributeAssignmentException | AttributeNotExistsException e) { throw new InternalErrorException(e); } } Attribute attribute = new Attribute(attributeDefinition); attribute.setValue(userOrganizations); return attribute; }

Target:
public Attribute getAttributeValue(PerunSessionImpl perunSession, User user, AttributeDefinition attributeDefinition) throws InternalErrorException { Map<String, String> userOrganizations = new LinkedHashMap<>(); List<Vo> vos = perunSession.getPerunBl().getUsersManagerBl().getVosWhereUserIsMember(perunSession, user); for (Vo vo : vos) { try { Member member = perunSession.getPerunBl().getMembersManagerBl().getMemberByUser(perunSession, vo, user); String value = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, member, A_M_organization).valueAsString(); if (value != null) userOrganizations.put(vo.getShortName(), value); } catch (MemberNotExistsException e) { throw new ConsistencyErrorException(e); } catch (WrongAttributeAssignmentException | AttributeNotExistsException e) { throw new InternalErrorException(e); } } Attribute attribute = new Attribute(attributeDefinition); attribute.setValue(userOrganizations); return attribute; }
Source:
public void startCommandByDoubleClick(String commandName) { String locatorToCurrentCommand = String.format(Locators.COMMANDS, commandName); WebElement currentCommand = redrawUiElementTimeout.until( ExpectedConditions.visibilityOfElementLocated(By.xpath(locatorToCurrentCommand))); actions.doubleClick(currentCommand).perform(); redrawUiElementTimeout.until( ExpectedConditions.invisibilityOfElementLocated(By.xpath(locatorToCurrentCommand))); }

Target:
public void startCommandByDoubleClick(String commandName) { String locatorToCurrentCommand = format(Locators.COMMANDS, commandName); WebElement currentCommand = redrawUiElementTimeout.until( ExpectedConditions.visibilityOfElementLocated(By.xpath(locatorToCurrentCommand))); actions.doubleClick(currentCommand).perform(); redrawUiElementTimeout.until( ExpectedConditions.invisibilityOfElementLocated(By.xpath(locatorToCurrentCommand))); }
Source:
public void should_return_endpoints_without_context_path() { contextRunner.withConfiguration(UserConfigurations.of(EndpointConfig.class)) .withPropertyValues("management.endpoint.health.enabled=true", "management.endpoint.info.enabled=true", "management.endpoints.web.exposure.include=info,health") .run(context -> { SkipPatternProvider skipPatternProvider = context .getBean(SkipPatternProvider.class); Pattern pattern = skipPatternProvider.skipPattern(); then(pattern.pattern()) .contains("/actuator/(health|health/.*|info|info/.*)"); }); }

Target:
public void should_return_endpoints_without_context_path() { contextRunner.withConfiguration(UserConfigurations.of(ServerPropertiesConfig.class)) .run(context -> { then(extractAllPatterns(context)).containsExactlyInAnyOrder( "/actuator/(health|health/.*|info|info/.*)", SleuthWebProperties.DEFAULT_SKIP_PATTERN); }); }
Source:
public static StreamStoreCleanupMetadata hydrateFromProto( SchemaMetadataPersistence.StreamStoreCleanupMetadata streamStoreCleanupMetadata) { ImmutableStreamStoreCleanupMetadata.Builder builder = ImmutableStreamStoreCleanupMetadata.builder(); if (streamStoreCleanupMetadata.hasV1Metadata()) { StreamStoreCleanupV1Metadata v1Metadata = streamStoreCleanupMetadata.getV1Metadata(); if (v1Metadata.hasNumHashedRowComponents()) { builder.numHashedRowComponents(v1Metadata.getNumHashedRowComponents()); } if (v1Metadata.hasStreamIdType()) { builder.streamIdType(ValueType.hydrateFromProto(v1Metadata.getStreamIdType())); } } else { log.warn("Encountered stream store cleanup metadata without v1 metadata, which is unexpected."); } return builder.build(); }

Target:
public static StreamStoreCleanupMetadata hydrateFromProto( SchemaMetadataPersistence.StreamStoreCleanupMetadata streamStoreCleanupMetadata) { ImmutableStreamStoreCleanupMetadata.Builder builder = ImmutableStreamStoreCleanupMetadata.builder(); if (streamStoreCleanupMetadata.hasV1Metadata()) { StreamStoreCleanupV1Metadata v1Metadata = streamStoreCleanupMetadata.getV1Metadata(); if (v1Metadata.hasNumHashedRowComponents()) { builder.numHashedRowComponents(v1Metadata.getNumHashedRowComponents()); } if (v1Metadata.hasStreamIdType()) { builder.streamIdType(ValueType.hydrateFromProto(v1Metadata.getStreamIdType())); } } else { final String v1MetadataNotFound = "Encountered stream store cleanup metadata without v1 metadata," + " which is unexpected."; log.warn(v1MetadataNotFound); throw new IllegalStateException(v1MetadataNotFound); } return builder.build(); }
Source:
public <T, E extends Exception> T transaction(TransactionActionWithException<T, D, E> action, Class<E> exClass) throws E { try { return transactionRetryExecutor.runInterruptible(() -> { try (Handle handle = dbi.open()) { handle.begin(); T retval; try { retval = action.call(handle, handle.attach(daoIface)); } catch (Exception ex) { try { handle.rollback(); } catch (Exception rollback) { ex.addSuppressed(rollback); } Throwables.propagateIfInstanceOf(ex, exClass); Throwables.propagateIfPossible(ex); throw new TransactionFailedException( "Transaction failed do to exception being thrown " + "from within the callback. See cause " + "for the original exception.", ex); } validateTransactionAndCommit(handle); return retval; } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); Throwables.propagateIfInstanceOf(innerException, exClass); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { throw Throwables.propagate(ex); } }

Target:
public <T, E extends Exception> T transaction(TransactionActionWithException<T, D, E> action, Class<E> exClass) throws E { try { return transactionRetryExecutor.runInterruptible(() -> { try (Handle handle = dbi.open()) { handle.begin(); T retval; try { retval = action.call(handle, handle.attach(daoIface)); } catch (Exception ex) { try { handle.rollback(); } catch (Exception rollback) { ex.addSuppressed(rollback); } Throwables.propagateIfInstanceOf(ex, exClass); Throwables.propagateIfPossible(ex); throw new TransactionFailedException( "Transaction failed due to exception being thrown " + "from within the callback. See cause " + "for the original exception.", ex); } validateTransactionAndCommit(handle); return retval; } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); Throwables.propagateIfInstanceOf(innerException, exClass); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { throw Throwables.propagate(ex); } }
Source:
private void _put(String tableName, String rowKeyStr) { _logger.trace(MessageFormat.format("Inserting rowkey {0} into table {1}", rowKeyStr, tableName)); final PutRequest put = new PutRequest(Bytes.toBytes(tableName), Bytes.toBytes(rowKeyStr), COLUMN_FAMILY, COLUMN_QUALIFIER, CELL_VALUE); Deferred<Object> deferred = _client.put(put); if(syncPut) { deferred.addCallback(new Callback<Object, Object>() { @Override public Object call(Object arg) throws Exception { _logger.trace(MessageFormat.format("Put to {0} successfully.", tableName)); return null; } }); } deferred.addErrback(new Callback<Object, Exception>() { @Override public Object call(Exception e) throws Exception { throw new SystemException("Error occured while trying to execute put().", e); } }); }

Target:
private void _put(String tableName, String rowKeyStr) { _logger.trace(MessageFormat.format("Inserting rowkey {0} into table {1}", rowKeyStr, tableName)); final PutRequest put = new PutRequest(Bytes.toBytes(tableName), Bytes.toBytes(rowKeyStr), COLUMN_FAMILY, COLUMN_QUALIFIER, CELL_VALUE); Deferred<Object> deferred = _client.put(put); if(_syncPut) { deferred.addCallback(new Callback<Object, Object>() { @Override public Object call(Object arg) throws Exception { _logger.trace(MessageFormat.format("Put to {0} successfully.", tableName)); return null; } }); } deferred.addErrback(new Callback<Object, Exception>() { @Override public Object call(Exception e) throws Exception { throw new SystemException("Error occured while trying to execute put().", e); } }); }
Source:
int commitAll() { if (rebalanceInProgress) { return -1; } final int committed = active.commit(); return committed + standby.commit(); }

Target:
int commitAll() { return rebalanceInProgress ? -1 : active.commit() + standby.commit(); }
Source:
private static boolean uniqueSchemaOnAllNodesAllowingForOneUnreachable( Map<String, List<String>> versions) { return getDistinctReachableSchemas(versions).size() <= 1 && (!versions.keySet().contains(VERSION_UNREACHABLE) || versions.get(VERSION_UNREACHABLE).size() == 1); }

Target:
private static boolean uniqueSchemaOnAllNodesAllowingForOneUnreachable( Map<String, List<String>> versions) { return getDistinctReachableSchemas(versions).size() == 1 && (versions.getOrDefault(VERSION_UNREACHABLE, ImmutableList.of()).size() <= 1); }
Source:
private ResettableRandomizedIterator<InternalNode> getRandomCandidates(int limit, NodeMap nodeMap, List<RemoteTask> existingTasks) { Set<InternalNode> existingNodes = existingTasks.stream().map(remoteTask -> nodeMap.getNodesByNodeId().get(remoteTask.getNodeId())).collect(toSet()); int alreadySelectedNodeCount = existingNodes.size(); int nodeCount = nodeMap.getNodesByNodeId().size(); if (alreadySelectedNodeCount < limit && alreadySelectedNodeCount < nodeCount) { List<InternalNode> moreNodes = selectNodes(limit - alreadySelectedNodeCount, randomizedNodes(nodeMap, includeCoordinator, existingNodes)); existingNodes.addAll(moreNodes); } return new ResettableRandomizedIterator<>(existingNodes); }

Target:
private ResettableRandomizedIterator<InternalNode> getRandomCandidates(int limit, NodeMap nodeMap, List<RemoteTask> existingTasks) { List<InternalNode> existingNodes = existingTasks.stream() .map(remoteTask -> nodeMap.getNodesByNodeId().get(remoteTask.getNodeId())) .collect(toList()); int alreadySelectedNodeCount = existingTasks.size(); int nodeCount = nodeMap.getNodesByNodeId().size(); if (alreadySelectedNodeCount < limit && alreadySelectedNodeCount < nodeCount) { List<InternalNode> moreNodes = selectNodes(limit - alreadySelectedNodeCount, randomizedNodes(nodeMap, includeCoordinator, newHashSet(existingNodes))); existingNodes.addAll(moreNodes); } return new ResettableRandomizedIterator<>(existingNodes); }
Source:
public void onCustomizedStateRootChange(String instanceName, List<String> customizedStateTypes, NotificationContext changeContext) { logger.info("START: GenericClusterController.onCustomizedStateRootChange()"); HelixManager manager = changeContext.getManager(); Builder keyBuilder = new Builder(manager.getClusterName()); synchronized (_lastSeenCustomizedStateTypes) { Set<String> lastSeenCustomizedStateTypes = _lastSeenCustomizedStateTypes.get(); for (String customizedState : customizedStateTypes) { try { if (lastSeenCustomizedStateTypes == null || !lastSeenCustomizedStateTypes .contains(customizedState)) { manager.addCustomizedStateChangeListener(this, instanceName, customizedState); logger.info( manager.getInstanceName() + " added customized state listener for " + instanceName + ", listener: " + this); } } catch (Exception e) { logger.error("Fail to add customized state listener for instance: " + instanceName, e); } } for (String previousCustomizedState : lastSeenCustomizedStateTypes) { if (!customizedStateTypes.contains(previousCustomizedState)) { manager.removeListener(keyBuilder.customizedStates(instanceName, previousCustomizedState), this); } } _lastSeenCustomizedStateTypes.set(new HashSet<>(customizedStateTypes)); } }

Target:
public void onCustomizedStateRootChange(String instanceName, List<String> customizedStateTypes, NotificationContext changeContext) { logger.info("START: GenericClusterController.onCustomizedStateRootChange()"); HelixManager manager = changeContext.getManager(); Builder keyBuilder = new Builder(manager.getClusterName()); if (customizedStateTypes.isEmpty()) { customizedStateTypes = manager.getHelixDataAccessor() .getChildNames(keyBuilder.customizedStatesRoot(instanceName)); } synchronized (_lastSeenCustomizedStateTypes) { Set<String> lastSeenCustomizedStateTypes = _lastSeenCustomizedStateTypes.get(); for (String customizedState : customizedStateTypes) { try { if (lastSeenCustomizedStateTypes == null || !lastSeenCustomizedStateTypes .contains(customizedState)) { manager.addCustomizedStateChangeListener(this, instanceName, customizedState); logger.info( manager.getInstanceName() + " added customized state listener for " + instanceName + ", listener: " + this); } } catch (Exception e) { logger.error("Fail to add customized state listener for instance: " + instanceName, e); } } for (String previousCustomizedState : lastSeenCustomizedStateTypes) { if (!customizedStateTypes.contains(previousCustomizedState)) { manager.removeListener(keyBuilder.customizedStates(instanceName, previousCustomizedState), this); } } _lastSeenCustomizedStateTypes.set(new HashSet<>(customizedStateTypes)); } }
Source:
protected void executeCommand() { initConnectionList(true); for (Map.Entry<StorageType, List<StorageServerConnections>> connectionToType : getConnectionsTypeMap().entrySet()) { disconnectStorageByType(connectionToType.getKey(), connectionToType.getValue()); } if (FeatureSupported.cinderProviderSupported(getStoragePool().getCompatibilityVersion())) { unregisterLibvirtSecrets(); } }

Target:
protected void executeCommand() { initConnectionList(true); for (Map.Entry<StorageType, List<StorageServerConnections>> connectionToType : getConnectionsTypeMap().entrySet()) { disconnectStorageByType(connectionToType.getKey(), connectionToType.getValue()); } unregisterLibvirtSecrets(); }
Source:
public void testSetReadOnly() { boolean arbitraryValue = false; view.setReadOnly(arbitraryValue); verify(slaTimeDuration).setDisabled(arbitraryValue); }

Target:
public void testSetReadOnly() { final boolean arbitraryValue = false; view.setReadOnly(arbitraryValue); verify(slaTimeDuration).setDisabled(arbitraryValue); }
Source:
public int populateContentTypeCache(int limit) { if (limit > 1000) { throw new IllegalArgumentException("Page limit cannot be more then 1000."); } if (limit <= 0) { throw new IllegalArgumentException("Page limit cannot be less or equal to 0."); } return observeContentTypeCachePopulation(limit).blockingFirst(); }

Target:
public int populateContentTypeCache(int limit) { if (limit > 1000) { throw new IllegalArgumentException("Content types per page limit cannot be more then 1000."); } if (limit <= 0) { throw new IllegalArgumentException("Content types per page limit cannot be " + "less or equal to 0."); } return observeContentTypeCachePopulation(limit).blockingFirst(); }
Source:
protected void createFieldEditors() { stringEditor = new StringFieldEditor(ReqifPreferences.REQIF_ID_ATTRIBUTE, "ID attribute", getFieldEditorParent()); addField(stringEditor); }

Target:
protected void createFieldEditors() { stringEditor = new StringFieldEditor(ReqifPreferences.REQIF_ID_ATTRIBUTE, ID_ATTRIBUTE, getFieldEditorParent()); addField(stringEditor); }
Source:
private void checkResourceRequirements() { final Map<JobID, Collection<ResourceRequirement>> missingResources = resourceTracker.getMissingResources(); if (missingResources.isEmpty()) { return; } final Map<JobID, ResourceCounter> outstandingRequirements = new LinkedHashMap<>(); for (Map.Entry<JobID, Collection<ResourceRequirement>> resourceRequirements : missingResources.entrySet()) { JobID jobId = resourceRequirements.getKey(); for (ResourceRequirement resourceRequirement : resourceRequirements.getValue()) { int numMissingSlots = internalRequestSlots(jobId, jobMasterTargetAddresses.get(jobId), resourceRequirement); if (numMissingSlots > 0) { outstandingRequirements .computeIfAbsent(jobId, ignored -> new ResourceCounter()) .incrementCount(resourceRequirement.getResourceProfile(), numMissingSlots); } } } final ResourceCounter pendingSlots = new ResourceCounter(taskExecutorManager.getPendingTaskManagerSlots().stream().collect( Collectors.groupingBy( PendingTaskManagerSlot::getResourceProfile, Collectors.summingInt(x -> 1)))); for (Map.Entry<JobID, ResourceCounter> unfulfilledRequirement : outstandingRequirements.entrySet()) { tryFulfillRequirementsWithPendingOrNewSlots( unfulfilledRequirement.getKey(), unfulfilledRequirement.getValue().getResourceProfilesWithCount(), pendingSlots); } }

Target:
private void checkResourceRequirements() { final Map<JobID, Collection<ResourceRequirement>> missingResources = resourceTracker.getMissingResources(); if (missingResources.isEmpty()) { return; } final Map<JobID, ResourceCounter> unfulfilledRequirements = new LinkedHashMap<>(); for (Map.Entry<JobID, Collection<ResourceRequirement>> resourceRequirements : missingResources.entrySet()) { final JobID jobId = resourceRequirements.getKey(); final ResourceCounter unfulfilledJobRequirements = tryAllocateSlotsForJob(jobId, resourceRequirements.getValue()); if (!unfulfilledJobRequirements.isEmpty()) { unfulfilledRequirements.put(jobId, unfulfilledJobRequirements); } } if (unfulfilledRequirements.isEmpty()) { return; } final ResourceCounter pendingSlots = new ResourceCounter(taskExecutorManager.getPendingTaskManagerSlots().stream().collect( Collectors.groupingBy( PendingTaskManagerSlot::getResourceProfile, Collectors.summingInt(x -> 1)))); for (Map.Entry<JobID, ResourceCounter> unfulfilledRequirement : unfulfilledRequirements.entrySet()) { tryFulfillRequirementsWithPendingSlots( unfulfilledRequirement.getKey(), unfulfilledRequirement.getValue().getResourceProfilesWithCount(), pendingSlots); } }
Source:
private void scheduleOrRescheduleJob(ScheduledJob job) { JobBuilder jobBuilder = JobBuilder.newJob(job.getClazz()) .withIdentity(job.getJobKey()) .requestRecovery(job.isRequestsRecovery()) .storeDurably(job.isStoreDurably()); boolean exists = false; try { exists = scheduler.checkExists(job.getJobKey()); } catch (SchedulerException e) { log.error("error occured checking the job " + job.getJobKey().toString(), e); return; } if (!exists) { try { scheduler.scheduleJob(jobBuilder.build(), job.getTrigger()); } catch (SchedulerException e) { log.error("error occured scheduling the job " + job.getJobKey().toString(), e); return; } log.info("scheduled job with key " + job.getJobKey().toString()); } else { List<? extends Trigger> triggers = new ArrayList<>(); try { triggers = scheduler.getTriggersOfJob(job.getJobKey()); } catch (SchedulerException e) { log.error("error occured reading triggers of the job " + job.getJobKey().toString(), e); return; } if (triggers.size() == 1) { try { scheduler.rescheduleJob(triggers.get(0).getKey(), job.getTrigger()); } catch (SchedulerException e) { log.error("error occured re-scheduling the job " + job.getJobKey().toString(), e); return; } } else { try { scheduler.deleteJob(job.getJobKey()); scheduler.scheduleJob(jobBuilder.build(), job.getTrigger()); } catch (SchedulerException e) { log.error("error occured deleting/scheduling the job " + job.getJobKey().toString(), e); return; } } } log.info(job.getMessage()); }

Target:
private void scheduleOrRescheduleJob(ScheduledJob job) { JobKey jobKey = job.getJobKey(); Trigger trigger = job.getTrigger(); JobBuilder jobBuilder = JobBuilder.newJob(job.getClazz()) .withIdentity(jobKey) .requestRecovery(job.isRequestsRecovery()) .storeDurably(job.isStoreDurably()); try { if (scheduler.checkExists(jobKey)) { List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey); if (triggers.size() == 1) { scheduler.rescheduleJob(triggers.get(0).getKey(), trigger); log.info(job.getMessage()); } else { scheduler.deleteJob(jobKey); scheduler.scheduleJob(jobBuilder.build(), trigger); log.info(job.getMessage()); } } else { scheduler.scheduleJob(jobBuilder.build(), trigger); log.info("scheduled job with key {}", jobKey.toString()); log.info(job.getMessage()); } } catch (SchedulerException e) { log.error(String.format("error occurred scheduling the job %s", jobKey), e); } }
Source:
private static String exclusionReasonExpressionNotSatisfy(List<String> tagExpressions) { return String.format("Test excluded Because it does not satisfy expression(s): [%s]", formatToString(tagExpressions)); }

Target:
private static String exclusionReasonExpressionNotSatisfy(List<String> tagExpressions) { return String.format("excluded because tags do not match tag expression(s): [%s]", formatToString(tagExpressions)); }
Source:
static boolean isTransformSelectedFrom(Transform[] selected, Transform[] selectFrom) { if ((selected.length > 1) || (selected.length == 0) != (selectFrom.length == 0)) { return false; } if (selected.length == 0) return true; Transform chosenTransform = selected[0]; return Arrays.asList(selectFrom).contains(chosenTransform); }

Target:
static boolean isTransformSelectedFrom(Transform[] selected, Transform[] selectFrom) { if ((selected.length > 1) || (selected.length == 0) != (selectFrom.length == 0)) { return false; } if (selected.length == 0) return true; return Arrays.asList(selectFrom).contains(selected[0]); }
Source:
final V putIfAbsent(K key, V value, Metadata metadata, long explicitFlags, InvocationContext ctx) { assertKeyValueNotNull(key, value); DataWriteCommand command; if (value instanceof Delta) { command = createApplyDelta(key, (Delta) value, explicitFlags, ctx); } if (value instanceof DeltaAware && (explicitFlags & FlagBitSets.CACHE_MODE_LOCAL) == 0) { command = createApplyDelta(key, ((DeltaAware) value).delta(), explicitFlags, ctx); } else { command = createPutIfAbsentCommand(key, value, metadata, explicitFlags, ctx); } return (V) executeCommandAndCommitIfNeeded(ctx, command); }

Target:
final V putIfAbsent(K key, V value, Metadata metadata, long explicitFlags, InvocationContext ctx) { assertKeyValueNotNull(key, value); DataWriteCommand command; if (value instanceof Delta) { command = createApplyDelta(key, (Delta) value, explicitFlags, ctx); } else if (value instanceof DeltaAware && (explicitFlags & FlagBitSets.CACHE_MODE_LOCAL) == 0) { command = createApplyDelta(key, ((DeltaAware) value).delta(), explicitFlags, ctx); } else { command = createPutIfAbsentCommand(key, value, metadata, explicitFlags, ctx); } return (V) executeCommandAndCommitIfNeeded(ctx, command); }
Source:
public void MessageWall_006_writeReply() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userName, credentials.password, wikiURL); NewMessageWall wall = base.openMessageWall(credentials.userName, wikiURL); MiniEditorComponentObject mini = wall.triggerMessageArea(); String message = PageContent.MESSAGE_WALL_MESSAGE_PREFIX + wall.getTimeStamp(); String title = PageContent.MESSAGE_WALL_TITLE_PREFIX+ wall.getTimeStamp(); mini.switchAndWrite(message); wall.writeTitle(title); wall.submit(); wall.verifyMessageText(title, message, credentials.userName); MiniEditorComponentObject miniReply = wall.triggerReplyMessageArea(); String reply = PageContent.MESSAGE_WALL_QUOTE_PREFIX + wall.getTimeStamp(); miniReply.switchAndQuoteMessageWall(reply);; wall.submitQuote(); wall.verifyQuote(reply); }

Target:
public void MessageWall_006_writeReply() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userName, credentials.password, wikiURL); NewMessageWall wall = base.openMessageWall(credentials.userName, wikiURL); MiniEditorComponentObject mini = wall.triggerMessageArea(); String message = PageContent.MESSAGE_WALL_MESSAGE_PREFIX + wall.getTimeStamp(); String title = PageContent.MESSAGE_WALL_TITLE_PREFIX + wall.getTimeStamp(); mini.switchAndWrite(message); wall.writeTitle(title); wall.submit(); wall.verifyMessageText(title, message, credentials.userName); MiniEditorComponentObject miniReply = wall.triggerReplyMessageArea(); String reply = PageContent.MESSAGE_WALL_QUOTE_PREFIX + wall.getTimeStamp(); miniReply.switchAndQuoteMessageWall(reply); wall.submitQuote(); wall.verifyQuote(reply); }
Source:
public void finalizeDependencies() { if (dependencies != null) { List<Rule> scalaCompiler = Collections.singletonList( new JvmBinaryRule() .mainClassName("scala.tools.nsc.Main") .deps(BuckRuleComposer.external(dependencies)) .ruleType(RuleType.JAVA_BINARY.getBuckName()) .name("scala-compiler.jar") .defaultVisibility()); Multimap<String, String> loadStatements = LoadStatementsUtil.getLoadStatements(scalaCompiler, extension); File buckFile = rootProject.file(SCALA_COMPILER_LOCATION).toPath().resolve("BUCK").toFile(); FileUtil.writeToBuckFile(loadStatements, scalaCompiler, buckFile); } }

Target:
public void finalizeDependencies() { if (dependencies != null) { List<Rule> scalaCompiler = Collections.singletonList( new JvmBinaryRule() .mainClassName("scala.tools.nsc.Main") .deps(BuckRuleComposer.external(dependencies)) .ruleType(RuleType.JAVA_BINARY.getBuckName()) .name("scala-compiler.jar") .defaultVisibility()); Multimap<String, String> loadStatements = LoadStatementsUtil.getLoadStatements(scalaCompiler, extension); File buckFile = rootProject .file(SCALA_COMPILER_LOCATION) .toPath() .resolve(OkBuckGradlePlugin.BUCK) .toFile(); FileUtil.writeToBuckFile(loadStatements, scalaCompiler, buckFile); } }
Source:
public void testGetEntryIdsOfTestEntries() { final List<ImportedGermplasm> importedGermplasmList = createImportedGermplasmList(); importedGermplasmList.get(0).setEntryTypeCategoricalID(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()); importedGermplasmList.get(2).setEntryTypeCategoricalID(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()); final Set<Integer> result = augmentedRandomizedBlockDesignServiceImpl.getEntryIdsOfTestEntries(importedGermplasmList); Assert.assertEquals("There should be 8 test entries in the list", 8, result.size()); Assert.assertTrue(!result.contains(1)); Assert.assertTrue(!result.contains(3)); }

Target:
public void testGetEntryIdsOfTestEntries() { final List<ImportedGermplasm> importedGermplasmList = createImportedGermplasmList(); importedGermplasmList.get(FIRST_CHECK_ENTRY).setEntryTypeCategoricalID(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()); importedGermplasmList.get(THIRD_CHECK_ENTRY).setEntryTypeCategoricalID(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()); final Set<Integer> result = augmentedRandomizedBlockDesignServiceImpl.getEntryIdsOfTestEntries(importedGermplasmList); Assert.assertEquals("There should be 8 test entries in the list", 8, result.size()); Assert.assertTrue(!result.contains(1)); Assert.assertTrue(!result.contains(3)); }
Source:
protected void updateNotify(long sequence) { Object[] refs = null; try { if(PlatformAggregatorProvider.getPlatformAggregator() != null){ refs = PlatformAggregatorProvider.getPlatformAggregator().getServiceReferences(IOptionsListener.class.getName(),"(name=" + registrationName + ")"); if (refs != null) { for (Object ref : refs) { IOptionsListener listener = (IOptionsListener)PlatformAggregatorProvider.getPlatformAggregator().getService(ref); if (listener != null) { try { listener.optionsUpdated(this, sequence); } catch (Throwable ignore) { } finally { PlatformAggregatorProvider.getPlatformAggregator().ungetService(ref); } } } } } } catch (Exception e) { if (log.isLoggable(Level.SEVERE)) { log.log(Level.SEVERE, e.getMessage(), e); } } }

Target:
protected void updateNotify (long sequence) { Object[] refs = null; try { if(aggregator != null && aggregator.getPlatformServices() != null){ refs = aggregator.getPlatformServices().getServiceReferences(IOptionsListener.class.getName(),"(name=" + registrationName + ")"); if (refs != null) { for (Object ref : refs) { IOptionsListener listener = (IOptionsListener)aggregator.getPlatformServices().getService(ref); if (listener != null) { try { listener.optionsUpdated(this, sequence); } catch (Throwable ignore) { } finally { aggregator.getPlatformServices().ungetService(ref); } } } } } } catch (PlatformServicesException e) { if (log.isLoggable(Level.SEVERE)) { log.log(Level.SEVERE, e.getMessage(), e); } } }
Source:
private String doResolvePath(final String nodePath, final String parameterReference) { if (".".equals(parameterReference)) { return nodePath; } if (parameterReference.startsWith("..")) { String current = nodePath; String ref = parameterReference; while (ref.startsWith("..")) { final int lastDot = current.lastIndexOf('.'); if (lastDot < 0) { return null; } current = current.substring(0, lastDot); ref = ref.substring(2 ); if (ref.startsWith("/")) { ref = ref.substring(1); } } return current + (!ref.isEmpty() ? "." : "") + ref.replace('/', '.'); } if (parameterReference.startsWith(".") || parameterReference.startsWith("./")) { return nodePath + '.' + parameterReference.replaceFirst("\\./?", "").replace('/', '.'); } return parameterReference; }

Target:
private Optional<String> doResolvePath(final String nodePath, final String parameterReference) { if (".".equals(parameterReference)) { return Optional.of(nodePath); } if (parameterReference.startsWith("..")) { String current = nodePath; String ref = parameterReference; while (ref.startsWith("..")) { final int lastDot = current.lastIndexOf('.'); if (lastDot < 0) { return Optional.empty(); } current = current.substring(0, lastDot); ref = ref.substring(2 ); if (ref.startsWith("/")) { ref = ref.substring(1); } } return Optional.of(current + (!ref.isEmpty() ? "." : "") + ref.replace('/', '.')); } if (parameterReference.startsWith(".") || parameterReference.startsWith("./")) { return Optional.of(nodePath + '.' + parameterReference.replaceFirst("\\./?", "").replace('/', '.')); } return Optional.of(parameterReference); }
Source:
@Override public boolean trackVmHostChange() { return true; }

Target:
public boolean trackVmHostChange() { return true; }
Source:
public void visitCatchBlock(CatchBlockTree tree) { complexity.addComplexityWithNesting(tree.catchToken()); complexity.incNesting(); super.visitCatchBlock(tree); complexity.decNesting(); }

Target:
public void visitCatchBlock(CatchBlockTree tree) { complexity.addComplexityWithNesting(tree.catchToken()); visitWithNesting(()-> super.visitCatchBlock(tree)); }
Source:
public void testReportingBuckets() throws Exception { createIndex("test"); LatencyStatsAction.LatencyStatsNodesResponse statsResponse = client().prepareExecute(LatencyStatsAction.INSTANCE).execute().get(); statsResponse.getNodes().stream().map(n -> n.statDetails).forEach(stat -> assertEquals(0, stat.getLatencies().size())); LatencyStatsAction.StatDetails allNodes = statsResponse.getAllNodes(); assertEquals(0, allNodes.getLatencies().size()); SearchRequestBuilder builder = client().prepareSearch("test").setQuery(new MatchAllQueryBuilder()) .setStats("integration"); client().search(builder.request()).get(); Thread.sleep(5200); statsResponse = client().prepareExecute(LatencyStatsAction.INSTANCE).execute().get(); assertEquals(4, statsResponse.getAllNodes().getLatencies().size()); statsResponse.getAllNodes().getLatencies().stream().forEach(stat -> assertEquals("integration", stat.getBucket())); assertNotEquals(0, statsResponse.getNodes().stream() .map(n -> n.statDetails) .filter(stat -> stat.getLatencies().size() > 0).count()); statsResponse.getNodes().stream() .flatMap(n -> n.statDetails.getLatencies().stream()) .forEach(stat -> assertEquals("integration", stat.getBucket())); }

Target:
public void testReportingBuckets() throws Exception { createIndex("test"); LatencyStatsAction.LatencyStatsNodesResponse statsResponse = client().prepareExecute(LatencyStatsAction.INSTANCE).execute().get(); statsResponse.getNodes().stream() .map(n -> n.statDetails) .forEach(stat -> assertEquals(0, stat.getLatencies().size())); LatencyStatsAction.StatDetails allNodes = statsResponse.getAllNodes(); assertEquals(0, allNodes.getLatencies().size()); SearchRequestBuilder builder = client() .prepareSearch("test") .setQuery(new MatchAllQueryBuilder()) .setStats("integration"); client().search(builder.request()).get(); Thread.sleep(5200); statsResponse = client().prepareExecute(LatencyStatsAction.INSTANCE).execute().get(); assertEquals(4, statsResponse.getAllNodes().getLatencies().size()); statsResponse.getAllNodes().getLatencies() .forEach(stat -> assertEquals("integration", stat.getBucket())); assertNotEquals(0, statsResponse.getNodes().stream() .map(n -> n.statDetails) .filter(stat -> stat.getLatencies().size() > 0) .count()); statsResponse.getNodes().stream() .flatMap(n -> n.statDetails.getLatencies().stream()) .forEach(stat -> assertEquals("integration", stat.getBucket())); }
Source:
private void checkConnectorPort() { if (null != connector) { int cp = ((ServerConnector)connector).getPort(); if (port != cp) { throw new IllegalStateException("Error: Connector port " + cp + " does not match" + " with the server engine port " + port); } } }

Target:
private void checkConnectorPort() { if (null != connector) { int cp = ((ServerConnector)connector).getPort(); if (port != cp) { throw new UncheckedIOException(new IOException("Error: Connector port " + cp + " does not match" + " with the server engine port " + port)); } } }
Source:
@Override protected void afterTest() throws Exception { super.afterTest(); indexingDisabled = false; }

Target:
@Override protected void afterTest() throws Exception { super.afterTest(); indexingDisabled = false; GridQueryProcessor.idxCls = null; }
Source:
public void updateCollisionFormulasToNewVersion() { for (Script script : getScriptList()) { Brick scriptBrick = script.getScriptBrick(); if (scriptBrick instanceof FormulaBrick) { FormulaBrick formulaBrick = (FormulaBrick) scriptBrick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } for (Brick brick : script.getBrickList()) { if (brick instanceof UserBrick) { UserBrick formulaBrick = (UserBrick) brick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } if (brick instanceof FormulaBrick) { FormulaBrick formulaBrick = (FormulaBrick) brick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } } } }

Target:
public void updateCollisionFormulasToNewVersion() { for (Script script : getScriptList()) { Brick scriptBrick = script.getScriptBrick(); if (scriptBrick instanceof FormulaBrick) { FormulaBrick formulaBrick = (FormulaBrick) scriptBrick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } for (Brick brick : script.getBrickList()) { if (brick instanceof UserBrick) { UserBrick formulaBrick = (UserBrick) brick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } else if (brick instanceof FormulaBrick) { FormulaBrick formulaBrick = (FormulaBrick) brick; for (Formula formula : formulaBrick.getFormulas()) { formula.updateCollisionFormulasToNewVersion(); } } } } }
Source:
private void deliverPendingReports() { lock.lock(); try { File outDir = new File(reportDirectory); if (outDir.exists()) { File[] fileList = outDir.listFiles(); if (fileList != null) { for (final File file : fileList) { deliverReportAtPath(file.getAbsolutePath()); } } } else { warn("Report directory does not exist, cannot read pending reports"); } } catch (Exception ex) { warn("Failed to parse/write pending reports: " + ex); } lock.unlock(); }

Target:
private void deliverPendingReports() { lock.lock(); try { File outDir = new File(reportDirectory); if (outDir.exists()) { File[] fileList = outDir.listFiles(); if (fileList != null) { for (final File file : fileList) { deliverReportAtPath(file.getAbsolutePath()); } } } else { warn("Report directory does not exist, cannot read pending reports"); } } catch (Exception ex) { warn("Failed to parse/write pending reports: " + ex); } finally { lock.unlock(); } }
Source:
boolean containsStops(JSONObject jsonObject) { Boolean hasStops = false; Set<?> keySet = jsonObject.keySet(); Iterator<?> keys = keySet.iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (jsonObject.get(key) instanceof JSONObject) { JSONObject child = (JSONObject) jsonObject.get(key); if (child.containsKey("stops") && ((JSONArray)((JSONArray)child.get("stops")).get(0)).get(0) instanceof JSONObject) { hasStops = true; } } } return hasStops; }

Target:
boolean containsStops(JSONObject jsonObject) { Boolean hasStops = false; Set<?> keySet = jsonObject.keySet(); Iterator<?> keys = keySet.iterator(); while (keys.hasNext()) { String key = (String) keys.next(); if (jsonObject.get(key) instanceof JSONObject) { JSONObject child = (JSONObject) jsonObject.get(key); if (child.containsKey("stops")) { if (!child.containsKey("property")) { hasStops = true; } else if (child.get("stops") instanceof JSONArray) { JSONArray stops = (JSONArray) child.get("stops"); if (stops.get(0) instanceof JSONObject && ((JSONObject)stops.get(0)).containsKey("zoom")) { hasStops = true; } } } } } return hasStops; }
Source:
public void start(Listener<RespT> listener, Metadata metadata) { ClientCall<ReqT, RespT> call = delegate(); synchronized (lock) { Preconditions.checkState(state == null, "Already started"); state = (pendingCount == 0) ? State.IDLE : State.WAITING; lastActivityAt = clock.currentTimeMillis(); } openStreams.put(this, PRESENT); call.start(new SimpleForwardingClientCallListener<RespT>(listener) { @Override public void onMessage(RespT message) { synchronized (lock) { state = State.DELIVERING; } try { super.onMessage(message); } finally { synchronized (lock) { pendingCount--; lastActivityAt = clock.currentTimeMillis(); state = (pendingCount > 0) ? State.WAITING : State.IDLE; } } } @Override public void onClose(Status status, Metadata trailers) { openStreams.remove(WatchedCall.this); if (status.getCause() instanceof StreamWaitTimeoutException) { status = Status.ABORTED .withDescription(status.getDescription()) .withCause(status.getCause()); } super.onClose(status, trailers); } }, metadata); }

Target:
public void start(Listener<RespT> listener, Metadata metadata) { ClientCall<ReqT, RespT> call = delegate(); synchronized (lock) { Preconditions.checkState(state == null, "Already started"); lastActivityAt = clock.currentTimeMillis(); } openStreams.put(this, PRESENT); call.start(new SimpleForwardingClientCallListener<RespT>(listener) { @Override public void onMessage(RespT message) { synchronized (lock) { state = State.DELIVERING; } try { super.onMessage(message); } finally { synchronized (lock) { pendingCount--; lastActivityAt = clock.currentTimeMillis(); state = (pendingCount > 0) ? State.WAITING : State.IDLE; } } } @Override public void onClose(Status status, Metadata trailers) { openStreams.remove(WatchedCall.this); super.onClose(status, trailers); } }, metadata); }
Source:
View findScrollingChild(View view) { if (ViewCompat.isNestedScrollingEnabled(view)) { return view; } if (view instanceof ViewPager2) { ViewPager2 viewPager = (ViewPager2) view; View currentViewPagerChild = viewPager.getChildAt(viewPager.getCurrentItem()); if (currentViewPagerChild != null) { return findScrollingChild(currentViewPagerChild); } } else if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; for (int i = 0, count = group.getChildCount(); i < count; i++) { View scrollingChild = findScrollingChild(group.getChildAt(i)); if (scrollingChild != null) { return scrollingChild; } } } return null; }

Target:
View findScrollingChild(View view) { if (ViewCompat.isNestedScrollingEnabled(view)) { return view; } if (view instanceof ViewPager2) { ViewPager2 viewPager = (ViewPager2) view; RecyclerView recycler = (RecyclerView) viewPager.getChildAt(0); View currentViewPagerChild = recycler.getChildAt(viewPager.getCurrentItem()); if (currentViewPagerChild != null) { return findScrollingChild(currentViewPagerChild); } } else if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; for (int i = 0, count = group.getChildCount(); i < count; i++) { View scrollingChild = findScrollingChild(group.getChildAt(i)); if (scrollingChild != null) { return scrollingChild; } } } return null; }
Source:
public final void setPath(final String location) { AudioPlayer.path = location; }

Target:
public final void setPath(final String location) { path = location; initializeTune(path); }
Source:
public void tsv_entriesAreEscaped() { TsvEntity csvEntity = new TsvEntity(); Map jsonMap = ImmutableMap.of( "hash", "hash1", "entry", ImmutableMap.of( "key1", "value1", "key2", "val\tue2", "key3", "val\"ue3", "key4", "val\nue4" ) ); JsonNode node = JsonObjectMapper.convert(jsonMap, JsonNode.class); AbstractView view = new SingleResultView("someTemplate", node); Object result = csvEntity.convert(view); assertThat(result.toString(), equalTo("hash\tkey1\tkey2\tkey3\tkey4\nhash1\tvalue1\t\"val\tue2\"\t\"val\"\"ue3\"\t\"val\nue4\"")); }

Target:
public void tsv_entriesAreEscaped() { TsvEntity csvEntity = new TsvEntity(); Map jsonMap = ImmutableMap.of( "hash", "hash1", "entry", ImmutableMap.of( "key1", "value1", "key2", "val\tue2", "key3", "val\"ue3", "key4", "val\nue4" ) ); JsonNode node = JsonObjectMapper.convert(jsonMap, JsonNode.class); AbstractView view = new SingleResultView("someTemplate", node); Object result = csvEntity.convert(view); assertThat(result.toString(), equalTo("hash\tkey1\tkey2\tkey3\tkey4\r\nhash1\tvalue1\t\"val\tue2\"\t\"val\"\"ue3\"\t\"val\nue4\"")); }
Source:
public int compareTo(PickerMilestone milestone) { if (isHighlighted) return -1; if (milestone.isHighlighted()) return 1; if (this.getDueDate().equals(milestone.getDueDate())) return 0; if (this.isOpen() != milestone.isOpen()) { return this.isOpen() ? -1 : 1; } if (!this.getDueDate().isPresent()) return -1; if (!milestone.getDueDate().isPresent()) return 1; return this.getDueDate().get() .isAfter(milestone.getDueDate().get()) ? -1 : 1; }

Target:
public int compareTo(PickerMilestone milestone) { if (isSelected != milestone.isSelected()) { return isSelected ? -1 : 1; } if (this.isOpen() != milestone.isOpen()) { return this.isOpen() ? -1 : 1; } if (this.getDueDate().equals(milestone.getDueDate())) return 0; if (!this.getDueDate().isPresent()) return 1; if (!milestone.getDueDate().isPresent()) return -1; return this.getDueDate().get() .isBefore(milestone.getDueDate().get()) ? -1 : 1; }