auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testModemActivityInfoIsValid() { ModemActivityInfo modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, new int[2], VALID_RX_TIME_MS); assertTrue("ModemActivityInfo should be valid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, INVALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, new int[2], VALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because sleep time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, INVALID_IDLE_TIME_MS, new int[2], VALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because idle time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, new int[2], INVALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because receive time is invalid", modemActivityInfo.isValid()); }

Target:
public void testModemActivityInfoIsValid() { ModemActivityInfo modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, VALID_TX_TIME_MS, VALID_RX_TIME_MS); assertTrue("ModemActivityInfo should be valid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, INVALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, VALID_TX_TIME_MS, VALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because sleep time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, INVALID_IDLE_TIME_MS, VALID_TX_TIME_MS, VALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because idle time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, VALID_TX_TIME_MS, INVALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because receive time is invalid", modemActivityInfo.isValid()); modemActivityInfo = new ModemActivityInfo(0, VALID_SLEEP_TIME_MS, VALID_IDLE_TIME_MS, INVALID_TX_TIME_MS, INVALID_RX_TIME_MS); assertFalse("ModemActivityInfo should be invalid because transmit time is invalid", modemActivityInfo.isValid()); }
Source:
public void setMaintenanceStatus(@Identification final String organisationIdentification, final String deviceIdentification, final boolean status) throws FunctionalException { final Device existingDevice = this.writableDeviceRepository.findByDeviceIdentification(deviceIdentification); if (existingDevice == null) { LOGGER.info("Device does not exist, cannot set maintenance status."); throw new FunctionalException(FunctionalExceptionType.UNKNOWN_DEVICE, ComponentType.WS_CORE, new UnknownEntityException(Device.class, deviceIdentification)); } else if (existingDevice.getOwner().getOrganisationIdentification().equals(organisationIdentification) || existingDevice.getOwner().getOrganisationIdentification().equals(this.netMangementOrganisation)) { existingDevice.updateInMaintenance(status); this.writableDeviceRepository.save(existingDevice); } else { throw new FunctionalException(FunctionalExceptionType.UNAUTHORIZED, ComponentType.WS_CORE, new UnknownEntityException(Device.class, deviceIdentification)); } }

Target:
public void setMaintenanceStatus(@Identification final String organisationIdentification, final String deviceIdentification, final boolean status) throws FunctionalException { final Device existingDevice = this.writableDeviceRepository.findByDeviceIdentification(deviceIdentification); if (existingDevice == null) { LOGGER.info("Device does not exist, cannot set maintenance status."); throw new FunctionalException(FunctionalExceptionType.UNKNOWN_DEVICE, ComponentType.WS_CORE, new UnknownEntityException(Device.class, deviceIdentification)); } else if (existingDevice.getOwner().getOrganisationIdentification().equals(organisationIdentification) || existingDevice.getOwner().getOrganisationIdentification().equals(this.netMangementOrganisation)) { existingDevice.updateInMaintenance(status); this.writableDeviceRepository.save(existingDevice); } else { throw new FunctionalException(FunctionalExceptionType.UNAUTHORIZED, ComponentType.WS_CORE, new NotAuthorizedException(organisationIdentification)); } }
Source:
public void shareProjectNotPA() throws ESException { try { ProjectUtil.share(getUsersession(), getLocalProject()); } catch (final ESException ex) { boolean found = false; for (final StackTraceElement stackTraceElement : ex.getStackTrace()) { final String className = stackTraceElement.getClassName(); final String methodName = stackTraceElement.getMethodName(); if ("org.eclipse.emf.emfstore.internal.server.core.EMFStoreImpl".equals(className) && "invoke".equals(methodName)) { found = true; } } if (!found) { fail("EMFStoreImpl#invoke should fail already"); } throw ex; } }

Target:
public void shareProjectNotPA() throws ESException { try { ProjectUtil.share(getUsersession(), getLocalProject()); } catch (final ESException ex) { assertTrue(getServerMock().getServerSpace().getProjects().isEmpty()); throw ex; } }
Source:
private static String guessApiUri(URL repositoryUrl) { StringBuilder sb = new StringBuilder(); sb.append(repositoryUrl.getProtocol()); sb.append("://"); sb.append(repositoryUrl.getHost()); if (repositoryUrl.getPort() != -1) { sb.append(':'); sb.append(repositoryUrl.getPort()); } sb.append('/').append(GitHubSCMBuilder.API_V3); return GitHubConfiguration.normalizeApiUri(sb.toString()); }

Target:
private static String guessApiUri(URL repositoryUrl) { StringBuilder sb = new StringBuilder(); sb.append(repositoryUrl.getProtocol()); sb.append("://"); boolean isGitHub = GITHUB_COM.equals(repositoryUrl.getHost()); if(isGitHub){ sb.append(GITHUB_API_URL); }else { sb.append(repositoryUrl.getHost()); } if (repositoryUrl.getPort() != -1) { sb.append(':'); sb.append(repositoryUrl.getPort()); } if(!isGitHub) { sb.append('/').append(GitHubSCMBuilder.API_V3); } return GitHubConfiguration.normalizeApiUri(sb.toString()); }
Source:
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) { if (FAKE_SIGNATURES) return true; if (Secp256k1Context.isEnabled()) { try { return NativeSecp256k1.verify(data, signature.toCanonicalised().encodeToDER(), pub); } catch (NativeSecp256k1Util.AssertFailException e) { log.error("Caught AssertFailException inside secp256k1", e); return false; } } ECDSASigner signer = new ECDSASigner(); ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE); signer.init(false, params); try { return signer.verifySignature(data, signature.r, signature.s); } catch (NullPointerException e) { log.error("Caught NPE inside bouncy castle", e); return false; } }

