auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public static void setEnvironmentVariables(String key, String value) throws IllegalAccessException, <END> NoSuchFieldException, ClassNotFoundException { Map<String, String> newEnv = new HashMap<>(); newEnv.put(key, value); setEnvironmentVariables(newEnv); }</code><technical_language>this is public static? this? if this is this class, private</technical_language>

Target:
private void setEnvironmentVariables(String key, String value) throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException { Map<String, String> newEnv = new HashMap<>(); newEnv.put(key, value); setEnvironmentVariables(newEnv); }
Source:
<code>public void remove(E mob) { checkArgument(mob.getState() == EntityState.ACTIVE, "state != ACTIVE"); checkArgument(mob.getIndex() != -1, "index == -1"); <START> indexes.offer(mob.getIndex()); <END> mob.setState(EntityState.INACTIVE); mobs[mob.getIndex()] = null; mob.setIndex(-1); size--; }</code><technical_language>Add/offer for ArrayDeque well</technical_language>

Target:
public void remove(E mob) { checkArgument(mob.getState() == EntityState.ACTIVE, "state != ACTIVE"); checkArgument(mob.getIndex() != -1, "index == -1"); indexes.add(mob.getIndex()); mob.setState(EntityState.INACTIVE); mobs[mob.getIndex()] = null; mob.setIndex(-1); size--; }
Source:
<code>public List<GrantedAuthority> getGrantedAuthorities(Context context, EPerson eperson) { List<GrantedAuthority> authorities = new LinkedList<>(); if (eperson != null) { boolean isAdmin = false; boolean isCommunityAdmin = false; boolean isColectionAdmin = false; try { isAdmin = authorizeService.isAdmin(context, eperson); isCommunityAdmin = authorizeService.isCommunityAdmin(context, eperson); <START> isColectionAdmin = authorizeService.isCollectionAdmin(context, eperson); <END> } catch (SQLException e) { log.error("SQL error while checking for admin rights", e); } if (isAdmin) { authorities.add(new SimpleGrantedAuthority(ADMIN_GRANT)); } else if ((isCommunityAdmin && AuthorizeUtil.canCommunityAdminManageAccounts()) || (isColectionAdmin && AuthorizeUtil.canCollectionAdminManageAccounts())) { authorities.add(new SimpleGrantedAuthority(ACCOUNT_ADMIN_GRANT)); } authorities.add(new SimpleGrantedAuthority(AUTHENTICATED_GRANT)); } return authorities; }</code><technical_language>Small typo in variable name, "isCollectionAdmin"</technical_language>

Target:
public List<GrantedAuthority> getGrantedAuthorities(Context context, EPerson eperson) { List<GrantedAuthority> authorities = new LinkedList<>(); if (eperson != null) { boolean isAdmin = false; boolean isCommunityAdmin = false; boolean isCollectionAdmin = false; try { isAdmin = authorizeService.isAdmin(context, eperson); isCommunityAdmin = authorizeService.isCommunityAdmin(context, eperson); isCollectionAdmin = authorizeService.isCollectionAdmin(context, eperson); } catch (SQLException e) { log.error("SQL error while checking for admin rights", e); } if (isAdmin) { authorities.add(new SimpleGrantedAuthority(ADMIN_GRANT)); } else if ((isCommunityAdmin && AuthorizeUtil.canCommunityAdminManageAccounts()) || (isCollectionAdmin && AuthorizeUtil.canCollectionAdminManageAccounts())) { authorities.add(new SimpleGrantedAuthority(ACCOUNT_ADMIN_GRANT)); } authorities.add(new SimpleGrantedAuthority(AUTHENTICATED_GRANT)); } return authorities; }
Source:
<code>public void deployContrib(FeaturesRunner runner) throws Exception { String contribName = null; switch (directoryType) { case DIRECTORY_VCS: contribName = "OSGI-INF/test-directory-sql-contrib.xml"; break; case DIRECTORY_MONGODB: contribName = "OSGI-INF/test-directory-mongodb-contrib.xml"; break; case DIRECTORY_LDAP: contribName = "OSGI-INF/test-directory-ldap-contrib.xml"; break; default: break; } RuntimeHarness harness = runner.getFeature(RuntimeFeature.class).getHarness(); <START> harness.deployContrib("org.nuxeo.ecm.directory.tests",contribName); <END> }</code><technical_language>Add a space ,</technical_language>

Target:
public void deployContrib(FeaturesRunner runner) throws Exception { String contribName; switch (directoryType) { case DIRECTORY_SQL: contribName = "OSGI-INF/test-directory-sql-contrib.xml"; break; case DIRECTORY_MONGODB: contribName = "OSGI-INF/test-directory-mongodb-contrib.xml"; break; default: throw new NuxeoException("Contribution for testing directories cannot be null"); } RuntimeHarness harness = runner.getFeature(RuntimeFeature.class).getHarness(); harness.deployContrib("org.nuxeo.ecm.directory.tests", contribName); }
Source:
<code>protected void validateTieredReplicants(Map<String, Integer> tieredReplicants){ <START> for(Map.Entry<String, Integer> entry: tieredReplicants.entrySet()){ <END> if(entry.getValue() < 0) throw new IllegalArgumentException("Replicant value cannot be less than 0"); } }</code><technical_language>formatting issues</technical_language>

