auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public AggregateScore getSingleScore(final Long accountId, final String date) { <START> Map<String, AttributeValue> key = new HashMap<>(); <END> key.put(ACCOUNT_ID_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(accountId))); key.put(DATE_ATTRIBUTE_NAME, new AttributeValue().withS(date)); final GetItemRequest getItemRequest = new GetItemRequest() .withTableName(this.tableName) .withKey(key) .withAttributesToGet(this.targetAttributes); final GetItemResult result = this.dynamoDBClient.getItem(getItemRequest); final Map<String, AttributeValue> item = result.getItem(); if (item == null) { LOGGER.debug("Account date score not found", accountId, date); return new AggregateScore(accountId, 0, "You haven't been sleeping", date, DEFAULT_SCORE_TYPE, this.version); } if(!item.keySet().containsAll(this.targetAttributes)){ LOGGER.warn("Missing field in item {}", item); return new AggregateScore(accountId, 0, "You haven't been sleeping", date, DEFAULT_SCORE_TYPE, this.version); } return new AggregateScore( Long.valueOf(item.get(ACCOUNT_ID_ATTRIBUTE_NAME).getN()), Integer.valueOf(item.get(SCORE_ATTRIBUTE_NAME).getN()), item.get(MESSAGE_ATTRIBUTE_NAME).getS(), item.get(DATE_ATTRIBUTE_NAME).getS(), item.get(TYPE_ATTRIBUTE_NAME).getS(), item.get(VERSION_ATTRIBUTE_NAME).getS() ); }</code><technical_language>final</technical_language>

Target:
public AggregateScore getSingleScore(final Long accountId, final String date) { final Map<String, AttributeValue> key = new HashMap<>(); key.put(ACCOUNT_ID_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(accountId))); key.put(DATE_ATTRIBUTE_NAME, new AttributeValue().withS(date)); final GetItemRequest getItemRequest = new GetItemRequest() .withTableName(this.tableName) .withKey(key) .withAttributesToGet(this.targetAttributes); final GetItemResult result = this.dynamoDBClient.getItem(getItemRequest); final Map<String, AttributeValue> item = result.getItem(); if (item == null) { LOGGER.debug("Account date score not found", accountId, date); return new AggregateScore(accountId, 0, date, DEFAULT_SCORE_TYPE, this.version); } if(!item.keySet().containsAll(this.targetAttributes)){ LOGGER.warn("Missing field in item {}", item); return new AggregateScore(accountId, 0, date, DEFAULT_SCORE_TYPE, this.version); } return this.createAggregateScore(item); }
Source:
<code>private String releaseDateInstant(String releaseDate) { try { <START> int timestamp = Integer.parseInt(releaseDate); <END> return Instant.ofEpochMilli(timestamp).toString(); } catch (NumberFormatException nfe) { return Instant.parse(releaseDate).toString(); } catch (DateTimeParseException dtpe) { throw new UserException("Unable to parse plugin info release date " + releaseDate, dtpe); } }</code><technical_language>this Long.parseLong for a timestamp</technical_language>

Target:
private String releaseDateInstant(String releaseDate) { try { long timestamp = Long.parseLong(releaseDate); return Instant.ofEpochMilli(timestamp).toString(); } catch (NumberFormatException nfe) { return Instant.parse(releaseDate).toString(); } catch (DateTimeParseException dtpe) { throw new UserException("Unable to parse plugin info release date " + releaseDate, dtpe); } }
Source:
<code>public void cannotNullifySets() { Subpopulation subpop = new DynamoSubpopulation(); subpop.setDataGroupsAssignedWhileConsented(null); subpop.setSubstudyIdsAssignedOnConsent(null); assertTrue(subpop.getDataGroupsAssignedWhileConsented().isEmpty()); <START> assertTrue(subpop.getSubstudyIdsAssignedOnConsent().isEmpty()); <END> }</code><technical_language>Is correct behavior ignore nulls turn empty sets? If correct behavior is ignore nulls, a non-empty set verify null is ignored</technical_language>

Target:
public void cannotNullifySets() { Subpopulation subpop = new DynamoSubpopulation(); subpop.setDataGroupsAssignedWhileConsented(ImmutableSet.of("A")); subpop.setSubstudyIdsAssignedOnConsent(ImmutableSet.of("B")); assertEquals(ImmutableSet.of("A"), subpop.getDataGroupsAssignedWhileConsented()); assertEquals(ImmutableSet.of("B"), subpop.getSubstudyIdsAssignedOnConsent()); subpop.setDataGroupsAssignedWhileConsented(null); subpop.setSubstudyIdsAssignedOnConsent(null); assertTrue(subpop.getDataGroupsAssignedWhileConsented().isEmpty()); assertTrue(subpop.getSubstudyIdsAssignedOnConsent().isEmpty()); }
Source:
<code>public static String hardWrap(String text) { int[] wrapOffsets = calculateWrapOffsets(text, MAX_LINE_WIDTH); if (wrapOffsets != null) { StringBuilder builder = new StringBuilder(text.length() + wrapOffsets.length); int prev = 0; for (int cur : wrapOffsets) { builder.append(text.substring(prev, cur)); <START> for (int j = cur; j > prev && builder.charAt(builder.length() - 1) == ' '; j--) { <END> builder.deleteCharAt(builder.length() - 1); } builder.append('\n'); prev = cur; } builder.append(text.substring(prev)); return builder.toString(); } return text; }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
public static String hardWrap(String text) { int[] wrapOffsets = calculateWrapOffsets(text, MAX_LINE_WIDTH); if (wrapOffsets != null) { StringBuilder builder = new StringBuilder(text.length() + wrapOffsets.length); int prev = 0; for (int cur : wrapOffsets) { builder.append(text.substring(prev, cur)); for (int j = cur; j > prev && builder.charAt(builder.length() - 1) == ' '; j--) builder.deleteCharAt(builder.length() - 1); builder.append('\n'); prev = cur; } builder.append(text.substring(prev)); return builder.toString(); } return text; }
Source:
<code>private Disk clone(Disk parent) { Disk disk = new Disk(); disk.setId(parent.getId()); <START> disk.setVm(new VM()); <END> if (parent.isSetVm()) { disk.getVm().setId(parent.getVm().getId()); } return disk; }</code><technical_language>disk.setVm(new VM()); of this /if/</technical_language>

