auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void parse() throws URISyntaxException { if (string.trim().length() == 0) { throw new URISyntaxException(string, MessageFormat.format(Messages.LocationURI_ParsePb_Blank, MENU_SCHEME, TABBAR_SCHEME)); } String[] locationsURI = string.split("\\" + LOCATION_SEPARATOR); if (locationsURI.length > 2) { throw new URISyntaxException(string, MessageFormat.format(Messages.LocationURI_ParsePb_MoreThanTwoLocations, LOCATION_SEPARATOR, locationsURI.length)); } for (int i = 0; i < locationsURI.length; i++) { if (locationsURI[i].startsWith(MENU_SCHEME)) { parseMenuURI(locationsURI[i]); } else if (locationsURI[i].startsWith(TABBAR_SCHEME)) { parseTabbarURI(locationsURI[i]); } else { throw new URISyntaxException(string, MessageFormat.format(Messages.LocationURI_ParsePb_WrongScheme, MENU_SCHEME, TABBAR_SCHEME)); } } }

Target:
private void parse() throws URISyntaxException { if (string.trim().length() == 0) { throw new URISyntaxException(string, MessageFormat.format(Messages.LocationURI_ParsePb_Blank, MENU_SCHEME, TABBAR_SCHEME)); } String[] locationsURI = string.split("\\" + LOCATION_SEPARATOR); if (locationsURI.length > 2) { throw new URISyntaxException(string, MessageFormat.format(Messages.LocationURI_ParsePb_MoreThanTwoLocations, LOCATION_SEPARATOR, locationsURI.length)); } for (int i = 0; i < locationsURI.length; i++) { String trimmedURI = locationsURI[i].trim(); if (trimmedURI.startsWith(MENU_SCHEME)) { parseMenuURI(trimmedURI); } else if (trimmedURI.startsWith(TABBAR_SCHEME)) { parseTabbarURI(trimmedURI); } else { throw new URISyntaxException(string, MessageFormat.format(Messages.LocationURI_ParsePb_WrongScheme, MENU_SCHEME, TABBAR_SCHEME)); } } }
Source:
public int complete(CommandContext ctx, String buffer, int cursor, List<String> candidates) { this.ctx = ctx; this.buffer = buffer; final ValueTypeCallbackHandler handler; try { handler = parse(buffer); } catch (CommandFormatException e) { if (LOG.isEnabled(Level.WARN)) { LOG.log(Level.WARN, e.getLocalizedMessage(), e); } return -1; } try { final Collection<String> foundCandidates = handler.getCandidates(propDescr); if (foundCandidates.isEmpty()) { return -1; } candidates.addAll(foundCandidates); return handler.getCompletionIndex(); } catch (Throwable th) { if (LOG.isEnabled(Level.WARN)) { LOG.log(Level.WARN, th.getLocalizedMessage(), th); } return -1; } }

Target:
public int complete(CommandContext ctx, String buffer, int cursor, List<String> candidates) { this.ctx = ctx; this.buffer = buffer; final ValueTypeCallbackHandler handler; try { handler = parse(buffer); } catch (CommandFormatException e) { if (LOG.isEnabled(Level.WARN)) { LOG.log(Level.WARN, e.getLocalizedMessage(), e); } return -1; } try { final Collection<String> foundCandidates = handler.getCandidates(propDescr); if (foundCandidates.isEmpty()) { return -1; } candidates.addAll(foundCandidates); return handler.getCompletionIndex(); } catch (RuntimeException ex) { if (LOG.isEnabled(Level.WARN)) { LOG.log(Level.WARN, ex.getLocalizedMessage(), ex); } return -1; } }
Source:
private static String trimSqlForDisplay(String sql) { return Pattern.compile(TRIM_SQL_PATTERN_STRING).matcher(sql).replaceAll(" "); }

Target:
private static String trimSqlForDisplay(String sql) { return sql.replaceAll("[\\s]*\\n+[\\s]*", " "); }
Source:
public static <T extends Enum<T>> WmiResult<T> queryWMI(WmiQuery<T> query) { WmiResult<T> result = WbemcliUtil.INSTANCE.new WmiResult<>(query.getPropertyEnum()); if (failedWmiClassNames.contains(query.getWmiClassName())) { return result; } try { if (!isComInitialized()) { initCOM(); } result = query.execute(wmiTimeout); } catch (COMException e) { if (!OHM_NAMESPACE.equals(query.getNameSpace())) { if (e.getHresult() == null) { LOG.warn("COM exception (HRESULT == null): {}", e.getMessage()); } else { switch (e.getHresult().intValue()) { case Wbemcli.WBEM_E_INVALID_NAMESPACE: LOG.warn("COM exception: Invalid Namespace {}", query.getNameSpace()); break; case Wbemcli.WBEM_E_INVALID_CLASS: LOG.warn("COM exception: Invalid Class {}", query.getWmiClassName()); break; case Wbemcli.WBEM_E_INVALID_QUERY: LOG.warn("COM exception: Invalid Query: {}", queryToString(query)); break; default: LOG.warn( "COM exception querying {}, which might not be on your system. Will not attempt to query it again. Error was: {}:", query.getWmiClassName(), e.getMessage()); } } failedWmiClassNames.add(query.getWmiClassName()); } } catch (TimeoutException e) { LOG.error("WMI query timed out after ms: {}", wmiTimeout, queryToString(query)); } return result; }