Target:
protected void validateTieredReplicants(Map<String, Integer> tieredReplicants){ for (Map.Entry<String, Integer> entry: tieredReplicants.entrySet()) { if (entry.getValue() < 0) throw new IAE("Replicant value [%d] is less than 0, which is not allowed", entry.getValue()); } }
Source:
<code>public static void main(String[] args) throws Exception { String accountName = getAccountName(); String accountKey = getAccountKey(); SharedKeyCredential credential = new SharedKeyCredential(accountName, accountKey); String endPoint = String.format(Locale.ROOT, "<LINK_0>", accountName); StorageClient storageClient = StorageClient.storageClientBuilder().endpoint(endPoint).credential(credential).buildClient(); ContainerClient containerClient = storageClient.getContainerClient("myjavacontainerparallelupload" + System.currentTimeMillis()); containerClient.create(); String filename = "BigFile.bin"; BlockBlobClient blobClient = containerClient.getBlockBlobClient(filename); File largeFile = createTempEmptyFile(filename); File downloadFile = createTempEmptyFile("downloadFile.bin"); <START> Long fileSize = 100 * 1024 * 1024L; <END> createTempFileWithFileSize(largeFile, fileSize); blobClient.uploadFromFile(largeFile.getPath()); blobClient.downloadToFile(downloadFile.getPath()); if (Files.exists(downloadFile.toPath()) && Files.exists(largeFile.toPath())) { checkTwoFilesAreTheSame(largeFile, downloadFile); System.out.println("The file we upload is the same as the one we download."); } else { throw new RuntimeException("Did not find the upload or download file."); } containerClient.delete(); Files.deleteIfExists(largeFile.toPath()); Files.deleteIfExists(downloadFile.toPath()); }</code><technical_language>examples long primitive instead of Long object. API Long object Long</technical_language>

Target:
public static void main(String[] args) throws Exception { String accountName = getAccountName(); String accountKey = getAccountKey(); SharedKeyCredential credential = new SharedKeyCredential(accountName, accountKey); String endPoint = String.format(Locale.ROOT, "<LINK_0>", accountName); StorageClient storageClient = StorageClient.storageClientBuilder().endpoint(endPoint).credential(credential).buildClient(); ContainerClient containerClient = storageClient.getContainerClient("myjavacontainerparallelupload" + System.currentTimeMillis()); containerClient.create(); String filename = "BigFile.bin"; BlockBlobClient blobClient = containerClient.getBlockBlobClient(filename); File largeFile = createTempEmptyFile(filename); File downloadFile = createTempEmptyFile("downloadFile.bin"); long fileSize = 100 * 1024 * 1024L; createTempFileWithFileSize(largeFile, fileSize); blobClient.uploadFromFile(largeFile.getPath()); blobClient.downloadToFile(downloadFile.getPath()); if (Files.exists(downloadFile.toPath()) && Files.exists(largeFile.toPath())) { checkTwoFilesAreTheSame(largeFile, downloadFile); System.out.println("The file we upload is the same as the one we download."); } else { throw new RuntimeException("Did not find the upload or download file."); } containerClient.delete(); Files.deleteIfExists(largeFile.toPath()); Files.deleteIfExists(downloadFile.toPath()); }
Source:
<code>public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://myhentaicomics.com/index.php/([a-zA-Z0-9-]*)$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } <START> throw new MalformedURLException("Expected imgur.com URL format: " + <END> "myhentaicomics.com/index.php/albumName - got " + url + " instead"); }</code><technical_language>Replace imgur.com</technical_language>

Target:
public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://myhentaicomics.com/index.php/([a-zA-Z0-9-]*)/?$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } Pattern pa = Pattern.compile("^https?://myhentaicomics.com/index.php/search\\?q=([a-zA-Z0-9-]*)([a-zA-Z0-9=&]*)?$"); Matcher ma = pa.matcher(url.toExternalForm()); if (ma.matches()) { return ma.group(1); } Pattern pat = Pattern.compile("^<LINK_0>[0-9]*)/?([a-zA-Z%0-9+\\?=:]*)?$"); Matcher mat = pat.matcher(url.toExternalForm()); if (mat.matches()) { return mat.group(1); } throw new MalformedURLException("Expected myhentaicomics.com URL format: " + "myhentaicomics.com/index.php/albumName - got " + url + " instead"); }
Source:
<code>private void doWork() { ArrayList<TimeRequest> request = new ArrayList<>(); while (true) { try { request.clear(); TimeRequest trh = null; while(trh == null){ if(closed.get()){ return; } trh = queue.poll(1, TimeUnit.SECONDS); } request.add(trh); queue.drainTo(request); long start; while (true) { try { String currentLeaderId; OracleService.Client localClient; synchronized (this) { currentLeaderId = getOracle(); localClient = client; } Context timerContext = responseTimer.time(); start = localClient.getTimestamps(env.getFluoApplicationID(), request.size()); String leaderId = getOracle(); if(leaderId != null && !leaderId.equals(currentLeaderId)) { reconnect(); continue; } stampsHistogram.update(request.size()); timerContext.close(); break; } catch (TTransportException tte) { log.info("Oracle connection lost. Retrying..."); reconnect(); } catch (TException e) { log.error("TException occurred in doWork() method", e); } } for (int i = 0; i < request.size(); i++) { TimeRequest tr = request.get(i); tr.timestamp.set(start + i); tr.cdl.countDown(); } } catch (InterruptedException e) { if(!closed.get()){ <START> log.error("InterruptedException occurred in doWork() method", e); <END> } } catch (Exception e) { log.error("Exception occurred in doWork() method", e); } } }</code><technical_language>log debug if closed</technical_language>

Target:
private void doWork() { ArrayList<TimeRequest> request = new ArrayList<>(); while (true) { try { request.clear(); TimeRequest trh = null; while(trh == null){ if(closed.get()){ return; } trh = queue.poll(1, TimeUnit.SECONDS); } request.add(trh); queue.drainTo(request); long start; while (true) { try { String currentLeaderId; OracleService.Client localClient; synchronized (this) { currentLeaderId = getOracle(); localClient = client; } Context timerContext = responseTimer.time(); start = localClient.getTimestamps(env.getFluoApplicationID(), request.size()); String leaderId = getOracle(); if(leaderId != null && !leaderId.equals(currentLeaderId)) { reconnect(); continue; } stampsHistogram.update(request.size()); timerContext.close(); break; } catch (TTransportException tte) { log.info("Oracle connection lost. Retrying..."); reconnect(); } catch (TException e) { log.error("TException occurred in doWork() method", e); } } for (int i = 0; i < request.size(); i++) { TimeRequest tr = request.get(i); tr.timestamp.set(start + i); tr.cdl.countDown(); } } catch (InterruptedException e) { if(!closed.get()){ log.error("InterruptedException occurred in doWork() method", e); } else { log.debug("InterruptedException occurred in doWork() method", e); } } catch (Exception e) { log.error("Exception occurred in doWork() method", e); } } }
Source:
<code>public Macro<?> getMacro(MacroId macroId) throws MacroLookupException { String macroHint = macroId.toString(); ComponentManager cm = this.componentManager.get(); try { if (cm.hasComponent(Macro.class, macroHint)) { return cm.getInstance(Macro.class, macroHint); } else { if (cm.hasComponent(Macro.class, macroId.getId())) { return cm.getInstance(Macro.class, macroId.getId()); } throw new MacroNotFoundException(String.format("No macro [%s] could be found.", macroId.toString())); } } catch (ComponentLookupException e) { throw new MacroLookupException(String.format("Macro [%s] failed to be instantiated" <START> + ".", macroId.toString()), e); <END> } }</code><technical_language>putting "." line</technical_language>