Target:
private Disk clone(Disk parent) { Disk disk = new Disk(); disk.setId(parent.getId()); if (parent.isSetVm()) { disk.setVm(new VM()); disk.getVm().setId(parent.getVm().getId()); } return disk; }
Source:
<code>public void createLineModelsFromMap(Map<String, Object> keyValueMap) { List<KeyValueLineModel> lineModels = new ArrayList<>(); if (useEditableKey) { for (Map.Entry<String, Object> entry : keyValueMap.entrySet()) { KeyValueLineModel lineModel = createNewLineModel(null); lineModel.getValue().setEntity(entry.getKey()); lineModel.getEditableKey().setEntity((String) <START> keyValueMap.get(entry.getKey())); <END> lineModels.add(lineModel); } } setItems(lineModels); }</code><technical_language>change :) Please change entry.getValue()</technical_language>

Target:
public void createLineModelsFromMap(Map<String, Object> keyValueMap) { List<KeyValueLineModel> lineModels = new ArrayList<>(); if (useEditableKey) { for (Map.Entry<String, Object> entry : keyValueMap.entrySet()) { KeyValueLineModel lineModel = createNewLineModel(null); lineModel.getValue().setEntity(entry.getKey()); lineModel.getEditableKey().setEntity((String) entry.getValue()); lineModels.add(lineModel); } } setItems(lineModels); }
Source:
<code>public Map<String, List<SubscribeCommand>> sync( PubSubConfig.Publisher publisher) throws IOException { config = publisher; Map<String, List<SubscribeCommand>> subscribeCommands = new HashMap< String, List<SubscribeCommand>>(); for (PubSubConfig.Subscriber s : publisher.getSubscribers()) { SubscribedRepository sr = repoSubscriptions.get(s.getName()); List<SubscribeCommand> repoCommands = new ArrayList< SubscribeCommand>(); if (sr == null) { sr = new SubscribedRepository(s); for (RefSpec spec : s.getSubscribeSpecs()) repoCommands.add(new SubscribeCommand( Command.SUBSCRIBE, spec.getSource())); } else { List<String> newSpecs = new ArrayList<String>(); List<String> oldSpecs = new ArrayList<String>(); for (RefSpec rs : s.getSubscribeSpecs()) newSpecs.add(rs.getSource()); for (RefSpec rs : sr.getSubscribeSpecs()) oldSpecs.add(rs.getSource()); <START> List<String> toAdd = new ArrayList<String>(newSpecs); <END> toAdd.removeAll(oldSpecs); for (String subscribe : toAdd) repoCommands.add( new SubscribeCommand(Command.SUBSCRIBE, subscribe)); List<String> toRemove = new ArrayList<String>(oldSpecs); toRemove.removeAll(newSpecs); for (String unsubscribe : toRemove) repoCommands.add(new SubscribeCommand( Command.UNSUBSCRIBE, unsubscribe)); sr.setSubscribeSpecs(s.getSubscribeSpecs()); } subscribeCommands.put(sr.getName(), repoCommands); repoSubscriptions.put(sr.getName(), sr); sr.setUpRefs(); } return subscribeCommands; }</code><technical_language>I this a Set removeAll is faster. LinkedHashSet preserve original ordering. (OTOH, number of subscribe specs typically small enough worry about.)</technical_language>

Target:
public Map<String, List<SubscribeCommand>> sync( PubSubConfig.Publisher publisher) throws IOException { config = publisher; Map<String, List<SubscribeCommand>> subscribeCommands = new HashMap< String, List<SubscribeCommand>>(); for (PubSubConfig.Subscriber s : publisher.getSubscribers()) { SubscribedRepository sr = repoSubscriptions.get(s.getName()); List<SubscribeCommand> repoCommands = new ArrayList< SubscribeCommand>(); if (sr == null) { sr = new SubscribedRepository(s); for (RefSpec spec : s.getSubscribeSpecs()) repoCommands.add(new SubscribeCommand( Command.SUBSCRIBE, spec.getSource())); } else { List<String> newSpecs = new ArrayList<String>(); List<String> oldSpecs = new ArrayList<String>(); for (RefSpec rs : s.getSubscribeSpecs()) newSpecs.add(rs.getSource()); for (RefSpec rs : sr.getSubscribeSpecs()) oldSpecs.add(rs.getSource()); Set<String> toAdd = new LinkedHashSet<String>(newSpecs); toAdd.removeAll(oldSpecs); for (String subscribe : toAdd) repoCommands.add( new SubscribeCommand(Command.SUBSCRIBE, subscribe)); Set<String> toRemove = new LinkedHashSet<String>(oldSpecs); toRemove.removeAll(newSpecs); for (String unsubscribe : toRemove) repoCommands.add(new SubscribeCommand( Command.UNSUBSCRIBE, unsubscribe)); sr.setSubscribeSpecs(s.getSubscribeSpecs()); } subscribeCommands.put(sr.getName(), repoCommands); repoSubscriptions.put(sr.getName(), sr); sr.setUpRefs(); } return subscribeCommands; }
Source:
<code>public void setClientOperations(final Client client) { ArgumentVerifier.assertNotNull(client, "Client"); <START> if(isRunning() && !clients.containsKey(client.getChannel()) && !client.isClosed() && client.getClientsSocketExecuter() == this) { <END> clients.putIfAbsent(client.getChannel(), client); } if(clients.containsKey(client.getChannel()) && !client.isClosed() && isRunning()) { synchronized(client) { if(!client.getChannel().isConnected() && client.getChannel().isConnectionPending()) { readScheduler.execute(new AddToSelector(client, readSelector, SelectionKey.OP_CONNECT)); writeScheduler.execute(new AddToSelector(client, writeSelector, 0)); } else if(client.canWrite() && client.canRead()) { writeScheduler.execute(new AddToSelector(client, writeSelector, SelectionKey.OP_WRITE)); readScheduler.execute(new AddToSelector(client, readSelector, SelectionKey.OP_READ)); } else if (client.canRead()){ readScheduler.execute(new AddToSelector(client, readSelector, SelectionKey.OP_READ)); writeScheduler.execute(new AddToSelector(client, writeSelector, 0)); } else if (client.canWrite()){ writeScheduler.execute(new AddToSelector(client, writeSelector, SelectionKey.OP_WRITE)); readScheduler.execute(new AddToSelector(client, readSelector, 0)); } else { writeScheduler.execute(new AddToSelector(client, writeSelector, 0)); readScheduler.execute(new AddToSelector(client, readSelector, 0)); } } readSelector.wakeup(); writeSelector.wakeup(); } else if (client.isClosed()) { clients.remove(client.getChannel()); } }</code><technical_language>hope annoying, get lost is another putIfAbsent weirdness</technical_language>