Target:
public static <T extends Enum<T>> WmiResult<T> queryWMI(WmiQuery<T> query) { WmiResult<T> result = WbemcliUtil.INSTANCE.new WmiResult<>(query.getPropertyEnum()); if (failedWmiClassNames.contains(query.getWmiClassName())) { return result; } try { if (!isComInitialized()) { initCOM(); } result = query.execute(wmiTimeout); } catch (COMException e) { if (!OHM_NAMESPACE.equals(query.getNameSpace())) { final int hresult = e.getHresult() == null ? -1 : e.getHresult().intValue(); switch (hresult) { case Wbemcli.WBEM_E_INVALID_NAMESPACE: LOG.warn("COM exception: Invalid Namespace {}", query.getNameSpace()); break; case Wbemcli.WBEM_E_INVALID_CLASS: LOG.warn("COM exception: Invalid Class {}", query.getWmiClassName()); break; case Wbemcli.WBEM_E_INVALID_QUERY: LOG.warn("COM exception: Invalid Query: {}", queryToString(query)); break; default: LOG.warn( "COM exception querying {}, which might not be on your system. Will not attempt to query it again. Error was: {}:", query.getWmiClassName(), e.getMessage()); } failedWmiClassNames.add(query.getWmiClassName()); } } catch (TimeoutException e) { LOG.error("WMI query timed out after ms: {}", wmiTimeout, queryToString(query)); } return result; }
Source:
public void testPhiroMoveMotorForwardBrick() { List<Integer> spinnerValuesResourceIds = Arrays.asList( R.string.phiro_motor_right, R.string.phiro_motor_left, R.string.phiro_motor_both); checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_phiro_motor_forward_action); checkIfValuesAvailableInSpinnerOnBrick(spinnerValuesResourceIds, R.id.brick_phiro_motor_forward_action_spinner, brickPosition); enterValueInFormulaTextFieldOnBrickAtPosition(SET_SPEED, R.id.brick_phiro_motor_forward_action_speed_edit_text, brickPosition); }

Target:
public void testPhiroMoveMotorForwardBrick() { checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_phiro_motor_forward_action); List<Integer> spinnerValuesResourceIds = Arrays.asList( R.string.phiro_motor_right, R.string.phiro_motor_left, R.string.phiro_motor_both); checkIfValuesAvailableInSpinnerOnBrick(spinnerValuesResourceIds, R.id.brick_phiro_motor_forward_action_spinner, brickPosition); enterValueInFormulaTextFieldOnBrickAtPosition(setSpeed, R.id.brick_phiro_motor_forward_action_speed_edit_text, brickPosition); }
Source:
public AggregateScore getSingleScore(final Long accountId, final String date) { 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, "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() ); }

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:
private String releaseDateInstant(String releaseDate) { try { int timestamp = Integer.parseInt(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); } }

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:
public void cannotNullifySets() { Subpopulation subpop = new DynamoSubpopulation(); subpop.setDataGroupsAssignedWhileConsented(null); subpop.setSubstudyIdsAssignedOnConsent(null); assertTrue(subpop.getDataGroupsAssignedWhileConsented().isEmpty()); assertTrue(subpop.getSubstudyIdsAssignedOnConsent().isEmpty()); }

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:
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; }

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:
private Disk clone(Disk parent) { Disk disk = new Disk(); disk.setId(parent.getId()); disk.setVm(new VM()); if (parent.isSetVm()) { disk.getVm().setId(parent.getVm().getId()); } return disk; }

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:
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) keyValueMap.get(entry.getKey())); lineModels.add(lineModel); } } setItems(lineModels); }

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:
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()); List<String> toAdd = new ArrayList<String>(newSpecs); 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; }

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:
public void setClientOperations(final Client client) { ArgumentVerifier.assertNotNull(client, "Client"); if(isRunning() && !clients.containsKey(client.getChannel()) && !client.isClosed() && client.getClientsSocketExecuter() == this) { 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()); } }

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:
public RuleAssert 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)))); } return this; }

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:
protected void executeCommand() { updateDefaultQuota(); 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); }

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:
public CosmosConfig getCosmosConfig() { return CosmosConfig.builder() .enableQueryMetrics(true) .responseDiagnosticsProcessor(new ResponseDiagnosticsProcessorImplementation()) .database(secondaryProperties.getDatabase()) .build(); }

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

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:
private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) { if (result.isSuccess()) { refreshListOfFilesFragment(true); } else { try { showSnackMessage( FileStorageUtils.getNewFolderName(((CreateFolderOperation) operation).getRemotePath()) + " " + getResources().getString(R.string.folder_already_exists) ); } catch (NotFoundException e) { Log_OC.e(TAG, "Error while trying to show fail message ", e); } } }

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:
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(); } throw new InvalidCronExpressionException(cronExpression); }

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:
public void searchForInGlobalNav(String query) { searchInputInGlobalNav.sendKeys(query); searchFormInGlobalNav.submit(); }