Target:
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) { if (FAKE_SIGNATURES) return true; if (Secp256k1Context.isEnabled()) { try { return NativeSecp256k1.verify(data, signature.encodeToDER(), pub); } catch (NativeSecp256k1Util.AssertFailException e) { log.error("Caught AssertFailException inside secp256k1", e); return false; } } ECDSASigner signer = new ECDSASigner(); ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE); signer.init(false, params); try { return signer.verifySignature(data, signature.r, signature.s); } catch (NullPointerException e) { log.error("Caught NPE inside bouncy castle", e); return false; } }
Source:
public Response setBranchType(long branchUuid, BranchType newType) { BranchReadable branch = getBranchById(branchUuid); boolean modified = false; if (isDifferent(branch.getBranchType(), newType)) { activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Set Branch Type {branchUUID: %s prevType: %s newType: %s accountId: %s serverId: %s clientId: %s}", branchUuid, branch.getBranchType(), newType, accountId, serverId, clientId)); Callable<?> op = getBranchOps().changeBranchType(branch, newType); executeCallable(op); modified = true; } return asResponse(modified); }

Target:
public Response setBranchType(long branchUuid, BranchType newType) { BranchReadable branch = getBranchById(branchUuid); boolean modified = false; if (isDifferent(branch.getBranchType(), newType)) { try { activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Set Branch Type {branchUUID: %s prevType: %s newType: %s accountId: %s serverId: %s clientId: %s}", branchUuid, branch.getBranchType(), newType, RestUtil.getAccountId(httpHeaders), RestUtil.getServerId(httpHeaders), RestUtil.getClientId(httpHeaders))); } catch (OseeCoreException ex) { OseeLog.log(ActivityLog.class, OseeLevel.SEVERE_POPUP, ex); } Callable<?> op = getBranchOps().changeBranchType(branch, newType); executeCallable(op); modified = true; } return asResponse(modified); }
Source:
protected Object execute(Object[] data) { if (data == null) { throw new ExecutionPlanRuntimeException("Data can not be null."); } hashMap = (HashMap) data[0]; String type = (String) data[2]; Object tmpVal = hashMap.get(data[1]); Object value = null; if (type.toLowerCase().equals("int")) { try { String tmpStr = tmpVal.toString(); value = Integer.parseInt(tmpStr); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be parsed to INTEGER"); } } else if (type.toLowerCase().equals("double")) { try { String tmpStr = tmpVal.toString(); value = Double.parseDouble(tmpStr); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be parsed to DOUBLE"); } } else if (type.toLowerCase().equals("long")) { try { String tmpStr = tmpVal.toString(); value = Long.parseLong(tmpStr); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be parsed to LONG"); } } else if (type.toLowerCase().equals("bool")) { try { String tmpStr = tmpVal.toString(); value = Boolean.parseBoolean(tmpStr); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be parsed to BOOLEAN"); } } else if (type.toLowerCase().equals("string")) { try { value = tmpVal.toString(); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be converted to STRING"); } } else { value = tmpVal; } return value; }

Target:
protected Object execute(Object[] data) { if (data == null) { throw new ExecutionPlanRuntimeException("Data can not be null."); } if(data[0] instanceof HashMap) { hashMap = (HashMap) data[0]; } else { throw new ExecutionPlanRuntimeException("First attribute value must be a hashmap."); } String type = (String) data[2]; Object tmpVal = hashMap.get(data[1]); Object value; String tmpStr = tmpVal.toString(); if (type.toLowerCase().equals("int")) { try { value = Integer.parseInt(tmpStr); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be parsed to INTEGER"); } } else if (type.toLowerCase().equals("double")) { try { value = Double.parseDouble(tmpStr); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be parsed to DOUBLE"); } } else if (type.toLowerCase().equals("long")) { try { value = Long.parseLong(tmpStr); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be parsed to LONG"); } } else if (type.toLowerCase().equals("bool")) { try { value = Boolean.parseBoolean(tmpStr); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be parsed to BOOLEAN"); } } else if (type.toLowerCase().equals("string")) { try { value = tmpVal.toString(); } catch (ExecutionPlanRuntimeException e) { throw new ExecutionPlanRuntimeException("Attribute value cannot be converted to STRING"); } } else { value = tmpVal; } return value; }
Source:
public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); if (!(input instanceof FileEditorInput)) { throw new PartInitException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Expected editor input to be of type FileEditorInput")); } FileEditorInput fileInput = ((FileEditorInput)input); if (fileInput != null) { source = fileInput.getFile(); } }

Target:
public void init(IEditorSite site, IEditorInput input) throws PartInitException { if (!(input instanceof FileEditorInput)) { throw new PartInitException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Expected editor input to be of type FileEditorInput")); } setSite(site); setInput(input); FileEditorInput fileInput = ((FileEditorInput) input); if (fileInput != null) { source = fileInput.getFile(); } }
Source:
public static Font getFont(FontByDefinition fontByDefinition) { Font font = fontByDefinition.getResource(); IColorAndFontProvider provider = CSSActivator.getDefault().getColorAndFontProvider(); if (provider == null) { return font; } FontData[] fontDataFromDefinition = provider.getFont(fontByDefinition.getSymbolicName()); FontData[] currentFontData = font.getFontData(); if (!isFontDataValid(fontDataFromDefinition) || !isFontDataValid(currentFontData)) { return font; } String name = fontDataFromDefinition[0].getName(); int height = fontByDefinition.getHeight() == null? fontDataFromDefinition[0].getHeight(): fontByDefinition.getHeight(); int style = fontByDefinition.getStyle() == null? fontDataFromDefinition[0].getStyle(): fontByDefinition.getStyle(); if (height != currentFontData[0].getHeight() || style != currentFontData[0].getStyle() || !name.equals(currentFontData[0].getName())) { font = new Font(font.getDevice(), new FontData(name, height, style)); } return font; }

Target:
public static Font getFont(FontByDefinition fontByDefinition) { Font font = fontByDefinition.getResource(); IColorAndFontProvider provider = CSSActivator.getDefault().getColorAndFontProvider(); if (provider == null) { return font; } FontData[] fontDataFromDefinition = provider.getFont(fontByDefinition.getSymbolicName()); FontData[] currentFontData = font.getFontData(); if (!isFontDataValid(fontDataFromDefinition) || !isFontDataValid(currentFontData)) { return font; } String name = fontDataFromDefinition[0].getName(); int height = fontByDefinition.getHeight() == null? fontDataFromDefinition[0].getHeight(): fontByDefinition.getHeight(); int style = fontByDefinition.getStyle() == null? fontDataFromDefinition[0].getStyle(): fontByDefinition.getStyle(); if (height != currentFontData[0].getHeight() || style != currentFontData[0].getStyle() || !name.equals(currentFontData[0].getName())) { Device device = font.getDevice(); font.dispose(); font = new Font(device, new FontData(name, height, style)); fontByDefinition.setResource(font); } fontByDefinition.setValid(true); return font; }
Source:
public static final byte[] readSome(final File path, final int limit) throws FileNotFoundException, IOException { final FileInputStream in = new FileInputStream(path); try { ByteArrayOutputStream result = new ByteArrayOutputStream(limit); final byte[] buf = new byte[1024]; int read = in.read(buf); while (read > 0) { result.write(buf, 0, read); read = in.read(buf); } return result.toByteArray(); } finally { try { in.close(); } catch (IOException ignored) { } } }

Target:
public static final byte[] readSome(final File path, final int limit) throws FileNotFoundException, IOException { FileInputStream in = new FileInputStream(path); try { byte[] buf = new byte[limit]; int cnt = 0; for (;;) { int n = in.read(buf, cnt, buf.length - cnt); if (n <= 0) break; cnt += n; } if (cnt == buf.length) return buf; byte[] res = new byte[cnt]; System.arraycopy(buf, 0, res, 0, cnt); return res; } finally { try { in.close(); } catch (IOException ignored) { } } }
Source:
protected void setResult(Collection<T> newUserSelection) { if (newUserSelection == null) { result = Collections.emptyList(); } else { result = newUserSelection; } }

Target:
protected void setResult(Collection<T> newUserSelection) { if (newUserSelection == null) { result = null; } else { result = newUserSelection; } }
Source:
public Context(PageContext pageContext) { this(pageContext.getServletContext(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(), null, null, null); }

Target:
public Context(PageContext pageContext) { this(pageContext.getServletContext(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse(), pageContext.getOut(), null, null); }
Source:
public ResourceMapping[] getMappings(IResource resource, ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { if (context instanceof GitSubscriberResourceMappingContext && resource instanceof IProject) { GitSubscriberResourceMappingContext gitContext = (GitSubscriberResourceMappingContext) context; GitSynchronizeDataSet gsds = gitContext.getSyncData(); GitSynchronizeData data = gsds.getData((IProject)resource); if (data != null) { GitModelObject object = null; try { object = GitModelObject.createRoot(data); } catch (IOException e) { Activator.logError(e.getMessage(), e); } if (object != null) { ResourceMapping rm = (ResourceMapping) object .getAdapter(ResourceMapping.class); return new ResourceMapping[] { rm }; } } } return super.getMappings(resource, context, monitor); }

Target:
public ResourceMapping[] getMappings(IResource resource, ResourceMappingContext context, IProgressMonitor monitor) throws CoreException { if (context instanceof GitSubscriberResourceMappingContext) { GitSubscriberResourceMappingContext gitContext = (GitSubscriberResourceMappingContext) context; GitSynchronizeDataSet gsds = gitContext.getSyncData(); GitSynchronizeData data = gsds.getData(resource.getProject()); if (data != null) { GitModelObject object = null; try { object = GitModelObject.createRoot(data); } catch (IOException e) { Activator.logError(e.getMessage(), e); } if (object != null) { ResourceMapping rm = (ResourceMapping) object .getAdapter(ResourceMapping.class); return new ResourceMapping[] { rm }; } } } return super.getMappings(resource, context, monitor); }
Source:
public void onMessage(org.springframework.amqp.core.Message amqpMessage, Channel channel) throws Exception { Message<?> message = toMessagingMessage(amqpMessage); if (logger.isDebugEnabled()) { logger.debug("Processing [" + message + "]"); } try { Object result = invokeHandler(amqpMessage, channel, message); if (result != null) { handleResult(result, amqpMessage, channel, message); } else { logger.trace("No result object given - no result to handle"); } } catch (ListenerExecutionFailedException e) { if (this.errorHandler != null) { try { Object result = this.errorHandler.handleError(amqpMessage, message, e); if (result != null) { handleResult(result, amqpMessage, channel, message); } else { logger.trace("Error handler returned no result"); } } catch (Exception ex) { if (!this.propagateExceptions) { throw ex; } handleResult(new RemoteInvocationResult(ex), amqpMessage, channel, message); } } else { if (!this.propagateExceptions) { throw e; } handleResult(new RemoteInvocationResult(e.getCause()), amqpMessage, channel, message); } } }

Target:
public void onMessage(org.springframework.amqp.core.Message amqpMessage, Channel channel) throws Exception { Message<?> message = toMessagingMessage(amqpMessage); if (logger.isDebugEnabled()) { logger.debug("Processing [" + message + "]"); } try { Object result = invokeHandler(amqpMessage, channel, message); if (result != null) { handleResult(result, amqpMessage, channel, message); } else { logger.trace("No result object given - no result to handle"); } } catch (ListenerExecutionFailedException e) { if (this.errorHandler != null) { try { Object result = this.errorHandler.handleError(amqpMessage, message, e); if (result != null) { handleResult(result, amqpMessage, channel, message); } else { logger.trace("Error handler returned no result"); } } catch (Exception ex) { if (!this.returnExceptions) { throw ex; } handleResult(new RemoteInvocationResult(ex), amqpMessage, channel, message); } } else { if (!this.returnExceptions) { throw e; } handleResult(new RemoteInvocationResult(e.getCause()), amqpMessage, channel, message); } } }
Source:
protected List<MethodMatcher> getMethodInvocationMatchers() { return ImmutableList.of(MethodMatcher.create().typeDefinition("java.util.stream.Stream").name("peek").withAnyParameters()); }

Target:
protected List<MethodMatcher> getMethodInvocationMatchers() { return ImmutableList.of( MethodMatcher.create().typeDefinition("java.util.stream.Stream").name("peek").withAnyParameters(), MethodMatcher.create().typeDefinition("java.util.stream.IntStream").name("peek").withAnyParameters(), MethodMatcher.create().typeDefinition("java.util.stream.LongStream").name("peek").withAnyParameters(), MethodMatcher.create().typeDefinition("java.util.stream.DoubleStream").name("peek").withAnyParameters() ); }
Source:
public boolean equals(Object o) { if ( o == null || getClass() != o.getClass() ) { return false; } Mapping mapping = (Mapping) o; return targetName.equals( mapping.targetName ); }

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Mapping mapping = (Mapping) o; return targetName.equals( mapping.targetName ); }
Source:
public String toString() { StringBuilder s = new StringBuilder(super.toString()); switch (useFlag){ case USED: s.append("[pos: "); s.append(String.valueOf(resolvedPosition)); s.append("]"); break; case UNUSED: s.append("[pos: unused]"); break; case FAKE_USED: s.append("[pos: fake_used]"); break; } s.append("[id:"); s.append(String.valueOf(id)); s.append("]"); if (initializationCount > 0) { s.append("[pc: "); for (int i = 0; i < initializationCount; i++) { if (i > 0) { s.append(", "); } s.append(String.valueOf(initializationPCs[i << 1])); s.append("-"); s.append( ((initializationPCs[(i << 1) + 1] == -1) ? "?" : String.valueOf(initializationPCs[(i<< 1) + 1]))); } s.append("]"); } return s.toString(); }

Target:
public String toString() { StringBuilder s = new StringBuilder(super.toString()); switch (useFlag){ case USED: s.append("[pos: "); s.append(resolvedPosition); s.append("]"); break; case UNUSED: s.append("[pos: unused]"); break; case FAKE_USED: s.append("[pos: fake_used]"); break; } s.append("[id:"); s.append(id); s.append("]"); if (initializationCount > 0) { s.append("[pc: "); for (int i = 0; i < initializationCount; i++) { if (i > 0) { s.append(", "); } s.append(initializationPCs[i << 1]); s.append("-"); if (initializationPCs[(i << 1) + 1] == -1) { s.append("?"); } else { s.append(initializationPCs[(i<< 1) + 1]); } } s.append("]"); } return s.toString(); }
Source:
private static Split createRemoteSplitFor(TaskId taskId, URI remoteSourceTaskLocation, TaskId remoteSourceTaskId) { String splitLocation = remoteSourceTaskLocation.toASCIIString() + "/results/" + taskId.getId(); return new Split(REMOTE_CONNECTOR_ID, new RemoteTransactionHandle(), new RemoteSplit(splitLocation, remoteSourceTaskId)); }

Target:
private static Split createRemoteSplitFor(TaskId taskId, URI remoteSourceTaskLocation, TaskId remoteSourceTaskId) { String splitLocation = remoteSourceTaskLocation.toASCIIString() + "/results/" + taskId.getId(); return new Split(REMOTE_CONNECTOR_ID, new RemoteTransactionHandle(), new RemoteSplit(new Location(splitLocation), remoteSourceTaskId)); }
Source:
public Client updateClient(ClientUpdate update) { try (Jedis j = pool.getResource()) { byte[] ep = j.get(toRegKey(update.getRegistrationId())); if (ep == null) { return null; } byte[] data = j.get(ByteArrayUtils.concatenate(EP_CLIENT.getBytes(UTF_8), ep)); if (data == null) { return null; } Client c = deserialize(data); byte[] lockValue = null; byte[] lockKey = toLockKey(c.getEndpoint()); try { lockValue = RedisLock.acquire(j, lockKey); Client clientUpdated = update.updateClient(c); j.set(toEndpointKey(clientUpdated.getEndpoint()), serialize(clientUpdated)); for (ClientRegistryListener l : listeners) { l.updated(update, clientUpdated); } return clientUpdated; } finally { RedisLock.release(j, lockKey, lockValue); } } }

Target:
public Client updateClient(ClientUpdate update) { try (Jedis j = pool.getResource()) { byte[] ep = j.get(toRegKey(update.getRegistrationId())); if (ep == null) { return null; } byte[] data = j.get(toEndpointKey(ep)); if (data == null) { return null; } Client c = deserialize(data); byte[] lockValue = null; byte[] lockKey = toLockKey(c.getEndpoint()); try { lockValue = RedisLock.acquire(j, lockKey); Client clientUpdated = update.updateClient(c); j.set(toEndpointKey(clientUpdated.getEndpoint()), serialize(clientUpdated)); for (ClientRegistryListener l : listeners) { l.updated(update, clientUpdated); } return clientUpdated; } finally { RedisLock.release(j, lockKey, lockValue); } } }
Source:
public ThreadLocalSslBufferPool(int maxPoolSize, boolean preallocate, boolean allocateDirect) { pool = new ThreadLocal<NonBlockingSslBufferPoll>() { @Override protected NonBlockingSslBufferPoll initialValue() { int threadLocalMaxPoolSize = maxPoolSize / DEFAULT_WORKER_THREAD_COUNT; if (threadLocalMaxPoolSize % DEFAULT_WORKER_THREAD_COUNT != 0) { threadLocalMaxPoolSize ++; } return new NonBlockingSslBufferPoll(threadLocalMaxPoolSize, preallocate, allocateDirect); } }; }

Target:
public ThreadLocalSslBufferPool(int maxPoolSize, boolean preallocate, boolean allocateDirect) { this(maxPoolSize, preallocate, allocateDirect, DEFAULT_WORKER_THREAD_COUNT); }
Source:
public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final RelNode input = call.rel(1); final RelMetadataQuery mq = call.getMetadataQuery(); if (!SqlFunctions.isTrue(mq.areColumnsUnique(input, aggregate.getGroupSet()))) { return; } final RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder(); final List<RexNode> projects = new LinkedList<>(); for (AggregateCall aggCall : aggregate.getAggCallList()) { final SqlAggFunction aggregation = aggCall.getAggregation(); final SqlSplittableAggFunction splitter = Objects.requireNonNull( aggregation.unwrap(SqlSplittableAggFunction.class)); final RexNode singleton = splitter.singleton( rexBuilder, input.getRowType(), aggCall); projects.add(singleton); } final RelNode newInput = convert(input, aggregate.getTraitSet().simplify()); final RelBuilder relBuilder = call.builder(); relBuilder.push(newInput); if (!projects.isEmpty()) { projects.addAll(0, relBuilder.fields(aggregate.getGroupSet().asList())); relBuilder.project(projects); } else if (newInput.getRowType().getFieldCount() > aggregate.getRowType().getFieldCount()) { relBuilder.project(relBuilder.fields(aggregate.getGroupSet().asList())); } final RelNode newRel = relBuilder.build(); call.transformTo(newRel); }

Target:
public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final RelNode input = aggregate.getInput(); final RelMetadataQuery mq = call.getMetadataQuery(); if (!SqlFunctions.isTrue(mq.areColumnsUnique(input, aggregate.getGroupSet()))) { return; } final RelBuilder relBuilder = call.builder(); final RexBuilder rexBuilder = relBuilder.getRexBuilder(); final List<RexNode> projects = new ArrayList<>(); for (AggregateCall aggCall : aggregate.getAggCallList()) { final SqlAggFunction aggregation = aggCall.getAggregation(); if (aggregation.getKind() == SqlKind.SUM0) { return; } final SqlSplittableAggFunction splitter = Objects.requireNonNull( aggregation.unwrap(SqlSplittableAggFunction.class)); final RexNode singleton = splitter.singleton( rexBuilder, input.getRowType(), aggCall); projects.add(singleton); } final RelNode newInput = convert(input, aggregate.getTraitSet().simplify()); relBuilder.push(newInput); if (!projects.isEmpty()) { projects.addAll(0, relBuilder.fields(aggregate.getGroupSet().asList())); relBuilder.project(projects); } else if (newInput.getRowType().getFieldCount() > aggregate.getRowType().getFieldCount()) { relBuilder.project(relBuilder.fields(aggregate.getGroupSet().asList())); } call.transformTo(relBuilder.build()); }
Source:
default <U> Seq<U> flatMap(Function<? super Tuple2<K, V>, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return iterator().flatMap(mapper).toStream(); }

Target:
default <U> Seq<U> flatMap(Function<? super Tuple2<K, V>, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return (Seq<U>) iterator().flatMap(mapper).toStream(); }
Source:
private void endRequest(String requestId, Exception failure) { if (requestId != null) { Session session = null; List<RequestInterceptor> interceptors = getInterceptors(true); for (RequestInterceptor requestInterceptor : interceptors) { if (requestInterceptor != null) { try { requestInterceptor.onEnd(requestId, session, (failure == null), failure); } catch (RequestInterruptionException e) { log.warn("Attempt to stop request from ending by an exception from the interceptor ("+requestInterceptor+"), cannot stop requests from ending though so request end continues, this may be an error: " + e.getMessage()); } catch (Exception e) { log.warn("Request interceptor ("+requestInterceptor+") failed to execute on end ("+requestId+"): " + e.getMessage()); } } } } }

Target:
private void endRequest(String requestId, Exception failure) { if (requestId != null) { List<RequestInterceptor> interceptors = getInterceptors(true); for (RequestInterceptor requestInterceptor : interceptors) { if (requestInterceptor != null) { try { requestInterceptor.onEnd(requestId, (failure == null), failure); } catch (RequestInterruptionException e) { log.warn("Attempt to stop request from ending by an exception from the interceptor ("+requestInterceptor+"), cannot stop requests from ending though so request end continues, this may be an error: " + e.getMessage()); } catch (Exception e) { log.warn("Request interceptor ("+requestInterceptor+") failed to execute on end ("+requestId+"): " + e.getMessage()); } } } } }
Source:
public Response getResponse(String descriptorAbsolutePathString) throws IOException { Response response = new Response(); response.setClonedRepositoryAbsolutePath(descriptorAbsolutePathString); List<String> commandLineArgs = Arrays.asList("validate", "-l", descriptorAbsolutePathString); try { WomtoolMain.Termination termination = WomtoolMain .runWomtool(JavaConverters.collectionAsScalaIterableConverter(commandLineArgs).asScala().toSeq()); Option<String> stdout = termination.stdout(); String[] split = stdout.get().split(System.lineSeparator()); List<String> strings = new ArrayList<>(); Collections.addAll(strings, split); if (strings.get(0).equals("Success!") && strings.get(1).equals("List of Workflow dependencies is:")) { response.setValid(true); handleSuccessResponse(response, strings); return response; } else { response.setValid(false); throw new IOException(); } } catch (StackOverflowError e) { response.setValid(false); return response; } }

Target:
public static LanguageParsingResponse getResponse(String descriptorAbsolutePathString) { LanguageParsingResponse response = new LanguageParsingResponse(); response.setClonedRepositoryAbsolutePath(descriptorAbsolutePathString); List<String> commandLineArgs = Arrays.asList("validate", "-l", descriptorAbsolutePathString); try { WomtoolMain.Termination termination = WomtoolMain.runWomtool( JavaConverters.collectionAsScalaIterableConverter(commandLineArgs).asScala().toSeq()); Option<String> stdout = termination.stdout(); String[] split = stdout.get().split(System.lineSeparator()); List<String> strings = new ArrayList<>(); Collections.addAll(strings, split); VersionTypeValidation versionTypeValidation = new VersionTypeValidation(); if (strings.get(0).equals("Success!") && strings.get(1).equals("List of Workflow dependencies is:")) { versionTypeValidation.setValid(true); response.setVersionTypeValidation(versionTypeValidation); handleSuccessResponse(response, strings); } else { versionTypeValidation.setValid(false); response.setVersionTypeValidation(versionTypeValidation); } return response; } catch (StackOverflowError e) { VersionTypeValidation versionTypeValidation = new VersionTypeValidation(); versionTypeValidation.setValid(false); response.setVersionTypeValidation(versionTypeValidation); return response; } }
Source:
public XYPair getRightVector() { return new XYPair(this.x * (xRightInverted ? -1 : 1), this.y * (yRightInverted ? -1 : 1)); }

Target:
public XYPair getRightVector() { return new XYPair( this.rightJoystickAxis.x * (getRightStickXInversion() ? -1 : 1), this.rightJoystickAxis.y * (getRightStickYInversion() ? -1 : 1)); }
Source:
public ResponseEntity<Resources<Resource<Component>>> getComponents(@RequestParam(value = "name", required = false) String name, OAuth2Authentication oAuth2Authentication) { User user = restControllerHelper.getSw360UserFromAuthentication(oAuth2Authentication); List<Component> components = new ArrayList<>(); if ((name != null) && (!name.isEmpty())) { components.addAll(searchComponentByName(name, user)); } else { components.addAll(componentService.getComponentsForUser(user)); } List<Resource<Component>> componentResources = new ArrayList<>(); for (Component component : components) { component.setDescription(null); component.setType(null); component.setCreatedOn(null); component.setVendorNames(null); component.setReleaseIds(null); Resource<Component> componentResource = new Resource<>(component); componentResources.add(componentResource); } Resources<Resource<Component>> resources = new Resources<>(componentResources); return new ResponseEntity<>(resources, HttpStatus.OK); }

Target:
public ResponseEntity<Resources<Resource<Component>>> getComponents(@RequestParam(value = "name", required = false) String name, OAuth2Authentication oAuth2Authentication) { User user = restControllerHelper.getSw360UserFromAuthentication(oAuth2Authentication); List<Component> components = new ArrayList<>(); if ((name != null) && (!name.isEmpty())) { components.addAll(searchComponentByName(name)); } else { components.addAll(componentService.getComponentsForUser(user)); } List<Resource<Component>> componentResources = new ArrayList<>(); for (Component component : components) { component.setDescription(null); component.setType(null); component.setCreatedOn(null); component.setVendorNames(null); component.setReleaseIds(null); Resource<Component> componentResource = new Resource<>(component); componentResources.add(componentResource); } Resources<Resource<Component>> resources = new Resources<>(componentResources); return new ResponseEntity<>(resources, HttpStatus.OK); }
Source:
private List<BrickDetails> getBrickDetails(int size, int clientListSize, int memPoolSize) { ArrayList<BrickDetails> list = new ArrayList<BrickDetails>(); for(int i=0; i < size ; i++) { BrickDetails details = new BrickDetails(); BrickProperties props = new BrickProperties(); props.setBlockSize(blockSize); props.setPid(88888); props.setMntOptions("mntOption1"); details.setBrickProperties(props); details.setClients(getClientList(clientListSize)); details.setMemoryStatus(getMemoryStatus(memPoolSize)); list.add(details); } return list; }

Target:
private List<BrickDetails> getBrickDetails(int size, int clientListSize, int memPoolSize) { ArrayList<BrickDetails> list = new ArrayList<BrickDetails>(); for(int i=0; i < size ; i++) { BrickDetails details = new BrickDetails(); BrickProperties props = new BrickProperties(); props.setBlockSize(14556); props.setPid(88888); props.setMntOptions("rw"); details.setBrickProperties(props); details.setClients(getClientList(clientListSize)); details.setMemoryStatus(getMemoryStatus(memPoolSize)); list.add(details); } return list; }
Source:
public <T> ProxyableIteratorAssert<T> assertThat(Iterator<? extends T> actual) { return proxy(ProxyableIteratorAssert.class, Iterator.class, actual); }

Target:
public <T> IteratorAssert<T> assertThat(Iterator<? extends T> actual) { return proxy(IteratorAssert.class, Iterator.class, actual); }
Source:
public IBlockStateMatcher allowValuesForProperty(String name, String... values) { return null; }

Target:
public IBlockStateMatcher allowValuesForProperty(String name, String... values) { CraftTweakerAPI.logWarning("Cannot change allowed values for a compound blockstate matcher"); return this; }
Source:
private synchronized void purge() { List<Entry> entriesToPurge = new ArrayList<>(map.values()); Collections.sort(entriesToPurge, Comparator.comparingLong(o -> -o.lastAccessed)); for (int index = purgeSize; index < entriesToPurge.size(); index++) { map.remove(entriesToPurge.get(index).key); } }

Target:
private void purge() { if (lock.tryLock()) { try { List<Entry> entriesToPurge = new ArrayList<>(map.values()); for (Entry e : entriesToPurge) { e.copyAccessTime(); } Collections.sort(entriesToPurge, Comparator.comparingLong(o -> -o.lastAccessedSorting)); for (int index = purgeSize; index < entriesToPurge .size(); index++) { map.remove(entriesToPurge.get(index).key); } } finally { lock.unlock(); } } }
Source:
private void drawInputLine(UiDrawer uiDrawer, float textX) { StringBuilder stringBuilder = new StringBuilder(); int width = 0; for (char c : inputLine.reverse().toString().toCharArray()) { try { width += (c == ' ' ? 3 : 1) * font.getData().getGlyph(c).width; if (width > MAX_WIDTH_OF_LINE) { break; } stringBuilder.append(c); } catch (NullPointerException e) { inputLine.deleteCharAt(0); } } uiDrawer.drawString(stringBuilder.reverse().toString(), textX, getLineY(20.666f), 0.5f, UiDrawer.TextAlignment.LEFT, false, Color.WHITE); inputLine.reverse(); }

Target:
private void drawInputLine(UiDrawer uiDrawer, float textX) { StringBuilder stringBuilder = new StringBuilder(); if (System.currentTimeMillis() % 2000 > 1000) { stringBuilder.append('_'); } int width = font.getData().getGlyph('_').width; for (char c : inputLine.reverse().toString().toCharArray()) { final BitmapFont.Glyph glyph = font.getData().getGlyph(c); if (glyph != null) { width += (c == ' ' ? 3 : 1) * glyph.width; if (width > MAX_WIDTH_OF_LINE) { break; } stringBuilder.append(c); } else { inputLine.deleteCharAt(0); } } uiDrawer.drawString(stringBuilder.reverse().toString(), textX, getLineY(INPUT_LINE_Y), 0.5f, UiDrawer.TextAlignment.LEFT, false, Color.WHITE); inputLine.reverse(); }
Source:
public static void main(String[] args) throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) .marshaller(ProtoStreamMarshaller.class); RemoteCacheManager client = new RemoteCacheManager(builder.build()); RemoteCache<String, Person> personsCache = client.administration().getOrCreateCache("people", "default"); Map<String, Person> persons = Stream.of(new Object[][]{ {"1", new Person("Oihana", "Rossignol", 2016, "Paris")}, {"2", new Person("Elaia", "Rossignol", 2018, "Paris")}, {"3", new Person("Yago", "Steiner", 2013, "Saint-Mandé")}, {"4", new Person("Alberto", "Steiner", 2016, "Paris")}}) .collect(Collectors.toMap(data -> (String) data[0], data -> (Person) data[1])); addPersonSchema(client); personsCache.putAll(persons); QueryFactory queryFactory = Search.getQueryFactory(personsCache); Query query = queryFactory.create("FROM tutorial.Person p where p.lastName = :lastName"); query.setParameter("lastName", "Rossignol"); List<Person> rossignols = query.list(); System.out.println(rossignols); client.stop(); }

Target:
public static void main(String[] args) throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT) .marshaller(ProtoStreamMarshaller.class); RemoteCacheManager client = new RemoteCacheManager(builder.build()); RemoteCache<String, Person> personsCache = client.administration().getOrCreateCache("people", "default"); Map<String, Person> persons = new HashMap<>(); persons.put("1", new Person("Oihana", "Rossignol", 2016, "Paris")); persons.put("2", new Person("Elaia", "Rossignol", 2018, "Paris")); persons.put("3", new Person("Yago", "Steiner", 2013, "Saint-Mandé")); persons.put("4", new Person("Alberto", "Steiner", 2016, "Paris")); addPersonSchema(client); personsCache.putAll(persons); QueryFactory queryFactory = Search.getQueryFactory(personsCache); Query query = queryFactory.create("FROM tutorial.Person p where p.lastName = :lastName"); query.setParameter("lastName", "Rossignol"); List<Person> rossignols = query.list(); System.out.println(rossignols); client.stop(); }
Source:
public ExternalIdBundle withoutScheme(ExternalScheme scheme) { Set<ExternalId> ids = new HashSet<>(externalIds.size()); for (ExternalId id : externalIds) { if (id.isScheme(scheme) == false) { ids.add(id); } } return create(ids); }

Target:
public ExternalIdBundle withoutScheme(ExternalScheme scheme) { Set<ExternalId> ids = externalIds.stream() .filter(id -> id.isNotScheme(scheme)) .collect(Collectors.toSet()); return create(ids); }
Source:
protected boolean isShowingOnlyAvailableOffline() { Bundle args = getArguments(); return ((args != null) && args.getBoolean(ARG_ONLY_AVAILABLE_OFFLINE, false)); }

Target:
boolean isShowingOnlyAvailableOffline() { Bundle args = getArguments(); return ((args != null) && args.getBoolean(ARG_ONLY_AVAILABLE_OFFLINE, false)); }
Source:
public void configureForMapReduce(Job job, PType<?> ptype, Path outputPath, String name) { Converter converter = getConverter(ptype); Class<?> keyClass = converter.getKeyClass(); Class<?> valueClass = Void.class; if (name == null) { job.setOutputKeyClass(keyClass); job.setOutputValueClass(valueClass); } else { CrunchOutputs.addNamedOutput(job, name, formatBundle, keyClass, valueClass); } job.setOutputFormatClass(formatBundle.getFormatClass()); formatBundle.configure(job.getConfiguration()); }

Target:
public void configureForMapReduce(Job job, PType<?> ptype, Path outputPath, String name) { Preconditions.checkNotNull(name, "Output name should not be null"); Converter converter = getConverter(ptype); Class<?> keyClass = converter.getKeyClass(); Class<?> valueClass = Void.class; CrunchOutputs.addNamedOutput(job, name, formatBundle, keyClass, valueClass); job.setOutputFormatClass(formatBundle.getFormatClass()); formatBundle.configure(job.getConfiguration()); }
Source:
MolgenisValidationException translateValueTooLongViolation() { ConstraintViolation constraintViolation = new ConstraintViolation("One of the values being added is too long."); return new MolgenisValidationException(singleton(constraintViolation)); }

Target:
MolgenisValidationException translateValueTooLongViolation() { ConstraintViolation constraintViolation = new ConstraintViolation(VALUE_TOO_LONG_MSG); return new MolgenisValidationException(singleton(constraintViolation)); }
Source:
public void testsHeaderNotAvailable() throws IOException { MatcherAssert.assertThat( new RqFake( Arrays.asList( "GET /f?a=3", "Host: www.example.com", "Accept: text/json" ), "" ), new HmRqHeader( Matchers.not( Matchers.hasEntry("host", "fake.org") ) ) ); }

Target:
public void testsHeaderNotAvailable() throws Exception { MatcherAssert.assertThat( new RqFake( Arrays.asList( "GET /f?a=3", "Host: www.example.com", "Accept: text/json" ), "" ), new HmRqHeader( Matchers.not( Matchers.hasEntry("host", "fake.org") ) ) ); }
Source:
public Object[] factory() { return new Object[] { new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OBJECT), new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OFF_HEAP) }; }