Target:
public void setClientOperations(final Client client) { ArgumentVerifier.assertNotNull(client, "Client"); if(!clients.containsKey(client.getChannel()) || client.isClosed()) { clients.remove(client.getChannel()); return; } synchronized(client) { if(!client.getChannel().isConnected() && client.getChannel().isConnectionPending()) { readScheduler.execute(new AddToSelector(client, readSelector, SelectionKey.OP_CONNECT)); writeScheduler.execute(new AddToSelector(client, writeSelector, 0)); } else if(client.canWrite() && client.canRead()) { writeScheduler.execute(new AddToSelector(client, writeSelector, SelectionKey.OP_WRITE)); readScheduler.execute(new AddToSelector(client, readSelector, SelectionKey.OP_READ)); } else if (client.canRead()){ readScheduler.execute(new AddToSelector(client, readSelector, SelectionKey.OP_READ)); writeScheduler.execute(new AddToSelector(client, writeSelector, 0)); } else if (client.canWrite()){ writeScheduler.execute(new AddToSelector(client, writeSelector, SelectionKey.OP_WRITE)); readScheduler.execute(new AddToSelector(client, readSelector, 0)); } else { writeScheduler.execute(new AddToSelector(client, writeSelector, 0)); readScheduler.execute(new AddToSelector(client, readSelector, 0)); } } readSelector.wakeup(); writeSelector.wakeup(); }
Source:
<code><START> public RuleAssert doesNotFire() <END> { RuleApplication ruleApplication = applyRule(); if (ruleApplication.wasRuleApplied()) { fail(String.format( "Expected %s to not fire for:\n%s", rule.getClass().getName(), inTransaction(session -> PlanPrinter.textLogicalPlan(plan, ruleApplication.types, metadata, costCalculator, session, 2)))); } return this; }</code><technical_language>I benefit. Rule & input is set up, expected output is defined. case</technical_language>

Target:
public void doesNotFire() { RuleApplication ruleApplication = applyRule(); if (ruleApplication.wasRuleApplied()) { fail(String.format( "Expected %s to not fire for:\n%s", rule.getClass().getName(), inTransaction(session -> PlanPrinter.textLogicalPlan(plan, ruleApplication.types, metadata, costCalculator, session, 2)))); } }
Source:
<code>protected void executeCommand() { <START> updateDefaultQuota(); <END> getStoragePoolDAO().updatePartial(getStoragePool()); if (getStoragePool().getstatus() == StoragePoolStatus.Up) { if (!StringHelper.EqOp(_oldStoragePool.getname(), getStoragePool().getname())) { runVdsCommand(VDSCommandType.SetStoragePoolDescription, new SetStoragePoolDescriptionVDSCommandParameters(getStoragePool().getId(), getStoragePool().getname())); } } updateStoragePoolFormatType(); setSucceeded(true); }</code><technical_language>Perform update case of vdsm call successes, time updatePartia() . change updatePartial() , update storage pool format type</technical_language>

Target:
protected void executeCommand() { updateDefaultQuota(); if (_oldStoragePool.getstatus() == StoragePoolStatus.Up) { if (!StringHelper.EqOp(_oldStoragePool.getname(), getStoragePool().getname())) { runVdsCommand(VDSCommandType.SetStoragePoolDescription, new SetStoragePoolDescriptionVDSCommandParameters( getStoragePool().getId(), getStoragePool().getname()) ); getStoragePoolDAO().updatePartial(getStoragePool()); } } updateStoragePoolFormatType(); setSucceeded(true); }
Source:
<code>public CosmosConfig getCosmosConfig() { return CosmosConfig.builder() .enableQueryMetrics(true) .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) .database(secondaryProperties.getDatabase()) <START> .build(); <END> }</code><technical_language>ok, I a bit confusing, actually, database2 CosmosConfig instance created database1. CosmosConfig is related database name. @saragluna do other ideas</technical_language>

Target:
public CosmosConfig getCosmosConfig() { return CosmosConfig.builder() .enableQueryMetrics(true) .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) .build(); }
Source:
<code>public ClusterFeature get() { SupportedAdditionalClusterFeature feature = BackendClusterFeatureHelper.getEnabledFeature(this, asGuid(clusterId), asGuid(id)); <START> return ClusterFeaturesMapper.map(feature.getFeature(), null); <END> }</code><technical_language>This addLinks(map(...))</technical_language>

Target:
public ClusterFeature get() { SupportedAdditionalClusterFeature feature = BackendClusterFeatureHelper.getEnabledFeature(this, asGuid(clusterId), guid); if (feature != null) { return addLinks(ClusterFeaturesMapper.map(feature.getFeature(), null)); } else { throw new WebApplicationException(Response.Status.NOT_FOUND); } }
Source:
<code>private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) { if (result.isSuccess()) { refreshListOfFilesFragment(true); } else { try { showSnackMessage( <START> FileStorageUtils.getNewFolderName(((CreateFolderOperation) operation).getRemotePath()) + " " + getResources().getString(R.string.folder_already_exists) <END> ); } catch (NotFoundException e) { Log_OC.e(TAG, "Error while trying to show fail message ", e); } } }</code><technical_language>get folder name <LINK_0> calling operation.getFileName() avoid creating a new method in FileStorageUtils</technical_language>

Target:
private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) { if (result.isSuccess()) { refreshListOfFilesFragment(true); } else { try { showSnackMessage( ErrorMessageAdapter.getResultMessage(result, operation, getResources()) ); } catch (NotFoundException e) { Log_OC.e(TAG, "Error while trying to show fail message ", e); } } }
Source:
<code>public Map<String,Object> validateCronExpression(@RequestParam String cronExpression) { ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.builder(); if (CronExpressionFuzzer.isValid(cronExpression)) { mapBuilder.put("response", "Cron expression is valid"); if (CronExpressionFuzzer.hasFuzzyExpression(cronExpression)) { mapBuilder.put("description", "No description available for fuzzy cron expressions"); } else { try { Options options = new Options(); options.setZeroBasedDayOfWeek(false); mapBuilder.put("description", CronExpressionDescriptor.getDescription(cronExpression, options)); } catch (ParseException IGNORED) { mapBuilder.put("description", "No description available"); } } return mapBuilder.build(); <START> } <END> throw new InvalidCronExpressionException(cronExpression); }</code><technical_language>important is this API call return a human-readable cron description? I ask pulling in another library uniquely for this..</technical_language>