Target:
public Macro<?> getMacro(MacroId macroId) throws MacroLookupException { String macroHint = macroId.toString(); ComponentManager cm = this.componentManager.get(); try { if (cm.hasComponent(Macro.class, macroHint)) { return cm.getInstance(Macro.class, macroHint); } else { if (cm.hasComponent(Macro.class, macroId.getId())) { return cm.getInstance(Macro.class, macroId.getId()); } throw new MacroNotFoundException(String.format("No macro [%s] could be found.", macroId.toString())); } } catch (ComponentLookupException e) { throw new MacroLookupException(String.format("Macro [%s] failed to be instantiated." + , macroId.toString()), e); } }
Source:
<code>public String getPackage() { if (!actualName.contains(File.separator)){ return null; } <START> return getActualName().substring(0, getActualName().lastIndexOf(File.separator) + 1) <END> .replaceAll(File.separator, "\\."); }</code><technical_language>file separator? internal class name "/"</technical_language>

Target:
public String getPackage() { if (!actualName.contains(File.separator)){ return null; } return getActualName().substring(0, getActualName().lastIndexOf("/") + 1) .replace("/", "\\."); }
Source:
<code>private void handleDestDisk() { if (getParameters().getLiveDiskMigrateStage() != LiveDiskMigrateStage.IMAGE_PLACEHOLDER_CREATION && getParameters().getLiveDiskMigrateStage() != LiveDiskMigrateStage.SOURCE_IMAGE_DELETION) { <START> if (Guid.Empty.equals(getParameters().getVdsId()) && <END> getParameters().getLiveDiskMigrateStage() != LiveDiskMigrateStage.VM_REPLICATE_DISK_FINISH) { log.error("Failed during live storage migration of disk '{}' of vm '{}', as the vm is not running" + " on any host not attempting to end the replication before the target disk deletion", getParameters().getImageGroupID(), getParameters().getVmId()); } else { log.error("Failed during live storage migration of disk '{}' of vm '{}', attempting to end " + "replication" + " before deleting the target disk", getParameters().getImageGroupID(), getParameters().getVmId()); try { replicateDiskFinish(getParameters().getSourceStorageDomainId(), getParameters().getSourceStorageDomainId()); } catch (Exception e) { log.error("Replication end of disk '{}' in vm '{}' back to the source failed, skipping deletion of " + "the target disk", getParameters().getImageGroupID(), getParameters().getVmId()); return; } } log.error("The target of disk '{}' of vm '{}' isn't used, attempting to delete it", getParameters().getImageGroupID(), getParameters().getVmId()); LiveStorageMigrationHelper.removeImage(this, getParameters().getTargetStorageDomainId(), getParameters() .getImageGroupID(), getParameters().getDestinationImageId(), AuditLogType .USER_MOVE_IMAGE_GROUP_FAILED_TO_DELETE_DST_IMAGE); } }</code><technical_language>please re-format changes</technical_language>

Target:
private void handleDestDisk() { if (getParameters().getLiveDiskMigrateStage() != LiveDiskMigrateStage.IMAGE_PLACEHOLDER_CREATION && getParameters().getLiveDiskMigrateStage() != LiveDiskMigrateStage.SOURCE_IMAGE_DELETION) { if (Guid.Empty.equals(getParameters().getVdsId())) { log.error("Failed during live storage migration of disk '{}' of vm '{}', as the vm is not running" + " on any host not attempting to end the replication before the target disk deletion", getParameters().getImageGroupID(), getParameters().getVmId()); } else { log.error("Failed during live storage migration of disk '{}' of vm '{}', attempting to end " + "replication before deleting the target disk", getParameters().getImageGroupID(), getParameters().getVmId()); try { replicateDiskFinish(getParameters().getSourceStorageDomainId(), getParameters().getSourceStorageDomainId()); } catch (Exception e) { log.error("Replication end of disk '{}' in vm '{}' back to the source failed, skipping deletion of " + "the target disk", getParameters().getImageGroupID(), getParameters().getVmId()); return; } } log.error("The target of disk '{}' of vm '{}' isn't used, attempting to delete it", getParameters().getImageGroupID(), getParameters().getVmId()); LiveStorageMigrationHelper.removeImage(this, getParameters().getTargetStorageDomainId(), getParameters() .getImageGroupID(), getParameters().getDestinationImageId(), AuditLogType .USER_MOVE_IMAGE_GROUP_FAILED_TO_DELETE_DST_IMAGE); } }
Source:
<code>private static Duration getStateTransferTimeoutEstimate(CorfuRuntime runtime) { Token trimMark = runtime.getAddressSpaceView().getTrimMark(); long tail = runtime.getAddressSpaceView().getAllTails().getLogTail(); long rangeToReplicate = tail - trimMark.getSequence(); long numSections = rangeToReplicate / runtime.getParameters().getBulkReadSize(); long rpcTimeout = (long) (runtime.getParameters().getRequestTimeout().toMillis() * 1.5); long timeoutInMs = Math.max(DEFAULT_HEAL_TIMEOUT.toMillis(), numSections * rpcTimeout); return Duration.ofMillis(timeoutInMs); <START> } <END></code><technical_language>add a note potentially collect metrics in future? give some hints state transfer happens, adjustment of bulk read size value. Also, add a trace log this data, right? in case of analyzing performance this a direct of visualizing chunks of data transferred correlation other metrics</technical_language>