Target:
public Object[] factory() { return new Object[] { new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.BINARY), new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OBJECT), new ContextAffectsTransactionReadCommittedTest().withStorage(StorageType.OFF_HEAP) }; }
Source:
synchronized void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); log.debug("{}updating builder with topic(s) with possible matching regex subscription(s)", logPrefix, subscriptionUpdates.size()); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); }

Target:
synchronized void updateSubscribedTopics(final Set<String> topics, final String logPrefix) { log.debug("{}found topics possibly matching subscription", logPrefix, topics.size()); subscriptionUpdates.clear(); subscriptionUpdates.addAll(topics); setRegexMatchedTopicsToSourceNodes(); setRegexMatchedTopicToStateStore(); }
Source:
public int hashCode() { int hash = 7; hash = 71 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; }

Target:
public int hashCode() { return name.hashCode(); }
Source:
private void updateCachedList(List list, List newList, String repoId){ HashMap<String, HashSet> changes = CollectionUtilities.getChangesToList(list, newList); HashSet removed = changes.get(CollectionUtilities.REMOVED_TAG); Platform.runLater(new Runnable() { @Override public void run() { list.removeAll(removed); Listable listItem = (Listable)newList.get(0); if (listItem.getClass() == TurboMilestone.class) { logNumOfUpdates(newList, "milestone(s)"); } else if (listItem.getClass() == TurboLabel.class) { logNumOfUpdates(newList, "label(s)"); } else if (listItem.getClass() == TurboUser.class) { logNumOfUpdates(newList, "collaborator(s)"); } ArrayList<Object> buffer = new ArrayList<>(); for (Object item : newList) { int index = list.indexOf(item); if(index != -1){ Listable old = (Listable)list.get(index); old.copyValues(item); }else{ buffer.add(item); } } list.addAll(buffer); dcHandler.writeToFile(repoId, issuesETag, collabsETag, labelsETag, milestonesETag, issueCheckTime, collaborators, labels, milestones, issues); } private void logNumOfUpdates(List newList, String type) { logger.info("Retrieved " + newList.size() + " updated " + type + " since last sync"); } }); }