Target:
public Map<String,Object> validateCronExpression(@RequestParam String cronExpression) { ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.builder(); try { if (cronExpression == null) { throw new InvalidCronExpressionException("null", "cron expression can't be null"); } new CronExpression(CronExpressionFuzzer.fuzz("", cronExpression)); mapBuilder.put("response", "Cron expression is valid"); if (CronExpressionFuzzer.hasFuzzyExpression(cronExpression)) { mapBuilder.put("description", "No description available for fuzzy cron expressions"); } else { try { Options options = new Options(); options.setZeroBasedDayOfWeek(false); mapBuilder.put("description", CronExpressionDescriptor.getDescription(cronExpression, options)); } catch (ParseException IGNORED) { mapBuilder.put("description", "No description available"); } } return mapBuilder.build(); } catch (ParseException e) { throw new InvalidCronExpressionException(cronExpression, e.getMessage()); } }
Source:
<code>public void searchForInGlobalNav(String query) { <START> searchInputInGlobalNav.sendKeys(query); <END> searchFormInGlobalNav.submit(); }</code><technical_language>advice waitForValueToBePresentInElementsAttributeByElement(searchInputInGlobalNav, "value", query) sendKeys cases Chrome type a long message, next line execute is typed in field</technical_language>

Target:
public void searchForInGlobalNav(String query) { searchInputInGlobalNav.sendKeys(query); waitForValueToBePresentInElementsAttributeByElement(searchInputInGlobalNav, "value", query); searchFormInGlobalNav.submit(); }
Source:
<code>private VmStatsRefresher getRefresherForVds(VdsManager vdsManager) { Version version = vdsManager.getCompatibilityVersion(); VDS vds = vdsManager.getCopyVds(); if ((FeatureSupported.jsonProtocol(version) && VdsProtocol.STOMP == vds.getProtocol() && FeatureSupported.vmStatsEvents(version)) <START> && FeatureSupported.events(version)){ <END> return new EventVmStatsRefresher(vdsManager); } return new PollListAndAllVmStatsRefresher(vdsManager); }</code><technical_language>need for extra '()' missing space '{'</technical_language>

Target:
private VmStatsRefresher getRefresherForVds(VdsManager vdsManager) { Version version = vdsManager.getCompatibilityVersion(); VDS vds = vdsManager.getCopyVds(); if (FeatureSupported.jsonProtocol(version) && VdsProtocol.STOMP == vds.getProtocol() && FeatureSupported.vmStatsEvents(version) && FeatureSupported.events(version)){ return new EventVmStatsRefresher(vdsManager); } return new PollListAndAllVmStatsRefresher(vdsManager); }
Source:
<code>public void shouldUpdateUsageStatisticsReporting() { UsageStatisticsReporting existing = usageStatisticsReportingSqlMapDao.load(); assertNotNull(existing); assertNotNull(existing.lastReportedAt()); dataSharingUsageStatisticsReportingService.updateLastReportedTime(); UsageStatisticsReporting loaded = usageStatisticsReportingSqlMapDao.load(); <START> assertThat(loaded.lastReportedAt().toInstant(), is(not(existing.lastReportedAt()))); <END> }</code><technical_language>check for loaded.lastReportedAt().toInstant() > existing.lastReportedAt() instead</technical_language>

Target:
public void shouldUpdateUsageStatisticsReporting() { UsageStatisticsReporting existing = usageStatisticsReportingSqlMapDao.load(); assertNotNull(existing); assertNotNull(existing.lastReportedAt()); dataSharingUsageStatisticsReportingService.startReporting(new HttpLocalizedOperationResult()); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); dataSharingUsageStatisticsReportingService.completeReporting(result); assertTrue(result.isSuccessful()); UsageStatisticsReporting loaded = dataSharingUsageStatisticsReportingService.get(); assertThat(loaded.lastReportedAt().getTime(), greaterThan(existing.lastReportedAt().getTime())); }
Source:
<code>public Optional<Map<String, ServiceConfiguration>> getServiceConfigurations() { return Optional.fromNullable(services); <START> } <END></code><technical_language>sending empty Map avoid null isPresent checks later. Thoughts</technical_language>

Target:
public Map<String, ServiceConfiguration> getServiceConfigurations() { return Optional.fromNullable(services).or(EMPTY_SERVICE_CONFIGURATION); }
Source:
<code>private void updatePasswordInSystemkeychain() { if (keychain.isPresent()) { try { keychain.get().changePassphrase(vault.getId(), CharBuffer.wrap(newPassword.get())); <START> LOG.info("Successful updated in password in system keychain for {}", vault.getDisplayableName()); <END> } catch (KeychainAccessException e) { LOG.error("Failed to update password in system keychain.", e); } } }</code><technical_language>Successfully</technical_language>

Target:
private void updatePasswordInSystemkeychain() { if (keychain.isPresent()) { try { keychain.get().changePassphrase(vault.getId(), CharBuffer.wrap(newPassword.get())); LOG.info("Successfully updated password in system keychain for {}", vault.getDisplayableName()); } catch (KeychainAccessException e) { LOG.error("Failed to update password in system keychain.", e); } } }
Source:
<code>public String getInstallationAccessTokenFromInstallationId(String installationId) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("<LINK_0>" + installationId + "/access_tokens") .post(RequestBody.create(okhttp3.MediaType.parse(""), "")) .addHeader("Accept", "application/vnd.github.machine-man-preview+json") .addHeader("Authorization", "Bearer " + jsonWebToken) .build(); try { okhttp3.Response response = client.newCall(request).execute(); JsonElement body = new JsonParser().parse(response.body().string()); if (body.isJsonObject()) { JsonObject responseBody = body.getAsJsonObject(); JsonElement token = responseBody.get("token"); if (token.isJsonPrimitive()) { return token.getAsString(); } } } catch (IOException ex) { <START> throw new Exception("Unable to retrieve installation access token."); <END> } throw new Exception("Unable to retrieve installation access token."); }</code><technical_language>useful log exception</technical_language>