Target:
private static Duration getStateTransferTimeoutEstimate(CorfuRuntime runtime) { Token trimMark = runtime.getAddressSpaceView().getTrimMark(); long tail = runtime.getAddressSpaceView().getAllTails().getLogTail(); long rangeToReplicate = tail - trimMark.getSequence(); long numSections = rangeToReplicate / runtime.getParameters().getBulkReadSize(); long rpcTimeout = (long) (runtime.getParameters().getRequestTimeout().toMillis() * TIMEOUT_MULTIPLICATIVE_FACTOR); long timeoutInMs = Math.max(DEFAULT_HEAL_TIMEOUT.toMillis(), numSections * rpcTimeout); return Duration.ofMillis(timeoutInMs); }
Source:
<code><START> private static void checkExceptions(DataTable dataTable, PinotSplit split) <END> { Map<String, String> metadata = dataTable.getMetadata(); List<String> exceptions = new ArrayList<>(); metadata.forEach((k, v) -> { if (k.startsWith(DataTable.EXCEPTION_METADATA_KEY)) { exceptions.add(v); } }); if (!exceptions.isEmpty()) { throw new PinotException(PinotErrorCode.PINOT_EXCEPTION, split.getSegmentPql(), String.format("Encountered %d pinot exceptions for split %s: %s", exceptions.size(), split, exceptions)); } int columnsExpected = split.getExpectedColumnHandles().size(); int columnsActual = dataTable.getDataSchema().size(); if (columnsActual != columnsExpected) { throw new PinotException(PinotErrorCode.PINOT_EXCEPTION, split.getSegmentPql(), String.format( "Expected pinot to contain %d columns but got %d: %s", columnsExpected, columnsActual, dataTable.getDataSchema())); } }</code><technical_language>move .stream() previous line</technical_language>

Target:
private static void checkExceptions(DataTable dataTable, PinotSplit split) { Map<String, String> metadata = dataTable.getMetadata(); List<String> exceptions = new ArrayList<>(); metadata.forEach((k, v) -> { if (k.startsWith(DataTable.EXCEPTION_METADATA_KEY)) { exceptions.add(v); } }); if (!exceptions.isEmpty()) { throw new PinotException( PINOT_EXCEPTION, split.getSegmentPql(), String.format("Encountered %d pinot exceptions for split %s: %s", exceptions.size(), split, exceptions)); } int numColumnsExpected = split.getExpectedColumnHandles().size(); int numColumnsActual = dataTable.getDataSchema().size(); if (numColumnsActual != numColumnsExpected) { throw new PinotException( PINOT_EXCEPTION, split.getSegmentPql(), String.format("Expected pinot to contain %d columns but got %d: %s", numColumnsExpected, numColumnsActual, dataTable.getDataSchema())); } }
Source:
<code>public ChatPrefs() { <START> ukTime = new SimpleStringProperty(TimeInfo.AUTO.getDisplayName()); <END> maxMessages = new SimpleIntegerProperty(500); zoom = new SimpleDoubleProperty(1); learnedAutoComplete = new SimpleBooleanProperty(false); previewImageUrls = new SimpleBooleanProperty(true); hideFoeMessages = new SimpleBooleanProperty(true); channelTabScrollPaneWidth = new SimpleIntegerProperty(250); userToColor = new SimpleMapProperty<>(FXCollections.observableHashMap()); chatColorMode = new SimpleObjectProperty<>(CUSTOM); idleThreshold = new SimpleIntegerProperty(10); }</code><technical_language>Preferences store display name, technical names (in this AUTO.name())</technical_language>