Target:
public void searchForInGlobalNav(String query) { searchInputInGlobalNav.sendKeys(query); waitForValueToBePresentInElementsAttributeByElement(searchInputInGlobalNav, "value", query); searchFormInGlobalNav.submit(); }
Source:
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); }

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:
public void shouldUpdateUsageStatisticsReporting() { UsageStatisticsReporting existing = usageStatisticsReportingSqlMapDao.load(); assertNotNull(existing); assertNotNull(existing.lastReportedAt()); dataSharingUsageStatisticsReportingService.updateLastReportedTime(); UsageStatisticsReporting loaded = usageStatisticsReportingSqlMapDao.load(); assertThat(loaded.lastReportedAt().toInstant(), is(not(existing.lastReportedAt()))); }

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:
public Optional<Map<String, ServiceConfiguration>> getServiceConfigurations() { return Optional.fromNullable(services); }

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

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:
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) { throw new Exception("Unable to retrieve installation access token."); } throw new Exception("Unable to retrieve installation access token."); }

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:
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) { writer.addMutation(upgradeDeleteMutation(olddelete)); } 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) { ; } }

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:
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); } if (currentLayer.composite == null) { graphics.setComposite(AlphaComposite.SrcOver); } else { graphics.setComposite(currentLayer.composite); } graphics.drawImage(image, 0, 0, null); ftsGraphics.dispose(); } } }

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:
public boolean isDefaultCallScreeningApp(ComponentName componentName) { try { if (isServiceConnected()) { getTelecomService().isDefaultCallScreeningApp(componentName); } } catch (RemoteException e) { Log.e(TAG, "RemoteException calling ITelecomService#isDefaultCallScreeningApp.", e); } return false; }

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:
protected Type visitComparisonExpression(ComparisonExpression node, StackableAstVisitorContext<Context> context) { Optional<DynamicFilter> dynamicFilter = getDynamicFilterOptional(node); if (dynamicFilter.isPresent()) { 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()); }

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:
public static RemoteWebDriver driver() { AbstractTestSession testSession = getTestSession(); if (testSession == null) { throw new IllegalStateException("Internal error. Test session not initialized."); } 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; }

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:
public 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 { log.friend = true; mergedLogs.add(log); } } return true; } return false; }

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:
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; } 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); } } }

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:
public void buildListOfRowKeyColumnExpressionsSingleNodeIsNullTest() throws Exception { List<Expression> expressions = new ArrayList<>(); RowKeyColumnExpression rvc1 = new RowKeyColumnExpression(); RowKeyColumnExpression rvc2 = new RowKeyColumnExpression(); IsNullExpression expression1 = mock(IsNullExpression.class); 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)); }

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:
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) { WebBrowserUIPlugin.logError("error opening browser", ex); } } }); return null; }

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:
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.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; }

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:
private void updateOriginalTemplateNameOnDerivedVms() { boolean templateNameChanged = !ObjectUtils.objectsEqual(mOldTemplate.getName(), getVmTemplate().getName()); if (templateNameChanged) { DbFacade.getInstance().getVmDao().updateOriginalTemplateName(getVmTemplate().getId(), getVmTemplate().getName()); } }

Target:
private void updateOriginalTemplateNameOnDerivedVms() { boolean templateNameChanged = !ObjectUtils.equals(mOldTemplate.getName(), getVmTemplate().getName()); if (templateNameChanged) { getVmDAO().updateOriginalTemplateName(getVmTemplate().getId(), getVmTemplate().getName()); } }
Source:
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); } } ); } }

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:
@Test public void emptyResponse() throws IOException { 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(); }

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:
public Widget asWidget() { return getView() == null ? null : getView().asWidget(); }

Target:
public Widget asWidget() { return getView().asWidget(); }