Target:
private String getInstallationAccessTokenFromInstallationId(String installationId) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("<LINK_0>" + installationId + "/access_tokens") .post(RequestBody.create(okhttp3.MediaType.parse(""), "")) .addHeader("Accept", "application/vnd.github.machine-man-preview+json") .addHeader("Authorization", "Bearer " + jsonWebToken) .build(); String errorMsg = "Unable to retrieve installation access token."; try { okhttp3.Response response = client.newCall(request).execute(); JsonElement body = new JsonParser().parse(response.body().string()); if (body.isJsonObject()) { JsonObject responseBody = body.getAsJsonObject(); if (response.isSuccessful()) { JsonElement token = responseBody.get("token"); if (token.isJsonPrimitive()) { return token.getAsString(); } } else { JsonElement errorMessage = responseBody.get("message"); if (errorMessage.isJsonPrimitive()) { errorMsg = errorMessage.getAsString(); } } } } catch (IOException ex) { LOG.error(errorMsg, ex); throw new Exception(errorMsg, ex); } LOG.error(errorMsg); throw new Exception(errorMsg); }
Source:
<code>static public void upgradeFileDeletes(ServerContext ctx, Ample.DataLevel level) { String tableName = level.metaTable(); AccumuloClient c = ctx; try (BatchWriter writer = c.createBatchWriter(tableName, new BatchWriterConfig())) { String continuePoint = ""; boolean stillDeletes = true; while (stillDeletes) { List<String> deletes = new ArrayList<>(); log.info("looking for candidates"); stillDeletes = getOldCandidates(ctx, tableName, continuePoint, deletes); log.info("found deletes to upgrade", deletes.size()); for (String olddelete : deletes) { <START> writer.addMutation(upgradeDeleteMutation(olddelete)); <END> } writer.flush(); for (String olddelete : deletes) { writer.addMutation(deleteOldDeleteMutation(olddelete)); } writer.flush(); sleepUninterruptibly(5, TimeUnit.SECONDS); continuePoint = deletes.get(deletes.size() - 1); log.debug("continuing from {}", continuePoint); } } catch (Exception e) { ; } }</code><technical_language>useful log trace debug is deleted added this code</technical_language>

Target:
public void upgradeFileDeletes(ServerContext ctx, Ample.DataLevel level) { String tableName = level.metaTable(); AccumuloClient c = ctx; try (BatchWriter writer = c.createBatchWriter(tableName, new BatchWriterConfig())) { log.info("looking for candidates in table {}", tableName); Iterator<String> oldCandidates = getOldCandidates(ctx, tableName); int t = 0; while (oldCandidates.hasNext()) { sleepUninterruptibly(t, TimeUnit.SECONDS); List<String> deletes = readCandidatesThatFitInMemory(oldCandidates); log.info("found deletes to upgrade", deletes.size()); for (String olddelete : deletes) { log.trace("upgrading delete entry for {}", olddelete); writer.addMutation(ServerAmpleImpl.createDeleteMutation(ctx, level.tableId(), olddelete)); } writer.flush(); log.info("upgrade processing completed so delete old entries"); for (String olddelete : deletes) { log.trace("deleting old entry for {}", olddelete); writer.addMutation(deleteOldDeleteMutation(olddelete)); } writer.flush(); t = 3; } } catch (TableNotFoundException | MutationsRejectedException e) { throw new RuntimeException(e); } }
Source:
<code>void execute() { if (graphics instanceof DelayedBackbufferGraphic) { ((DelayedBackbufferGraphic) graphics).init(); } for (LiteFeatureTypeStyle currentLayer : lfts) { final Graphics2D ftsGraphics = currentLayer.graphics; if (ftsGraphics instanceof DelayedBackbufferGraphic && !(ftsGraphics == graphics)) { BufferedImage image = ((DelayedBackbufferGraphic) ftsGraphics).image; if (image == null) { Rectangle size = ((DelayedBackbufferGraphic) ftsGraphics).screenSize; image = new BufferedImage( size.width, size.height, BufferedImage.TYPE_4BYTE_ABGR); } <START> if (currentLayer.composite == null) { <END> graphics.setComposite(AlphaComposite.SrcOver); } else { graphics.setComposite(currentLayer.composite); } graphics.drawImage(image, 0, 0, null); ftsGraphics.dispose(); } } }</code><technical_language>avoid buffered image allocation render in this case, common one</technical_language>

Target:
void execute() { if (graphics instanceof DelayedBackbufferGraphic) { ((DelayedBackbufferGraphic) graphics).init(); } for (LiteFeatureTypeStyle currentLayer : lfts) { final Graphics2D ftsGraphics = currentLayer.graphics; if (ftsGraphics instanceof DelayedBackbufferGraphic && !(ftsGraphics == graphics)) { BufferedImage image = ((DelayedBackbufferGraphic) ftsGraphics).image; if (currentLayer.composite == null) { graphics.setComposite(AlphaComposite.SrcOver); } else { if (image == null) { Rectangle size = ((DelayedBackbufferGraphic) ftsGraphics).screenSize; image = new BufferedImage( size.width, size.height, BufferedImage.TYPE_4BYTE_ABGR); } graphics.setComposite(currentLayer.composite); } if (image != null) { graphics.drawImage(image, 0, 0, null); ftsGraphics.dispose(); } } } }
Source:
<code>public boolean isDefaultCallScreeningApp(ComponentName componentName) { try { if (isServiceConnected()) { getTelecomService().isDefaultCallScreeningApp(componentName); } } catch (RemoteException e) { Log.e(TAG, "RemoteException calling ITelecomService#isDefaultCallScreeningApp.", e); } <START> return false; <END> }</code><technical_language>return false</technical_language>

Target:
public boolean isDefaultCallScreeningApp(ComponentName componentName) { try { if (isServiceConnected()) { return getTelecomService().isDefaultCallScreeningApp(componentName); } } catch (RemoteException e) { Log.e(TAG, "RemoteException calling ITelecomService#isDefaultCallScreeningApp.", e); } return false; }
Source:
<code>protected Type visitComparisonExpression(ComparisonExpression node, StackableAstVisitorContext<Context> context) { Optional<DynamicFilter> dynamicFilter = getDynamicFilterOptional(node); <START> if (dynamicFilter.isPresent()) { <END> expressionTypes.put(NodeRef.of(node.getLeft()), process(dynamicFilter.get().getSourceExpression(), context)); expressionTypes.put(NodeRef.of(node.getRight()), process(dynamicFilter.get().getSourceExpression(), context)); } OperatorType operatorType = OperatorType.valueOf(node.getType().name()); return getOperator(context, node, operatorType, node.getLeft(), node.getRight()); }</code><technical_language>do this more functional with: dynamicFilter.ifPresent(filter -> { expressionTypes.put(NodeRef.of(node.getLeft()), process(dynamicFilter.get().getSourceExpression(), context)); expressionTypes.put(NodeRef.of(node.getRight()), process(dynamicFilter.get().getSourceExpression(), context)); });</technical_language>