Target:
public ChatPrefs() { timeFormat = new SimpleObjectProperty<>(TimeInfo.AUTO); maxMessages = new SimpleIntegerProperty(500); zoom = new SimpleDoubleProperty(1); learnedAutoComplete = new SimpleBooleanProperty(false); previewImageUrls = new SimpleBooleanProperty(true); hideFoeMessages = new SimpleBooleanProperty(true); channelTabScrollPaneWidth = new SimpleIntegerProperty(250); userToColor = new SimpleMapProperty<>(FXCollections.observableHashMap()); chatColorMode = new SimpleObjectProperty<>(CUSTOM); idleThreshold = new SimpleIntegerProperty(10); }
Source:
<code>public static org.ovirt.engine.core.common.job.Step map(Step step, org.ovirt.engine.core.common.job.Step entity) { org.ovirt.engine.core.common.job.Step target = entity != null ? entity : new org.ovirt.engine.core.common.job.Step(); <START> target.setId(new Guid(step.getId())); <END> if (step.isSetParentStep()) { target.setParentStepId(Guid.createGuidFromString(step.getParentStep().getId())); } target.setJobId(GuidUtils.asGuid(step.getJob().getId())); if (step.isSetType()) { StepEnum type = StepEnum.fromValue(step.getType()); if (type != null) { target.setStepType(map(type)); } } if (step.isSetDescription()) { target.setDescription(step.getDescription()); } if (step.isSetNumber()) { target.setStepNumber(step.getNumber()); } if (step.isSetStatus()) { target.setStatus(JobMapper.map(step.getStatus(), null)); } target.setStartTime(step.isSetStartTime() ? step.getStartTime().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setEndTime(step.isSetEndTime() ? step.getEndTime().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setExternal(step.isSetExternal() ? step.isExternal() : true); return target; }</code><technical_language>GuidUtils.asGuid() formats BAD_REQUEST format exception, while new Guid() throws runtime exception</technical_language>

Target:
public static org.ovirt.engine.core.common.job.Step map(Step step, org.ovirt.engine.core.common.job.Step entity) { org.ovirt.engine.core.common.job.Step target = entity != null ? entity : new org.ovirt.engine.core.common.job.Step(); target.setId(new Guid(step.getId())); if (step.isSetParentStep()) { target.setParentStepId(GuidUtils.asGuid(step.getParentStep().getId())); } target.setJobId(GuidUtils.asGuid(step.getJob().getId())); if (step.isSetType()) { StepEnum type = StepEnum.fromValue(step.getType()); if (type != null) { target.setStepType(map(type)); } } if (step.isSetDescription()) { target.setDescription(step.getDescription()); } if (step.isSetNumber()) { target.setStepNumber(step.getNumber()); } if (step.isSetStatus()) { target.setStatus(JobMapper.map(step.getStatus(), null)); } target.setStartTime(step.isSetStartTime() ? step.getStartTime().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setEndTime(step.isSetEndTime() ? step.getEndTime().toGregorianCalendar().getTime() : new Date((Calendar.getInstance().getTimeInMillis()))); target.setExternal(step.isSetExternal() ? step.isExternal() : true); return target; }
Source:
<code>public void refreshAccessToken() { AccessTokenDTO refreshedToken = callConcurEndpoint( <START> this::callRefreshAccessTokenEndpoint, AccessTokenDTO.class); <END> webServiceCredentialService.updateWebServiceCredentialValue(ConcurConstants.CONCUR_ACCESS_TOKEN_EXPIRATION_DATE, refreshedToken.getExpirationDate()); }</code><technical_language>Similar thought adding clarity, move "this::CallRequestAccessTokenEndpoint" a variable: Function<Client, Response> endpointCaller</technical_language>

Target:
public void refreshAccessToken() { AccessTokenDTO refreshedToken = callConcurEndpoint( this::buildRefreshAccessTokenClientRequest, AccessTokenDTO.class); webServiceCredentialService.updateWebServiceCredentialValue(ConcurConstants.CONCUR_ACCESS_TOKEN_EXPIRATION_DATE, refreshedToken.getExpirationDate()); }
Source:
<code>public OperationStepHandler apply(OperationStepHandler handler) { <START> return (context, operation) -> { <END> PathAddress address = context.getCurrentAddress(); JGroupsLogger.ROOT_LOGGER.legacyProtocol(address.getLastElement().getValue(), this.targetName); PathAddress targetAddress = address.getParent().append(pathElement(this.targetName)); Operations.setPathAddress(operation, targetAddress); PathAddress targetRegistrationAddress = address.getParent().append(ProtocolResourceDefinition.WILDCARD_PATH); String operationName = Operations.getName(operation); context.addStep(operation, context.getRootResourceRegistration().getOperationHandler(targetRegistrationAddress, operationName), OperationContext.Stage.MODEL); }; }</code><technical_language>This a lambda</technical_language>

Target:
public OperationStepHandler apply(OperationStepHandler handler) { return this; }
Source:
<code>private T determineNextSelectedItem() { T currentItem = getSelectedItem() != null ? getSelectedItem() : getSelectedItems() != null ? getSelectedItems().get(0) : null; T nextItem = null; Collection<T> items = getItems(); if (items != null && currentItem != null) { List<T> itemsList = <START> (List<T>) items; <END> int currentIndex = itemsList.indexOf(currentItem); if (currentIndex > -1 && currentIndex < itemsList.size()) { if (currentIndex + 1 < itemsList.size()) { nextItem = itemsList.get(currentIndex + 1); } else if (currentIndex - 1 > -1) { nextItem = itemsList.get(currentIndex - 1); } } } return nextItem; }</code><technical_language>consider creating ArrayList out of items Collection. OK current change too, items a List anyway</technical_language>

Target:
private T determineNextSelectedItem() { T currentItem = getSelectedItem() != null ? getSelectedItem() : getSelectedItems() != null ? getSelectedItems().get(0) : null; T nextItem = null; Collection<T> items = getItems(); if (items != null && currentItem != null && items instanceof List) { List<T> itemsList = (List<T>) items; int currentIndex = itemsList.indexOf(currentItem); if (currentIndex > -1 && currentIndex < itemsList.size()) { if (currentIndex + 1 < itemsList.size()) { nextItem = itemsList.get(currentIndex + 1); } else if (currentIndex - 1 > -1) { nextItem = itemsList.get(currentIndex - 1); } } } return nextItem; }
Source:
<code>public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); final PsiFile file = element != null ? element.getContainingFile() : null; if (!(element instanceof GoImportSpec && file instanceof GoFile)) return; <START> final Map<GoReferenceExpressionBase, String> usages = ContainerUtil.newHashMap(); <END> file.acceptChildren(new PsiRecursiveElementVisitor() { public void visitElement(@NotNull PsiElement element) { if (element instanceof GoReferenceExpression || element instanceof GoTypeReferenceExpression) { PsiReference reference = element.getReference(); PsiElement definition = reference != null ? reference.resolve() : null; PsiFile definitionFile = definition instanceof GoNamedElement ? definition.getContainingFile() : null; if (definitionFile != null && definitionFile.getParent() == file.getParent()) { usages.put((GoReferenceExpressionBase)element, ((GoNamedElement)definition).getName()); return; } } super.visitElement(element); } }); WriteCommandAction.runWriteCommandAction(project, new Runnable() { @Override public void run() { for (Map.Entry<GoReferenceExpressionBase, String> usage : usages.entrySet()) { GoReferenceExpressionBase expression = usage.getKey(); expression.replace(expression instanceof GoReferenceExpression ? GoElementFactory.createReferenceExpression(project, usage.getValue()) : GoElementFactory.createTypeReferenceExpression(project, usage.getValue())); } GoImportDeclaration importDeclaration = PsiTreeUtil.getParentOfType(element, GoImportDeclaration.class); assert importDeclaration != null; PsiElement elementToDelete = importDeclaration.getImportSpecList().size() == 1 ? importDeclaration : element; elementToDelete.delete(); } }); }</code><technical_language>GoDeleteQuickFix? do need this untested stuff replacing</technical_language>

Target:
public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); final PsiFile file = element != null ? element.getContainingFile() : null; if (!(element instanceof GoImportSpec && file instanceof GoFile)) return; WriteCommandAction.runWriteCommandAction(project, new Runnable() { @Override public void run() { ((GoFile)file).deleteImport((GoImportSpec)element); } }); }
Source:
<code>public List<Pair<Term, BitSet>> disjunctions() { <START> Set<Pair<Term, BitSet>> disjunctions = new HashSet<>(); <END> disjunctions.addAll((java.util.Collection<Pair<Term, BitSet>>) (Object) Arrays.asList(kItemDisjunctionsArray)); ((List<List<Pair<Term, BitSet>>>) (Object) Arrays.asList(variableDisjunctionsArray)).stream().filter(l -> l != null).forEach(disjunctions::addAll); disjunctions.addAll((java.util.Collection<Pair<Term, BitSet>>) (Object) tokenDisjunctions.values()); disjunctions.removeIf(e -> e == null); return new ArrayList<>(disjunctions); }</code><technical_language>is this method called? cache this computation others</technical_language>