Target:
private void updateCachedList(List list, List newList, String repoId){ HashMap<String, HashSet> changes = CollectionUtilities.getChangesToList(list, newList); HashSet removed = changes.get(CollectionUtilities.REMOVED_TAG); Platform.runLater(new Runnable() { @Override public void run() { list.removeAll(removed); Listable listItem = (Listable)newList.get(0); if (listItem instanceof TurboMilestone) { logNumOfUpdates(newList, "milestone(s)"); } else if (listItem instanceof TurboLabel) { logNumOfUpdates(newList, "label(s)"); } else if (listItem instanceof TurboUser) { logNumOfUpdates(newList, "collaborator(s)"); } ArrayList<Object> buffer = new ArrayList<>(); for (Object item : newList) { int index = list.indexOf(item); if(index != -1){ Listable old = (Listable)list.get(index); old.copyValues(item); }else{ buffer.add(item); } } list.addAll(buffer); dcHandler.writeToFile(repoId, issuesETag, collabsETag, labelsETag, milestonesETag, issueCheckTime, collaborators, labels, milestones, issues); } private void logNumOfUpdates(List newList, String type) { logger.info("Retrieved " + newList.size() + " updated " + type + " since last sync"); } }); }
Source:
public void testContainerSortOnId() { PackingPlan packingPlan = getFirstFitDecreasingPackingPlan(topology); Assert.assertEquals(packingPlan.getContainers().size(), 2); Assert.assertEquals((long) packingPlan.getInstanceCount(), totalInstances); AssertPacking.assertNumInstances(packingPlan.getContainers(), BOLT_NAME, boltParallelism); AssertPacking.assertNumInstances(packingPlan.getContainers(), SPOUT_NAME, spoutParallelism); PackingPlan.ContainerPlan[] currentContainers = packingPlan.getContainers().toArray( new PackingPlan.ContainerPlan[1]); Assert.assertEquals(currentContainers.length, packingPlan.getContainers().size()); for (int i = 0; i < currentContainers.length; i++) { Assert.assertEquals((currentContainers[i]).getId(), i + 1); } }

Target:
public void testContainerSortOnId() { Integer[] containerIds = {5, 4, 1, 2, 3}; Integer[] instanceIds = {1, 2, 3}; Set<PackingPlan.ContainerPlan> containers = generateContainers(containerIds, instanceIds); PackingPlan.ContainerPlan[] currentContainers = PackingUtils.sortOnContainerId(containers); Assert.assertEquals(containerIds.length, currentContainers.length); for (int i = 0; i < currentContainers.length; i++) { Assert.assertEquals((currentContainers[i]).getId(), i + 1); } }