Target:
protected Type visitComparisonExpression(ComparisonExpression node, StackableAstVisitorContext<Context> context) { Optional<DynamicFilter> dynamicFilter = getDynamicFilterOptional(node); dynamicFilter.ifPresent(filter -> { expressionTypes.put(NodeRef.of(node.getLeft()), process(filter.getSourceExpression(), context)); expressionTypes.put(NodeRef.of(node.getRight()), process(filter.getSourceExpression(), context)); }); OperatorType operatorType = OperatorType.valueOf(node.getType().name()); return getOperator(context, node, operatorType, node.getLeft(), node.getRight()); }
Source:
<code>public static RemoteWebDriver driver() { AbstractTestSession testSession = getTestSession(); if (testSession == null) { <START> throw new IllegalStateException("Internal error. Test session not initialized."); <END> } if (!testSession.isStarted()) { testSession.startSession(); } RemoteWebDriver rwd = threadLocalWebDriver.get(); if (rwd == null) { throw new IllegalStateException("Driver not initialized. Is @WebTest/@MobileTest missing on class/method?"); } return rwd; }</code><technical_language>provide a more informative message here</technical_language>

Target:
public static RemoteWebDriver driver() { AbstractTestSession testSession = getTestSession(); if (testSession == null) { throw new IllegalStateException("Test session not initialized. Make sure the SeLion SeleniumGridListener is " + "enabled and you have annotated your class/method with @MobileTest/@WebTest."); } if (!testSession.isStarted()) { testSession.startSession(); } RemoteWebDriver rwd = threadLocalWebDriver.get(); if (rwd == null) { throw new IllegalStateException("Driver not initialized. Is @WebTest/@MobileTest missing on class/method?"); } return rwd; }
Source:
<code><START> public static boolean mergeFriendsLogs(final List<LogEntry> mergedLogs, List<LogEntry> logsToMerge) { <END> if (logsToMerge != null && !logsToMerge.isEmpty()) { for (final LogEntry log : logsToMerge) { if (mergedLogs.contains(log)) { mergedLogs.get(mergedLogs.indexOf(log)).friend = true; } else { log.friend = true; mergedLogs.add(log); } } return true; } return false; }</code><technical_language>public</technical_language>

Target:
private static boolean mergeFriendsLogs(final List<LogEntry> mergedLogs, List<LogEntry> logsToMerge) { if (logsToMerge != null && !logsToMerge.isEmpty()) { for (final LogEntry log : logsToMerge) { if (mergedLogs.contains(log)) { mergedLogs.get(mergedLogs.indexOf(log)).friend = true; } else { mergedLogs.add(log); } } return true; } return false; }
Source:
<code>private void rebuildIndex() throws Exception { ByteBuffer buf = ByteBuffer.allocate(KEY_POS); for (; ; ) { buf.clear().limit(KEY_POS); channel.read(buf, filePos); if (buf.remaining() > 0) return; buf.flip(); int entrySize = buf.getInt(); int keyLen = buf.getInt(); int dataLen = buf.getInt(); int metadataLen = buf.getInt(); long expiryTime = buf.getLong(); FileEntry fe = new FileEntry(filePos, entrySize, keyLen, dataLen, metadataLen, expiryTime); if (fe.size < KEY_POS + fe.keyLen + fe.dataLen + fe.metadataLen) { throw log.errorReadingFileStore(file.getPath(), filePos); } filePos += fe.size; if (smallestLen < fe.size) { smallestLen = fe.size; <START> } <END> if (fe.keyLen > 0) { if (buf.capacity() < fe.keyLen) buf = ByteBuffer.allocate(fe.keyLen); buf.clear().limit(fe.keyLen); channel.read(buf, fe.offset + KEY_POS); Object key = ctx.getMarshaller().objectFromByteBuffer(buf.array(), 0, fe.keyLen); entries.put(key, fe); } else { freeList.add(fe); } } }</code><technical_language>I smallest allowed entry size a constant, 128. True, in worst case lead a lot of 128 bytes-sized unusable entries, this approach, if user allocates 128 bytes (or smaller) entry</technical_language>

Target:
private void rebuildIndex() throws Exception { ByteBuffer buf = ByteBuffer.allocate(KEY_POS); for (; ; ) { buf.clear().limit(KEY_POS); channel.read(buf, filePos); if (buf.remaining() > 0) return; buf.flip(); int entrySize = buf.getInt(); int keyLen = buf.getInt(); int dataLen = buf.getInt(); int metadataLen = buf.getInt(); long expiryTime = buf.getLong(); FileEntry fe = new FileEntry(filePos, entrySize, keyLen, dataLen, metadataLen, expiryTime); if (fe.size < KEY_POS + fe.keyLen + fe.dataLen + fe.metadataLen) { throw log.errorReadingFileStore(file.getPath(), filePos); } filePos += fe.size; if (fe.keyLen > 0) { if (buf.capacity() < fe.keyLen) buf = ByteBuffer.allocate(fe.keyLen); buf.clear().limit(fe.keyLen); channel.read(buf, fe.offset + KEY_POS); Object key = ctx.getMarshaller().objectFromByteBuffer(buf.array(), 0, fe.keyLen); entries.put(key, fe); } else { freeList.add(fe); } } }
Source:
<code>public void buildListOfRowKeyColumnExpressionsSingleNodeIsNullTest() throws Exception { List<Expression> expressions = new ArrayList<>(); RowKeyColumnExpression rvc1 = new RowKeyColumnExpression(); RowKeyColumnExpression rvc2 = new RowKeyColumnExpression(); <START> IsNullExpression expression1 = mock(IsNullExpression.class); <END> Mockito.when(expression1.getChildren()).thenReturn(Lists.<Expression>newArrayList(rvc1)); List<RowKeyColumnExpression> result = offsetCompiler.buildListOfRowKeyColumnExpressions(expression1, false); assertEquals(1,result.size()); assertEquals(rvc1,result.get(0)); }</code><technical_language>nit: renaming expression expression2</technical_language>