Target:
public List<Pair<Term, BitSet>> disjunctions() { return disjunctions; }
Source:
<code>private Response getSchema() { ByteArrayOutputStream baos = null; InputStream is = null; byte[] buffer = new byte[4096]; try { baos = new ByteArrayOutputStream(); is = Thread.currentThread().getContextClassLoader().getResourceAsStream(API_SCHEMA); int count; while ((count = is.read(buffer)) != -1) { baos.write(buffer, 0, count); } baos.flush(); return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename = " + SCHEMA_NAME) .build(); } catch (IOException e) { log.error("Loading api.xsd file failed: {}", e.getMessage()); <START> log.debug("Exception", e); <END> return Response.serverError().build(); } finally { try { if (baos != null) baos.close(); if (is != null) is.close(); } catch (IOException ignored) } }</code><technical_language>strack trace lavel error</technical_language>

Target:
private Response getSchema() { ByteArrayOutputStream baos = null; InputStream is = null; byte[] buffer = new byte[4096]; try { baos = new ByteArrayOutputStream(); is = Thread.currentThread().getContextClassLoader().getResourceAsStream(API_SCHEMA); int count; while ((count = is.read(buffer)) != -1) { baos.write(buffer, 0, count); } baos.flush(); return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename = " + SCHEMA_NAME) .build(); } catch (IOException e) { log.error("Loading api.xsd file failed.", e); return Response.serverError().build(); } finally { try { if (baos != null) baos.close(); if (is != null) is.close(); } catch (IOException ignored) } }
Source:
<code>public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { String newPort = (String) config.get("port"); if (StringUtils.isNotBlank(newPort) && !newPort.equals(port)) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } try { <START> openPort(newPort); <END> setProperlyConfigured(true); } catch (InitializationException e) { logger.error(e.getMessage()); setProperlyConfigured(false); } } } }</code><technical_language>is port opened if name of port changed? I assume port opened in case, right</technical_language>

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } String newPort = (String) config.get("port"); if (StringUtils.isNotBlank(newPort) && !newPort.equals(port)) { try { openPort(newPort); setProperlyConfigured(true); } catch (InitializationException e) { logger.error(e.getMessage()); setProperlyConfigured(false); } } } }
Source:
<code>private ExecutorService createExecutor() { int numThreads = Runtime.getRuntime().availableProcessors() + 1; return Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setNameFormat("SonarJava-parallel-analysis-%d").build()); <START> } <END></code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') "createExecutor" a "static" method. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private ExecutorService createExecutor() { int numThreads = 2; return Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setNameFormat("SonarJava-parallel-analysis-%d").build()); }
Source:
<code>private ClassLoader getCachedNonBootclasspathSystemLib(String zip, ClassLoader parent, String classLoaderName, List<ClassLoader> sharedLibraries) { if (mSystemLibsPreloadMap == null) { return null; } if (parent != null || classLoaderName != null) { return null; } CachedClassLoader preload = mSystemLibsPreloadMap.get(zip); if (preload == null) { return null; } if <START> (!sharedLibrariesEquals(sharedLibraries, <END> preload.sharedLibraries)) { Log.w(TAG, "Unexpected environment for preloaded library: (" + sharedLibraries + "|" + preload.sharedLibraries + ")"); return null; } Log.d(TAG, "Returning zygote-cached class loader: " + zip); return preload.loader; }</code><technical_language>check parent classLoaderName</technical_language>

Target:
private ClassLoader getCachedNonBootclasspathSystemLib(String zip, ClassLoader parent, String classLoaderName, List<ClassLoader> sharedLibraries) { if (mSystemLibsCacheMap == null) { return null; } if (parent != null || classLoaderName != null) { return null; } CachedClassLoader cached = mSystemLibsCacheMap.get(zip); if (cached == null) { return null; } if (!sharedLibrariesEquals(sharedLibraries, cached.sharedLibraries)) { Log.w(TAG, "Unexpected environment for cached library: (" + sharedLibraries + "|" + cached.sharedLibraries + ")"); return null; } Log.d(TAG, "Returning zygote-cached class loader: " + zip); return cached.loader; }
Source:
<code>long gtk_configure_event (long widget, long event) { int x = new int [1], y = new int [1]; GTK.gtk_window_get_position (shellHandle, x, y); if (!isVisible ()) { return 0; } if (!moved || oldX != x [0] || oldY != y [0]) { moved = true; oldX = x [0]; oldY = y [0]; sendEvent (SWT.Move); countMove++; <START> if (oldFunction != 0 && ((style & SWT.MAX) != 0) && ((style & SWT.RESIZE) != 0) && countMove == 3) { <END> long window = gtk_widget_get_window (shellHandle); if (((style & SWT.SHELL_TRIM) == SWT.SHELL_TRIM)) { GDK.gdk_window_set_functions(window, GDK.GDK_FUNC_ALL); } else { oldFunction |= GDK.GDK_FUNC_MAXIMIZE; GDK.gdk_window_set_functions(window, oldFunction); } } } return 0; }</code><technical_language>3 from? Ideally hardcode things</technical_language>