Target:
public void buildListOfRowKeyColumnExpressionsSingleNodeIsNullTest() throws Exception { List<Expression> expressions = new ArrayList<>(); RowKeyColumnExpression rvc = new RowKeyColumnExpression(); IsNullExpression expression = mock(IsNullExpression.class); Mockito.when(expression.getChildren()).thenReturn(Lists.<Expression>newArrayList(rvc)); List<RowKeyColumnExpression> result = offsetCompiler.buildListOfRowKeyColumnExpressions(expression, false); assertEquals(1,result.size()); assertEquals(rvc,result.get(0)); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { String urlText = event.getParameter(PARAM_ID_URL); final URL url; if (urlText == null) { url = null; } else { try { url = new URL(urlText); } catch (MalformedURLException ex) { throw new ExecutionException("malformed URL:" + urlText, ex); } } final String browserId = event.getParameter(PARAM_ID_BROWSER_ID); final String name = event.getParameter(PARAM_ID_NAME); final String tooltip = event.getParameter(PARAM_ID_TOOLTIP); HandlerUtil.getActiveShellChecked(event).getDisplay().asyncExec(new Runnable() { @Override public void run() { try { IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport(); IWebBrowser browser = browserSupport.createBrowser( IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.NAVIGATION_BAR, browserId, name, tooltip); browser.openURL(url); } catch (PartInitException ex) { <START> WebBrowserUIPlugin.logError("error opening browser", ex); END> } } }); return null; }</code><technical_language>I realize opening error dialog here: frustrating opening a browser shown up. code in org.eclipse.ui.browser WebBrowserUtil.openError() report errors user</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { String urlText = event.getParameter(PARAM_ID_URL); final URL url; if (urlText == null) { url = null; } else { try { url = new URL(urlText); } catch (MalformedURLException ex) { throw new ExecutionException("malformed URL:" + urlText, ex); } } final String browserId = event.getParameter(PARAM_ID_BROWSER_ID); final String name = event.getParameter(PARAM_ID_NAME); final String tooltip = event.getParameter(PARAM_ID_TOOLTIP); HandlerUtil.getActiveShellChecked(event).getDisplay().asyncExec(new Runnable() { @Override public void run() { try { IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport(); IWebBrowser browser = browserSupport.createBrowser( IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.NAVIGATION_BAR, browserId, name, tooltip); browser.openURL(url); } catch (PartInitException ex) { WebBrowserUtil.openError(NLS.bind(Messages.errorCouldNotLaunchWebBrowser, url)); } } }); return null; }
Source:
<code>public boolean apply(ServerConfiguration conf, LedgerFlags cmdFlags) { initLedgerIdFormatter(conf, cmdFlags); long ledgerId = cmdFlags.ledgerId; if (conf.getLedgerStorageClass().equals(DbLedgerStorage.class.getName())) { if (!dumpLedgerInfo(ledgerId, conf)) { return false; } <START> } else if (conf.getLedgerStorageClass().equals(SortedLedgerStorage.class.getName()) || conf <END> .getLedgerStorageClass().equals(InterleavedLedgerStorage.class.getName())) { ServerConfiguration tConf = new ServerConfiguration(conf); InterleavedLedgerStorage interleavedLedgerStorage = new InterleavedLedgerStorage(); try { Bookie.mountLedgerStorageOffline(tConf, interleavedLedgerStorage); } catch (IOException e) { throw new UncheckedExecutionException(e.getMessage(), e); } if (cmdFlags.meta) { printMeta(ledgerId, interleavedLedgerStorage); } try { print.apply("===== LEDGER: " + ledgerIdFormatter.formatLedgerId(ledgerId) + " ====="); for (LedgerCache.PageEntries page : interleavedLedgerStorage.getIndexEntries(ledgerId)) { if (printPageEntries(page)) { return true; } } } catch (IOException e) { LOG.error("Failed to read index page"); return true; } } return true; }</code><technical_language>suggestion } else if (conf.getLedgerStorageClass().equals(SortedLedgerStorage.class.getName()) || conf.getLedgerStorageClass().equals(InterleavedLedgerStorage.class.getName())) {</technical_language>

Target:
public boolean apply(ServerConfiguration conf, LedgerFlags cmdFlags) { initLedgerIdFormatter(conf, cmdFlags); long ledgerId = cmdFlags.ledgerId; if (conf.getLedgerStorageClass().equals(DbLedgerStorage.class.getName())) { if (!dumpLedgerInfo(ledgerId, conf)) { return false; } } else if (conf.getLedgerStorageClass().equals(SortedLedgerStorage.class.getName()) || conf.getLedgerStorageClass().equals(InterleavedLedgerStorage.class.getName())) { ServerConfiguration tConf = new ServerConfiguration(conf); InterleavedLedgerStorage interleavedLedgerStorage = new InterleavedLedgerStorage(); try { Bookie.mountLedgerStorageOffline(tConf, interleavedLedgerStorage); } catch (IOException e) { throw new UncheckedExecutionException(e.getMessage(), e); } if (cmdFlags.meta) { printMeta(ledgerId, interleavedLedgerStorage); } try { print.accept("===== LEDGER: " + ledgerIdFormatter.formatLedgerId(ledgerId) + " ====="); for (LedgerCache.PageEntries page : interleavedLedgerStorage.getIndexEntries(ledgerId)) { if (printPageEntries(page)) { return true; } } } catch (IOException e) { LOG.error("Failed to read index page"); return true; } } return true; }
Source:
<code>private void updateOriginalTemplateNameOnDerivedVms() { boolean templateNameChanged = !ObjectUtils.objectsEqual(mOldTemplate.getName(), getVmTemplate().getName()); if (templateNameChanged) { <START> DbFacade.getInstance().getVmDao().updateOriginalTemplateName(getVmTemplate().getId(), getVmTemplate().getName()); <END> } }</code><technical_language>get***Dao in base class.. (in other places well)</technical_language>

Target:
private void updateOriginalTemplateNameOnDerivedVms() { boolean templateNameChanged = !ObjectUtils.equals(mOldTemplate.getName(), getVmTemplate().getName()); if (templateNameChanged) { getVmDAO().updateOriginalTemplateName(getVmTemplate().getId(), getVmTemplate().getName()); } }
Source:
<code>private void handleStatusMessage(CarbonMessage carbonMessage) { StatusCarbonMessage statusCarbonMessage = (StatusCarbonMessage) carbonMessage; if (org.wso2.carbon.messaging.Constants.STATUS_OPEN.equals(statusCarbonMessage.getStatus())) { log.info("Status open carbon message received."); Session session = (Session) statusCarbonMessage. getProperty(Constants.WEBSOCKET_SESSION); sessionList.forEach( currentSession -> { try { currentSession.getBasicRemote(). sendText(WebSocketTestConstants.PAYLOAD_NEW_CLIENT_CONNECTED); } catch (IOException e) { log.error("IO exception when sending data : " + e.getMessage(), e); } } ); sessionList.add(session); } else if (org.wso2.carbon.messaging.Constants.STATUS_CLOSE. equals(statusCarbonMessage.getStatus())) { log.info("Status closed carbon message received."); Session session = (Session) statusCarbonMessage. getProperty(Constants.WEBSOCKET_SESSION); sessionList.forEach( currentSession -> { try { currentSession.getBasicRemote(). sendText(WebSocketTestConstants.PAYLOAD_CLIENT_LEFT); } catch (IOException e) { log.error("IO exception when sending data : " + e.getMessage(), e); } <START> <END> } ); } }</code><technical_language>additional blank line</technical_language>

Target:
private void handleStatusMessage(CarbonMessage carbonMessage) { StatusCarbonMessage statusCarbonMessage = (StatusCarbonMessage) carbonMessage; if (org.wso2.carbon.messaging.Constants.STATUS_OPEN.equals(statusCarbonMessage.getStatus())) { logger.info("Status open carbon message received."); Session session = (Session) statusCarbonMessage. getProperty(Constants.WEBSOCKET_SESSION); sessionList.forEach( currentSession -> { try { currentSession.getBasicRemote(). sendText(WebSocketTestConstants.NEW_CLIENT_CONNECTED); } catch (IOException e) { logger.error("IO exception when sending data : " + e.getMessage(), e); } } ); sessionList.add(session); } else if (org.wso2.carbon.messaging.Constants.STATUS_CLOSE. equals(statusCarbonMessage.getStatus())) { logger.info("Status closed carbon message received."); sessionList.forEach( currentSession -> { try { currentSession.getBasicRemote(). sendText(WebSocketTestConstants.CLIENT_LEFT); } catch (IOException e) { logger.error("IO exception when sending data : " + e.getMessage(), e); } } ); } }
Source:
<code><START> @Test public void emptyResponse() throws IOException { <END> com.squareup.okhttp.Response okResponse = new com.squareup.okhttp.Response.Builder() .code(200).message("OK") .addHeader("foo", "bar") .addHeader("kit", "kat") .protocol(Protocol.HTTP_1_1) .request(new com.squareup.okhttp.Request.Builder() .url(HOST + "/foo/bar/") .get() .build()) .build(); Response response = OkClient.parseResponse(okResponse); assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/"); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getReason()).isEqualTo("OK"); assertThat(response.getHeaders()).hasSize(2) .containsExactly(new Header("foo", "bar"), new Header("kit", "kat")); assertThat(response.getBody()).isNull(); }</code><technical_language>(you _construct_ a null response body, get a call. cacheResponse() networkResponse() want exist bodies)</technical_language>

Target:
@Test public void emptyResponse() throws IOException { com.squareup.okhttp.Response okResponse = new com.squareup.okhttp.Response.Builder() .code(200) .message("OK") .body(new TestResponseBody("", null)) .addHeader("foo", "bar") .addHeader("kit", "kat") .protocol(Protocol.HTTP_1_1) .request(new com.squareup.okhttp.Request.Builder() .url(HOST + "/foo/bar/") .get() .build()) .build(); Response response = OkClient.parseResponse(okResponse); assertThat(response.getUrl()).isEqualTo(HOST + "/foo/bar/"); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getReason()).isEqualTo("OK"); assertThat(response.getHeaders()) .containsExactly(new Header("foo", "bar"), new Header("kit", "kat")); assertThat(response.getBody()).isNull(); }
Source:
<code>public Widget asWidget() { <START> return getView() == null ? null : getView().asWidget(); <END> }</code><technical_language>view null. If contract enforced in ctor check removed</technical_language>

Target:
public Widget asWidget() { return getView().asWidget(); }
Source:
<code>public void storeToLocalStorage(HasConsoleModel model) { if (model.isPool()) { return; } ConsoleProtocol selectedProtocol = model.getUserSelectedProtocol(); ConsoleContext context = model.getConsoleContext(); String id = model.getVM().getId().toString(); KeyMaker keyMaker = new KeyMaker(id, context); clientStorage.setLocalItem(keyMaker.make(SELECTED_PROTOCOL), selectedProtocol.toString()); <START> switch (selectedProtocol) { <END> case SPICE: storeSpiceData(model, keyMaker); break; case VNC: storeVncData(model, keyMaker); break; case RDP : storeRdpData(model, keyMaker); break; } }</code><technical_language>I if-else this is NPE vulnerable. if want a switch-case please add a null check return if selectedProtocol is null</technical_language>

Target:
public void storeToLocalStorage(HasConsoleModel model) { if (model.isPool()) { return; } ConsoleProtocol selectedProtocol = model.getUserSelectedProtocol(); ConsoleContext context = model.getConsoleContext(); String id = model.getVM().getId().toString(); KeyMaker keyMaker = new KeyMaker(id, context); clientStorage.setLocalItem(keyMaker.make(SELECTED_PROTOCOL), selectedProtocol.toString()); if (selectedProtocol == ConsoleProtocol.SPICE) { storeSpiceData(model, keyMaker); } else if (selectedProtocol == ConsoleProtocol.VNC) { storeVncData(model, keyMaker); } else if (selectedProtocol == ConsoleProtocol.RDP) { storeRdpData(model, keyMaker); } }
Source:
<code>public void execute(Runnable command) { final Runnable runnable = doWrap(command, controlPoint); try { super.execute(doIdentityWrap(runnable)); <START> } catch (RejectedExecutionException e) { <END> controlPoint.requestComplete(); throw e; } }</code><technical_language>catching Exception</technical_language>

Target:
public void execute(Runnable command) { final Runnable runnable = doWrap(command, controlPoint); try { super.execute(doIdentityWrap(runnable)); } catch (Exception e) { controlPoint.requestComplete(); throw e; } }