Target:
long gtk_configure_event (long widget, long event) { int x = new int [1], y = new int [1]; GTK.gtk_window_get_position (shellHandle, x, y); if (!isVisible ()) { return 0; } if (!moved || oldX != x [0] || oldY != y [0]) { moved = true; oldX = x [0]; oldY = y [0]; sendEvent (SWT.Move); } if (oldFunction != 0 && ((style & SWT.MAX) != 0) && ((style & SWT.RESIZE) != 0) && reenableMax) { long window = gtk_widget_get_window (shellHandle); if (((style & SWT.SHELL_TRIM) == SWT.SHELL_TRIM)) { GDK.gdk_window_set_functions(window, GDK.GDK_FUNC_ALL); } else { oldFunction |= GDK.GDK_FUNC_MAXIMIZE; GDK.gdk_window_set_functions(window, oldFunction); } reenableMax = false; } return 0; }
Source:
<code>protected List<GenericRecord> readOutput(Location location, Schema schema) throws IOException { org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(schema.toString()); DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(avroSchema); List<GenericRecord> records = Lists.newArrayList(); for (Location file : location.list()) { String locName = file.getName(); if (locName.endsWith(".avro")) { DataFileStream<GenericRecord> fileStream = new DataFileStream<>(file.getInputStream(), datumReader); Iterables.addAll(records, fileStream); fileStream.close(); } if (locName.endsWith(".parquet")) { Path parquetFile = new Path(file.toString()); AvroParquetReader.Builder<GenericRecord> genericRecordBuilder = AvroParquetReader.builder(parquetFile); <START> org.apache.parquet.hadoop.ParquetReader<GenericRecord> reader = genericRecordBuilder.build(); <END> GenericRecord result = reader.read(); while (result != null) { records.add(result); result = reader.read(); } } } return records; }</code><technical_language>full name is used? remove parquet.hadoop.ParquetReader import import this class</technical_language>

Target:
protected List<GenericRecord> readOutput(Location location, Schema schema) throws IOException { org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(schema.toString()); DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(avroSchema); List<GenericRecord> records = Lists.newArrayList(); for (Location file : location.list()) { String locName = file.getName(); if (locName.endsWith(".avro")) { DataFileStream<GenericRecord> fileStream = new DataFileStream<>(file.getInputStream(), datumReader); Iterables.addAll(records, fileStream); fileStream.close(); } if (locName.endsWith(".parquet")) { Path parquetFile = new Path(file.toString()); AvroParquetReader.Builder<GenericRecord> genericRecordBuilder = AvroParquetReader.builder(parquetFile); ParquetReader<GenericRecord> reader = genericRecordBuilder.build(); GenericRecord result = reader.read(); while (result != null) { records.add(result); result = reader.read(); } } } return records; }
Source:
<code>public static void assertValidSubmoduleName(String name) throws SubmoduleValidationException { if (name.contains("/../") || name.contains("\\..\\") || name.startsWith("../") || name.startsWith("..\\") || name.endsWith("/..") || name.endsWith("\\..")) { throw new SubmoduleValidationException(MessageFormat .format(JGitText.get().invalidNameContainsDotDot, name), <START> ObjectChecker.ErrorType.GITMODULES_NAME); <END> } if (name.startsWith("-")) { throw new SubmoduleValidationException( MessageFormat.format( JGitText.get().submoduleNameInvalid, name), ObjectChecker.ErrorType.GITMODULES_NAME); } }</code><technical_language>optional: import static for brevity</technical_language>

Target:
public static void assertValidSubmoduleName(String name) throws SubmoduleValidationException { if (name.contains("/../") || name.contains("\\..\\") || name.startsWith("../") || name.startsWith("..\\") || name.endsWith("/..") || name.endsWith("\\..")) { throw new SubmoduleValidationException(MessageFormat .format(JGitText.get().invalidNameContainsDotDot, name), GITMODULES_NAME); } if (name.startsWith("-")) { throw new SubmoduleValidationException( MessageFormat.format( JGitText.get().submoduleNameInvalid, name), GITMODULES_NAME); } }
Source:
<code>private void removeTemplateBackup() { AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { TemplateBackupModel templateBackupModel = (TemplateBackupModel) model; ArrayList<StoragePool> pools = (ArrayList<StoragePool>) returnValue; if (pools != null && pools.size() > 0) { StoragePool pool = pools.get(0); ArrayList<VdcActionParametersBase> prms = new ArrayList<VdcActionParametersBase>(); for (Object a : templateBackupModel.getSelectedItems()) { VmTemplate template = (VmTemplate) a; prms.add(new VmTemplateImportExportParameters(template.getId(), getEntity().getId(), pool.getId())); } Frontend.getInstance().runMultipleAction(VdcActionType.RemoveVmTemplateFromImportExport, prms); } } }), getEntity().getId()); <START> setConfirmWindow(null); <END> }</code><technical_language>call cancel() 'onSuccess' (to dialog open action is fully invoked in backend)</technical_language>

Target:
private void removeTemplateBackup() { AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { TemplateBackupModel templateBackupModel = (TemplateBackupModel) model; ArrayList<StoragePool> pools = (ArrayList<StoragePool>) returnValue; if (pools != null && pools.size() > 0) { StoragePool pool = pools.get(0); ArrayList<VdcActionParametersBase> prms = new ArrayList<VdcActionParametersBase>(); for (Object a : templateBackupModel.getSelectedItems()) { VmTemplate template = (VmTemplate) a; prms.add(new VmTemplateImportExportParameters(template.getId(), getEntity().getId(), pool.getId())); } Frontend.getInstance().runMultipleAction(VdcActionType.RemoveVmTemplateFromImportExport, prms); cancel(); } } }), getEntity().getId()); }
Source:
<code>private List<WebElement> findInnerShadowHosts(final List<WebElement> shadowHosts, final List<String> innerHostSelectors) { List<WebElement> hosts = shadowHosts; List<String> hostSelectors = innerHostSelectors; while (!hostSelectors.isEmpty()) { final List<WebElement> innerHosts = new ArrayList<>(); <START> final String innerHostSelector = innerHostSelectors.get(0); <END> for (final WebElement host : hosts) { innerHosts.addAll(getElementsInsideShadowTree(host, innerHostSelector)); } hosts = innerHosts; hostSelectors = innerHostSelectors.subList(1, innerHostSelectors.size()); } return hosts; }</code><technical_language>get host hostSelectors</technical_language>

Target:
private List<WebElement> findInnerShadowHosts(final List<WebElement> shadowHosts, final List<String> innerHostSelectors) { List<WebElement> hosts = shadowHosts; List<String> hostSelectors = innerHostSelectors; while (!hostSelectors.isEmpty()) { final List<WebElement> innerHosts = new ArrayList<>(); final String hostSelector = hostSelectors.get(0); for (final WebElement host : hosts) { innerHosts.addAll(getElementsInsideShadowTree(host, hostSelector)); } hosts = innerHosts; hostSelectors = hostSelectors.subList(1, hostSelectors.size()); } return hosts; }
Source:
<code>protected <U> void update(final T parameterName, final U value) { <START> if (!parameterMap.get(parameterName).getValue().getClass().isInstance(value)) { <END> throw new IllegalArgumentException("Cannot update parameter value with type different from that of current value."); } parameterMap.put(parameterName, new Parameter<>(parameterName, value)); }</code><technical_language>Utils.validateArg</technical_language>

Target:
protected <U> void update(final T parameterName, final U value) { Utils.validateArg(parameterMap.get(parameterName).getValue().getClass().isInstance(value), "Cannot update parameter value with type different from that of current value."); parameterMap.put(parameterName, new Parameter<>(parameterName, value)); }
Source:
<code>protected void freeCustomLocks() { if (getCommandStatus() == CommandStatus.ENDED_WITH_FAILURE && !Guid.Empty.equals(getVmId()) && getParameters().isVmLockedOnSelect()) { EngineLock runLock = vmPoolHandler.createLock(getVmId()); lockManager.releaseLock(runLock); log.info("VM lock freed: {}", runLock); <START> getParameters().setVmLockedOnSelect(false); <END> } }</code><technical_language>is needed</technical_language>

Target:
protected void freeCustomLocks() { if (getCommandStatus() == CommandStatus.ENDED_WITH_FAILURE && !Guid.Empty.equals(getVmId()) && !getParameters().isVmPrestarted()) { EngineLock runLock = vmPoolHandler.createLock(getVmId()); lockManager.releaseLock(runLock); log.info("VM lock freed: {}", runLock); } }
Source:
<code>public void shouldFetch_withAttributeQueryAndMaxPageSize() throws Exception { final StubItem createdItem = dataGenerator.createStubItem(); final String stringProperty = createdItem.getStringProperty(); final StubItem stubItem = new StubItem(); stubItem.setStringProperty(stringProperty); final Query query = new AttributeQuery(STRING_PROPERTY, new Condition(Operators.EQUALS, stringProperty)); final DynamoDbTemplate dynamoDbTemplate = new DynamoDbTemplate(databaseSchemaHolder); dynamoDbTemplate.initialize(amazonDynamoDbClient); <START> final Collection<StubItem> itemResults = dynamoDbTemplate.fetch(query, StubItem.class, 10); <END> assertNotNull(itemResults); assertEquals(1, itemResults.size()); assertEquals(createdItem, itemResults.iterator().next()); }</code><technical_language>Prefer randomInt(11) (returned values: 0 - 10)</technical_language>

Target:
public void shouldFetch_withAttributeQueryAndMaxPageSize() throws Exception { final StubItem createdItem = dataGenerator.createStubItem(); final String stringProperty = createdItem.getStringProperty(); final StubItem stubItem = new StubItem(); stubItem.setStringProperty(stringProperty); final Query query = new AttributeQuery(STRING_PROPERTY, new Condition(Operators.EQUALS, stringProperty)); final DynamoDbTemplate dynamoDbTemplate = new DynamoDbTemplate(databaseSchemaHolder); dynamoDbTemplate.initialize(amazonDynamoDbClient); final Collection<StubItem> itemResults = dynamoDbTemplate.fetch(query, StubItem.class, Randoms.randomInt(11)); assertNotNull(itemResults); assertEquals(1, itemResults.size()); assertEquals(createdItem, itemResults.iterator().next()); }
Source:
<code>public static String sanitizeForNextUrl(String url) { <START> if(url == null) return null; <END> return url.replace("&", "${amp}").replace("%2B", "${plus}").replace("%23", "${hash}"); }</code><technical_language>coding style</technical_language>

Target:
public static String sanitizeForNextUrl(String url) { if (url == null) { return null; } return url.replace("&", "${amp}").replace("%2B", "${plus}").replace("%23", "${hash}"); }
Source:
<code>public void tradePerformed(Order o, double matchPrice) throws StockMarketExpection { double totalPrice = 0; if (containsStock(o.getStockSymbol(), position) != -1){ <START> int i = containsStock(o.getStockSymbol(), position); <END> Order order = position.get(i); int totalStocks = order.getSize(); switch (o.getType()) { case BUY: totalStocks = totalStocks + o.getSize(); totalPrice = matchPrice * o.getSize(); cashInHand = cashInHand - totalPrice; break; case SELL: totalStocks = totalStocks - o.getSize(); totalPrice = matchPrice * o.getSize(); cashInHand = cashInHand + totalPrice; break; } if(totalStocks == 0) { position.remove(i); } else { order.setSize(totalStocks); position.set(i, order); } int location = containsStock(o.getStockSymbol(), ordersPlaced); ordersPlaced.remove(location); } else { position.add(o); int location = containsStock(o.getStockSymbol(), ordersPlaced); ordersPlaced.remove(location); totalPrice = matchPrice * o.getSize(); cashInHand = cashInHand - totalPrice; } }</code><technical_language>change short variable "i"</technical_language>

Target:
public void tradePerformed(Order o, double matchPrice) throws StockMarketExpection { double totalPrice = 0; if (containsStock(o.getStockSymbol(), possession) != -1){ int foundOrder = containsStock(o.getStockSymbol(), possession); Order order = possession.get(foundOrder); int totalStocks = order.getSize(); switch (o.getType()) { case BUY: totalStocks = totalStocks + o.getSize(); totalPrice = matchPrice * o.getSize(); cashInHand = cashInHand - totalPrice; break; case SELL: totalStocks = totalStocks - o.getSize(); totalPrice = matchPrice * o.getSize(); cashInHand = cashInHand + totalPrice; break; } if(totalStocks == 0) { possession.remove(foundOrder); } else { order.setSize(totalStocks); possession.set(foundOrder, order); } int location = containsStock(o.getStockSymbol(), ordersPlaced); ordersPlaced.remove(location); } else { possession.add(o); int location = containsStock(o.getStockSymbol(), ordersPlaced); ordersPlaced.remove(location); totalPrice = matchPrice * o.getSize(); cashInHand = cashInHand - totalPrice; } }