auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCompute() { DoubleLeastPostAggregator greatestPostAggregator; CountAggregator agg = new CountAggregator("rows"); agg.aggregate(); agg.aggregate(); agg.aggregate(); Map<String, Object> metricValues = new HashMap<String, Object>(); metricValues.put(agg.getName(), agg.get()); List<PostAggregator> postAggregatorList = Lists.newArrayList( new ConstantPostAggregator( "roku", 6 ), new FieldAccessPostAggregator( "rows", "rows" ) ); greatestPostAggregator = new DoubleLeastPostAggregator("least", postAggregatorList); Assert.assertEquals(3.0, greatestPostAggregator.compute(metricValues)); }

Target:
public void testCompute() { final String aggName = "rows"; DoubleLeastPostAggregator leastPostAggregator; CountAggregator agg = new CountAggregator(); agg.aggregate(); agg.aggregate(); agg.aggregate(); Map<String, Object> metricValues = new HashMap<String, Object>(); metricValues.put(aggName, agg.get()); List<PostAggregator> postAggregatorList = Lists.newArrayList( new ConstantPostAggregator( "roku", 6D ), new FieldAccessPostAggregator( "rows", aggName ) ); leastPostAggregator = new DoubleLeastPostAggregator("least", postAggregatorList); Assert.assertEquals(3.0, leastPostAggregator.compute(metricValues)); }
Source:
private Object doGetAttribute(Class<?> clazz) { ensureServletContext(); return context.getAttribute(clazz.getName()); }

Target:
private Object doGetAttribute(Class<?> clazz) { ensureServletContext(); return getContext().getAttribute(clazz.getName()); }
Source:
protected Optional<PlanNodeStatsEstimate> doCalculate(PlanNode node, StatsProvider sourceStats, Lookup lookup, Session session, Map<Symbol, Type> types) { FilterNode filterNode = (FilterNode) node; PlanNode nodeSource = lookup.resolve(filterNode.getSource()); SemiJoinNode semiJoinNode; if (nodeSource instanceof ProjectNode) { ProjectNode projectNode = (ProjectNode) nodeSource; if (!projectNode.isIdentity()) { return Optional.empty(); } PlanNode projectNodeSource = lookup.resolve(projectNode.getSource()); if (!(projectNodeSource instanceof SemiJoinNode)) { return Optional.empty(); } semiJoinNode = (SemiJoinNode) projectNodeSource; } else { if (!(nodeSource instanceof SemiJoinNode)) { return Optional.empty(); } semiJoinNode = (SemiJoinNode) nodeSource; } return calculate(filterNode, semiJoinNode, sourceStats, session, types); }

Target:
protected Optional<PlanNodeStatsEstimate> doCalculate(PlanNode node, StatsProvider sourceStats, Lookup lookup, Session session, Map<Symbol, Type> types) { FilterNode filterNode = (FilterNode) node; PlanNode nodeSource = lookup.resolve(filterNode.getSource()); SemiJoinNode semiJoinNode; if (nodeSource instanceof ProjectNode) { ProjectNode projectNode = (ProjectNode) nodeSource; if (!projectNode.isIdentity()) { return Optional.empty(); } PlanNode projectNodeSource = lookup.resolve(projectNode.getSource()); if (!(projectNodeSource instanceof SemiJoinNode)) { return Optional.empty(); } semiJoinNode = (SemiJoinNode) projectNodeSource; } else if (nodeSource instanceof SemiJoinNode) { semiJoinNode = (SemiJoinNode) nodeSource; } else { return Optional.empty(); } return calculate(filterNode, semiJoinNode, sourceStats, session, types); }
Source:
public static ZoneOffset ofHours(int hours) { checkArgument(Math.abs(hours) <= 18, "offset size must be between -18 and 18 hours inclusive"); @SuppressWarnings("NumericCastThatLosesPrecision") final int seconds = (int) Durations.toSeconds(Durations.ofHours(hours)); return ZoneOffset.newBuilder() .setAmountSeconds(seconds) .build(); }

Target:
public static ZoneOffset ofHours(int hours) { final int maxHoursBound = 18; checkArgument(Math.abs(hours) <= maxHoursBound, "offset size must be between -18 and 18 hours inclusive"); @SuppressWarnings("NumericCastThatLosesPrecision") final int seconds = (int) Durations.toSeconds(Durations.ofHours(hours)); return ZoneOffset.newBuilder() .setAmountSeconds(seconds) .build(); }
Source:
public List<Category> getCategoriesFromContent(Contentlet contentlet, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { final List<Category> cats = new ArrayList<>(); final List<com.dotmarketing.portlets.structure.model.Field> fields = new LegacyFieldTransformer( APILocator.getContentTypeAPI(APILocator.systemUser()). find(contentlet.getContentType().inode()).fields()).asOldFieldList(); for (com.dotmarketing.portlets.structure.model.Field field : fields) { if (field.getFieldType().equals(com.dotmarketing.portlets.structure.model.Field.FieldType.CATEGORY.toString())) { String catValue = contentlet.getStringProperty(field.getVelocityVarName()); if (UtilMethods.isSet(catValue)) { for (String categoryIdKeyOrVar : catValue.split("\\s*,\\s*")) { Category category = APILocator.getCategoryAPI() .find(categoryIdKeyOrVar, user, respectFrontendRoles); if (category != null && InodeUtils.isSet(category.getCategoryId())) { cats.add(category); } else { category = APILocator.getCategoryAPI() .findByKey(categoryIdKeyOrVar, user, respectFrontendRoles); if (category != null && InodeUtils .isSet(category.getCategoryId())) { cats.add(category); } else { try { category = findByVariable(categoryIdKeyOrVar, user, respectFrontendRoles); if (category != null && InodeUtils.isSet(category.getCategoryId())) { cats.add(category); } } catch (DotDataException e) { Logger.error(this, "Error finding category by variable. " + "Var name: " + categoryIdKeyOrVar, e); } } } } } } } return UtilMethods.isSet(cats)?cats:null; }

Target:
public List<Category> getCategoriesFromContent(Contentlet contentlet, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException { final List<Category> categories = new ArrayList<>(); final List<com.dotmarketing.portlets.structure.model.Field> fields = new LegacyFieldTransformer( APILocator.getContentTypeAPI(APILocator.systemUser()). find(contentlet.getContentType().inode()).fields()).asOldFieldList(); for (com.dotmarketing.portlets.structure.model.Field field : fields) { if (field.getFieldType().equals(com.dotmarketing.portlets.structure.model.Field.FieldType.CATEGORY.toString())) { final String catValue = contentlet.getStringProperty(field.getVelocityVarName()); if (UtilMethods.isSet(catValue)) { for (final String categoryIdKeyOrVar : catValue.split("\\s*,\\s*")) { Category category = APILocator.getCategoryAPI() .find(categoryIdKeyOrVar, user, respectFrontendRoles); if (category != null && InodeUtils.isSet(category.getCategoryId())) { categories.add(category); } else { category = APILocator.getCategoryAPI() .findByKey(categoryIdKeyOrVar, user, respectFrontendRoles); if (category != null && InodeUtils .isSet(category.getCategoryId())) { categories.add(category); } else { try { category = findByVariable(categoryIdKeyOrVar, user, respectFrontendRoles); if (category != null && InodeUtils.isSet(category.getCategoryId())) { categories.add(category); } } catch (DotDataException e) { Logger.error(this, "Error finding category by variable. " + "Var name: " + categoryIdKeyOrVar, e); } } } } } } } return UtilMethods.isSet(categories)?categories:null; }
Source:
public DefaultPluginDictionary(Object plugin, Locale defaultLocale, Path dir) { super(plugin, defaultLocale, Paths.get(dir.toString(), Sponge.getPluginManager().getId(plugin) + FILE_EXTENSION)); }

Target:
public DefaultPluginDictionary(Object plugin, Locale defaultLocale, Path dir) { super(plugin, defaultLocale, dir.resolve(Sponge.getPluginManager().fromInstance(plugin).get().getId() + FILE_EXTENSION)); }
Source:
public Response gatewaySynapseArtifactsGet(String gatewayLabel, MessageContext messageContext) throws APIManagementException { List<String> gatewayRuntimeArtifactsArray = new ArrayList<>(); try { List<ByteArrayInputStream> baip = apiMgtDAO.getAllGatewayPublishedAPIArtifacts(gatewayLabel); for (ByteArrayInputStream byteStream :baip){ byte[] bytes = ByteStreams.toByteArray(byteStream); String gatewayRuntimeArtifacts = new String(bytes); gatewayRuntimeArtifactsArray.add(gatewayRuntimeArtifacts); } } catch (APIManagementException | IOException e) { throw new APIManagementException("Error retrieving Artifact from DB", e); } synapseArtifactListDTOS.list(gatewayRuntimeArtifactsArray); synapseArtifactListDTOS.setCount(gatewayRuntimeArtifactsArray.size()); return Response.ok().entity(synapseArtifactListDTOS).build(); }

Target:
public Response gatewaySynapseArtifactsGet(String gatewayLabel, MessageContext messageContext) throws APIManagementException { List<String> gatewayRuntimeArtifactsArray; try { gatewayRuntimeArtifactsArray = gatewayArtifactsMgtDAO.getAllGatewayPublishedAPIArtifacts(gatewayLabel); } catch (APIManagementException e) { throw new APIManagementException("Error retrieving Artifact from DB", e); } synapseArtifactListDTOS.list(gatewayRuntimeArtifactsArray); synapseArtifactListDTOS.setCount(gatewayRuntimeArtifactsArray.size()); return Response.ok().entity(synapseArtifactListDTOS).build(); }
Source:
public void onStreamReceived(Session session, Stream stream) { Log.i(LOG_TAG, "Stream Received"); if (mSubscriber == null) { mSubscriber = (new Subscriber.Builder(this, stream)).build(); mSubscriber.setSubscriberListener(this); mSubscriber.getRenderer().setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); mSession.subscribe(mSubscriber); } }

Target:
public void onStreamReceived(Session session, Stream stream) { Log.i(LOG_TAG, "Stream Received"); if (mSubscriber == null) { mSubscriber = new Subscriber.Builder(this, stream).build(); mSubscriber.setSubscriberListener(this); mSubscriber.getRenderer().setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); mSession.subscribe(mSubscriber); } }
Source:
public void test() { String title = getViewTitle(); SWTBotView viewBot = fBot.viewByTitle(title); viewBot.show(); viewBot.setFocus(); TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(this, START_TIME)); ConditionHelpers.timeGraphIsReadyCondition((AbstractTimeGraphView) viewBot.getViewReference().getPart(false), new TmfTimeRange(START_TIME, START_TIME), START_TIME); openDialog(viewBot); SWTBotShell shell = fBot.shell("Find"); SWTBot bot = shell.bot(); SWTBotButton findButton = bot.button("Fi&nd"); String text = getFindText(); testWrapSearch(text, bot, findButton, viewBot); testDirectionSearch(true, text, bot, findButton, viewBot); testCaseSensitive(text, bot, findButton); final @NonNull String ttext = text.split(SPACE)[0]; testWholeWord(ttext, bot, findButton); testRegEx(REGEX_PREFIX + ttext, bot, findButton); testDirectionSearch(false, text, bot, findButton, viewBot); }

Target:
public void test() { String title = getViewTitle(); SWTBotView viewBot = fBot.viewByTitle(title); viewBot.show(); viewBot.setFocus(); TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(this, START_TIME)); fBot.waitUntil(ConditionHelpers.timeGraphIsReadyCondition((AbstractTimeGraphView) viewBot.getViewReference().getPart(false), new TmfTimeRange(START_TIME, START_TIME), START_TIME)); openDialog(viewBot); SWTBotShell shell = fBot.shell("Find"); SWTBot bot = shell.bot(); SWTBotButton findButton = bot.button("Fi&nd"); String text = getFindText(); testWrapSearch(text, bot, findButton, viewBot); testDirectionSearch(true, text, bot, findButton, viewBot); testCaseSensitive(text, bot, findButton); final @NonNull String ttext = text.split(SPACE)[0]; testWholeWord(ttext, bot, findButton); testRegEx(REGEX_PREFIX + ttext, bot, findButton); testDirectionSearch(false, text, bot, findButton, viewBot); }
Source:
public Map<String, Object> sampleForFields(String indexAndType, Collection<String> fields) { if (fields == null || fields.isEmpty()) { return Collections.emptyMap(); } StringBuilder sb = new StringBuilder(); sb.append("{ \"terminate_after\":1, \"size\":1,\n"); sb.append("\"_source\": ["); for (String field : fields) { sb.append(String.format(Locale.ROOT, "\"%s\",", field)); } sb.setLength(sb.length() - 1); sb.append("],\n\"query\":{"); if (esVersion().after(EsVersion.V_1_X)) { sb.append("\"bool\": { \"must\":["); } else { sb.append("\"constant_score\":{ \"filter\": { \"and\":["); } for (String field: fields) { sb.append(String.format(Locale.ROOT, "\n{ \"exists\":{ \"field\":\"%s\"} },", field)); } sb.setLength(sb.length() - 1); sb.append("\n]}"); if (esVersion().equals(EsVersion.V_2_X)) { sb.append("}"); } sb.append("}}"); Map<String, List<Map<String, Object>>> hits = parseContent(execute(GET, indexAndType + "/_search", new BytesArray(sb.toString())).body(), "hits"); List<Map<String, Object>> docs = hits.get("hits"); if (docs == null || docs.isEmpty()) { return Collections.emptyMap(); } Map<String, Object> foundFields = docs.get(0); Map<String, Object> fieldInfo = (Map<String, Object>) foundFields.get("_source"); return fieldInfo; }

Target:
public Map<String, Object> sampleForFields(String indexAndType, Collection<String> fields) { if (fields == null || fields.isEmpty()) { return Collections.emptyMap(); } StringBuilder sb = new StringBuilder(); sb.append("{ \"terminate_after\":1, \"size\":1,\n"); sb.append("\"_source\": ["); for (String field : fields) { sb.append(String.format(Locale.ROOT, "\"%s\",", field)); } sb.setLength(sb.length() - 1); sb.append("],\n\"query\":{"); if (internalVersion.onOrAfter(EsMajorVersion.V_2_X)) { sb.append("\"bool\": { \"must\":["); } else { sb.append("\"constant_score\":{ \"filter\": { \"and\":["); } for (String field: fields) { sb.append(String.format(Locale.ROOT, "\n{ \"exists\":{ \"field\":\"%s\"} },", field)); } sb.setLength(sb.length() - 1); sb.append("\n]}"); if (internalVersion.on(EsMajorVersion.V_1_X)) { sb.append("}"); } sb.append("}}"); Map<String, List<Map<String, Object>>> hits = parseContent(execute(GET, indexAndType + "/_search", new BytesArray(sb.toString())).body(), "hits"); List<Map<String, Object>> docs = hits.get("hits"); if (docs == null || docs.isEmpty()) { return Collections.emptyMap(); } Map<String, Object> foundFields = docs.get(0); Map<String, Object> fieldInfo = (Map<String, Object>) foundFields.get("_source"); return fieldInfo; }
Source:
public void passCodeEntered(String passcode) { if (!isInternetAvailable()) { passCodeView.clearPasscodeField(); return; } if (counter == 3) { Toast.makeText(getApplicationContext(), R.string.incorrect_passcode_more_than_three, Toast.LENGTH_SHORT).show(); PrefManager.clearPrefs(); startLoginActivity(); return; } if (isPassCodeLengthCorrect()) { String passwordEntered = EncryptionUtil.getHash(passCodeView.getPasscode()); if (PrefManager.getPassCode().equals(passwordEntered)) { startDashBoardActivity(); } else { counter++; passCodeView.clearPasscodeField(); Toaster.show(clRootview, R.string.incorrect_passcode); } } }

Target:
public void passCodeEntered(String passcode) { String passwordEntered = EncryptionUtil.getHash(passCodeView.getPasscode()); boolean isPassCodeCorrect = PrefManager.getPassCode().equals(passwordEntered); if (counter == 3 && !isPassCodeCorrect) { Toast.makeText(getApplicationContext(), R.string.incorrect_passcode_more_than_three, Toast.LENGTH_SHORT).show(); PrefManager.clearPrefs(); startSplashActivity(); return; } if (isPassCodeLengthCorrect()) { if (isPassCodeCorrect) { startDashBoardActivity(); } else { counter++; passCodeView.clearPasscodeField(); Toaster.show(clRootview, R.string.incorrect_passcode); } } }
Source:
public Block readBlock(BlockEncodingSerde blockEncodingSerde, SliceInput sliceInput) { Type keyType = TypeSerde.readType(typeManager, sliceInput); Block keyBlock = blockEncodingSerde.readBlock(sliceInput); Block valueBlock = blockEncodingSerde.readBlock(sliceInput); int hashTableLength = sliceInput.readInt(); int[] hashTable = null; if (hashTableLength >= 0) { hashTable = new int[hashTableLength]; sliceInput.readBytes(wrappedIntArray(hashTable)); } if (keyBlock.getPositionCount() != valueBlock.getPositionCount() || hashTable != null && keyBlock.getPositionCount() * HASH_MULTIPLIER != hashTable.length) { throw new IllegalArgumentException( format("Deserialized MapBlock violates invariants: key %d, value %d, hash %d", keyBlock.getPositionCount(), valueBlock.getPositionCount(), hashTable.length)); } int positionCount = sliceInput.readInt(); int[] offsets = new int[positionCount + 1]; sliceInput.readBytes(wrappedIntArray(offsets)); Optional<boolean[]> mapIsNull = EncoderUtil.decodeNullBits(sliceInput, positionCount); return MapType.createMapBlockInternal(typeManager, keyType, 0, positionCount, mapIsNull, offsets, keyBlock, valueBlock, Optional.ofNullable(hashTable)); }

Target:
public Block readBlock(BlockEncodingSerde blockEncodingSerde, SliceInput sliceInput) { Type keyType = TypeSerde.readType(typeManager, sliceInput); Block keyBlock = blockEncodingSerde.readBlock(sliceInput); Block valueBlock = blockEncodingSerde.readBlock(sliceInput); int hashTableLength = sliceInput.readInt(); int[] hashTable = null; if (hashTableLength >= 0) { hashTable = new int[hashTableLength]; sliceInput.readBytes(wrappedIntArray(hashTable)); } if (keyBlock.getPositionCount() != valueBlock.getPositionCount()) { throw new IllegalArgumentException( format("Deserialized MapBlock violates invariants: key %d, value %d", keyBlock.getPositionCount(), valueBlock.getPositionCount())); } if (hashTable != null && keyBlock.getPositionCount() * HASH_MULTIPLIER != hashTable.length) { throw new IllegalArgumentException( format("Deserialized MapBlock violates invariants: expected hashtable size %d, actual hashtable size %d", keyBlock.getPositionCount() * HASH_MULTIPLIER, hashTable.length)); } int positionCount = sliceInput.readInt(); int[] offsets = new int[positionCount + 1]; sliceInput.readBytes(wrappedIntArray(offsets)); Optional<boolean[]> mapIsNull = EncoderUtil.decodeNullBits(sliceInput, positionCount); return MapType.createMapBlockInternal(typeManager, keyType, 0, positionCount, mapIsNull, offsets, keyBlock, valueBlock, Optional.ofNullable(hashTable)); }
Source:
public NegotiatedTokenBinding decode(int[] serverdata) throws TlsFatalAlert { if(serverdata.length !=4){ throw new TlsFatalAlert(AlertDescription.unsupported_extension); } this.setMajorProtocolVerison(serverdata[0]); this.setMinorProtocolVerison(serverdata[1]); if(serverdata[3]==0){ this.setSelectedKeyParameter("rsa2048_pcks15"); }else if (serverdata[3]==1){ this.setSelectedKeyParameter("rsa2048_pss"); }else if (serverdata[3]==2){ this.setSelectedKeyParameter("rsa2048_ecdsap256"); }else{ throw new TlsFatalAlert(AlertDescription.unsupported_extension); } return this; }

Target:
public NegotiatedTokenBinding decode(int[] serverdata) throws TlsFatalAlert { if (serverdata.length != 4) { throw new TlsFatalAlert(AlertDescription.unsupported_extension); } this.setMajorProtocolVerison(serverdata[0]); this.setMinorProtocolVerison(serverdata[1]); if (serverdata[3] == 0) { this.setSelectedKeyParameter(RSA2048_PCKS15); } else if (serverdata[3] == 1) { this.setSelectedKeyParameter(RSA2048_PSS); } else if (serverdata[3] == 2) { this.setSelectedKeyParameter(RSA2048_ECDSAP256); } else { throw new TlsFatalAlert(AlertDescription.unsupported_extension); } return this; }
Source:
private boolean checkPreCondition(PreCondition preCondition, Vendor<? extends T> vendor, IEclipseContext context) { final Object object = context.get(preCondition.key()); if (object == null) { return false; } return object.equals(preCondition.value()); }

Target:
private boolean checkPreCondition(PreCondition preCondition, Vendor<? extends T> vendor, IEclipseContext context) { if (preCondition.value().equals(PreCondition.UNASSIGNED)) { return context.containsKey(preCondition.key()); } final Object object = context.get(preCondition.key()); if (object == null) { return false; } return object.equals(preCondition.value()); }
Source:
public Account apply(HttpResponse from) { return Account.builder() .bytesUsed(Long.parseLong(from.getFirstHeaderOrNull("X-Account-Bytes-Used"))) .containerCount(Long.parseLong(from.getFirstHeaderOrNull("X-Account-Container-Count"))) .objectCount(Long.parseLong(from.getFirstHeaderOrNull("X-Account-Object-Count"))) .metadata(EntriesWithoutMetaPrefix.INSTANCE.apply(from.getHeaders())).build(); }

Target:
public Account apply(HttpResponse from) { return Account.builder() .bytesUsed(Long.parseLong(from.getFirstHeaderOrNull(ACCOUNT_BYTES_USED))) .containerCount(Long.parseLong(from.getFirstHeaderOrNull(ACCOUNT_CONTAINER_COUNT))) .objectCount(Long.parseLong(from.getFirstHeaderOrNull(ACCOUNT_OBJECT_COUNT))) .metadata(EntriesWithoutMetaPrefix.INSTANCE.apply(from.getHeaders())).build(); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShutDownVpcVspCommand that = (ShutDownVpcVspCommand) o; if (_domainTemplateName != null ? !_domainTemplateName.equals(that._domainTemplateName) : that._domainTemplateName != null) return false; if (_domainUuid != null ? !_domainUuid.equals(that._domainUuid) : that._domainUuid != null) return false; if (_vpcUuid != null ? !_vpcUuid.equals(that._vpcUuid) : that._vpcUuid != null) return false; return true; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ShutDownVpcVspCommand)) return false; if (!super.equals(o)) return false; ShutDownVpcVspCommand that = (ShutDownVpcVspCommand) o; if (_domainTemplateName != null ? !_domainTemplateName.equals(that._domainTemplateName) : that._domainTemplateName != null) return false; if (_domainUuid != null ? !_domainUuid.equals(that._domainUuid) : that._domainUuid != null) return false; if (_vpcUuid != null ? !_vpcUuid.equals(that._vpcUuid) : that._vpcUuid != null) return false; return true; }
Source:
public JavaBeanExecutable<?> executable(Executable executable) { if ( executable instanceof Constructor ) { return new JavaBeanConstructor( (Constructor<?>) executable ); } return executable( executable.getDeclaringClass(), ( (Method) executable ) ); }

Target:
public JavaBeanExecutable<?> executable(Executable executable) { return executable( executable.getDeclaringClass(), executable ); }
Source:
private String getMethodNameAndParameters(String methodSignature) { Pattern pattern = Pattern.compile("[\\w\\$]+\\([^)]*\\)"); Matcher methodPatternMatcher = pattern.matcher(methodSignature); if (methodPatternMatcher.find()) { return methodPatternMatcher.group(); } else { throw new IllegalArgumentException(); } }

Target:
private static String getMethodNameAndParameters(String methodSignature) { Matcher methodPatternMatcher = pattern.matcher(methodSignature); if (methodPatternMatcher.find()) { return methodPatternMatcher.group(); } else { throw new IllegalArgumentException(methodSignature); } }
Source:
private void doPutGetWithExpiration(RemoteCacheManager rm, String cacheName) throws Exception { RemoteCache<String, String> cache = rm.getCache(cacheName); assertEquals(0, numEntries(server1, cacheName)); assertEquals(0, numEntries(server2, cacheName)); for (int i = 0; i < 10; i++) { cache.put("key" + i, "value" + i); } for (int i = 0; i < 10; i++) { assertEquals("value" + i, cache.get("key" + i)); } assertEquals(10, numEntries(server1, cacheName)); Thread.sleep(2100); for (int i = 0; i < 10; i++) { assertNull(cache.get("key" + i)); } }

Target:
private void doPutGetWithExpiration(RemoteCacheManager rm, String cacheName) throws Exception { RemoteCache<String, String> cache = rm.getCache(cacheName); assertEquals(0, numEntries(server1, cacheName)); assertEquals(0, numEntries(server2, cacheName)); for (int i = 0; i < 10; i++) { cache.put("key" + i, "value" + i); } for (int i = 0; i < 10; i++) { assertEquals("value" + i, cache.get("key" + i)); } assertEquals(10, numEntries(server2, cacheName)); Thread.sleep(2100); for (int i = 0; i < 10; i++) { assertNull(cache.get("key" + i)); } }
Source:
public void buildsPngImage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; final User user = base.user(new URN(urn)); user.aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkFriend(base).act( new RqRegex.Fake( new RqWithAuth(urn), "(.*)", alias ) ) ), Matchers.notNullValue() ); }

Target:
public void buildsPngImage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(new URN(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkFriend(base).act( new RqRegex.Fake( new RqWithAuth(urn), "(.*)", alias ) ) ), Matchers.notNullValue() ); }
Source:
public void initExecutor() { pageProviderService = Framework.getLocalService(PageProviderService.class); queryParametersMap = new EnumMap<>(QueryParams.class); queryParametersMap.put(QueryParams.PAGE_SIZE, PAGE_SIZE); queryParametersMap.put(QueryParams.CURRENT_PAGE_INDEX, CURRENT_PAGE_INDEX); queryParametersMap.put(QueryParams.MAX_RESULTS, MAX_RESULTS); queryParametersMap.put(QueryParams.SORT_BY, SORT_BY); queryParametersMap.put(QueryParams.SORT_ORDER, SORT_ORDER); queryParametersMap.put(QueryParams.QUERY, QUERY); queryParametersMap.put(QueryParams.ORDERED_PARAMS, ORDERED_PARAMS); langPathMap = new EnumMap<>(LangParams.class); langPathMap.put(LangParams.NXQL, NXQL); }

Target:
public void initExecutor() { pageProviderService = Framework.getService(PageProviderService.class); }
Source:
protected Object doGetValue() { Object value = null; boolean allCompSameValue = true; if (source instanceof ShapeImpl) { for (Object child : source.getChildren()) { if (child instanceof BasicCompartmentImpl) { NamedStyle valueStyle = ((View) child).getNamedStyle(styleClass, styleName); if (valueStyle != null) { if (value == null) { value = valueStyle.eGet(styleFeature); } else if (!value.equals(valueStyle.eGet(styleFeature))) { allCompSameValue = false; } } } } } return allCompSameValue ? value : getDefaultValue(); }

Target:
protected Object doGetValue() { Object value = null; boolean allCompSameValue = true; if (source instanceof View) { Iterator<?> iterator = source.getChildren().iterator(); while (iterator.hasNext() && allCompSameValue == true) { Object child = (Object) iterator.next(); if (child instanceof BasicCompartmentImpl) { NamedStyle valueStyle = ((View) child).getNamedStyle(styleClass, styleName); if (valueStyle != null) { if (value == null) { value = valueStyle.eGet(styleFeature); } else if (!value.equals(valueStyle.eGet(styleFeature))) { allCompSameValue = false; } } } } } return allCompSameValue ? value : getDefaultValue(); }
Source:
@Override public <T> T evaluate(ExecutionContext ctx, Object... args) { if (opImpl == null) opImpl = new ExpressionFactory(ctx.parent().typeFactory(), ctx.parent().conformance(), ctx.parent().opTable()).implement(this); return (T) opImpl.apply(operands.stream().map(o -> o.evaluate(ctx, args)).toArray()); }

Target:
@Override public <T> T evaluate(ExecutionContext ctx, Object... args) { if (opImpl == null) { IgniteTypeFactory typeFactory = ctx.parent().typeFactory(); SqlConformance conformance = ctx.parent().conformance(); SqlOperatorTable opTable = ctx.parent().opTable(); opImpl = new ExpressionFactory(typeFactory, conformance, opTable).implement(this); } return (T) opImpl.apply(operands.stream().map(o -> o.evaluate(ctx, args)).toArray()); }
Source:
private void startSnapShot(LatLngBounds latLngBounds, int height, int width) { if (mapSnapshotter == null) { MapSnapshotter.Options options = new MapSnapshotter.Options(width, height).withRegion(latLngBounds).withStyle(mapboxMap.getStyleUrl()); mapSnapshotter = new MapSnapshotter(SnapshotShareActivity.this, options); } else { mapSnapshotter.setSize(width, height); mapSnapshotter.setRegion(latLngBounds); mapSnapshotter.setRegion(latLngBounds); } mapSnapshotter.start(new MapSnapshotter.SnapshotReadyCallback() { @Override public void onSnapshotReady(MapSnapshot snapshot) { Bitmap bitmapOfMapSnapshotImage = snapshot.getBitmap(); Uri bmpUri = getLocalBitmapUri(bitmapOfMapSnapshotImage); Intent shareIntent = new Intent(); shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri); shareIntent.setType("image/*"); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(shareIntent, "Share map image")); hasStartedSnapshotGeneration = false; } }); }

Target:
private void startSnapShot(LatLngBounds latLngBounds, int height, int width) { if (mapSnapshotter == null) { MapSnapshotter.Options options = new MapSnapshotter.Options(width, height).withRegion(latLngBounds).withStyle(mapboxMap.getStyleUrl()); mapSnapshotter = new MapSnapshotter(SnapshotShareActivity.this, options); } else { mapSnapshotter.setSize(width, height); mapSnapshotter.setRegion(latLngBounds); mapSnapshotter.setRegion(latLngBounds); } mapSnapshotter.start(new MapSnapshotter.SnapshotReadyCallback() { @Override public void onSnapshotReady(MapSnapshot snapshot) { Bitmap bitmapOfMapSnapshotImage = snapshot.getBitmap(); Uri bmpUri = getLocalBitmapUri(bitmapOfMapSnapshotImage); Intent shareIntent = new Intent(); shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri); shareIntent.setType("image/png"); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(shareIntent, "Share map image")); hasStartedSnapshotGeneration = false; } }); }
Source:
public Table findTableOrThrow(String table) throws SchemaSyncError { Table t = findTable(table); if ( t == null ) throw new SchemaSyncError("Couldn't find table '" + table + "'" + " in database '" + this.name); return t; }

Target:
public Table findTableOrThrow(String table) throws InvalidSchemaError { Table t = findTable(table); if ( t == null ) throw new InvalidSchemaError("Couldn't find table '" + table + "'" + " in database '" + this.name); return t; }
Source:
protected boolean canDoAction() { if (getParameters() != null) { if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RUN.toString()); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM.toString()); return false; } } return true; }

Target:
protected boolean canDoAction() { if (getParameters() == null) { return false; } else if (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())) { return false; } return true; }
Source:
private boolean peekIdOrKeyword() { return peekIdOrKeyword(0); }

Target:
private boolean peekIdOrKeyword() { TokenType type = peekType(); return TokenType.IDENTIFIER == type || Keywords.isKeyword(type); }
Source:
private boolean validateListMethodsResponse(Object[] availableMethods) { if (availableMethods == null) { AppLog.e(T.NUX, "The response of system.listMethods was empty!"); return false; } String[] requiredMethods = { "wp.getUsersBlogs", "wp.getPage", "wp.getCommentStatusList", "wp.newComment", "wp.editComment", "wp.deleteComment", "wp.getComments", "wp.getComment", "wp.getOptions", "wp.uploadFile", "wp.newCategory", "wp.getTags", "wp.getCategories", "wp.editPage", "wp.deletePage", "wp.newPage", "wp.getPages" }; for (String currentRequiredMethod: requiredMethods) { boolean match = false; for (Object currentAvailableMethod: availableMethods) { if ((currentAvailableMethod).equals(currentRequiredMethod)) { match = true; continue; } } if (!match) { AppLog.e(T.NUX, "The following XML-RPC method: " + currentRequiredMethod + " is missing on the server."); return false; } } return true; }

Target:
private boolean validateListMethodsResponse(Object[] availableMethods) { if (availableMethods == null) { AppLog.e(T.NUX, "The response of system.listMethods was empty!"); return false; } String[] requiredMethods = { "wp.getUsersBlogs", "wp.getPage", "wp.getCommentStatusList", "wp.newComment", "wp.editComment", "wp.deleteComment", "wp.getComments", "wp.getComment", "wp.getOptions", "wp.uploadFile", "wp.newCategory", "wp.getTags", "wp.getCategories", "wp.editPage", "wp.deletePage", "wp.newPage", "wp.getPages" }; for (String currentRequiredMethod: requiredMethods) { boolean match = false; for (Object currentAvailableMethod: availableMethods) { if ((currentAvailableMethod).equals(currentRequiredMethod)) { match = true; break; } } if (!match) { AppLog.e(T.NUX, "The following XML-RPC method: " + currentRequiredMethod + " is missing on the server."); return false; } } return true; }
Source:
public void setClientInfo(Properties properties) throws SQLClientInfoException { if (isClosed()) { throw new SQLClientInfoException(); } if (properties != null) { if (properties.isEmpty()) { this.properties.clear(); } else { this.properties = properties; } } }

Target:
public void setClientInfo(Properties properties) throws SQLClientInfoException { if (isClosed()) { throw new SQLClientInfoException(); } if (properties == null || properties.isEmpty()) { this.properties.clear(); } else { this.properties = properties; } }
Source:
private void loadAndPut(String environment) { try (InputStream resource = getClass().getResourceAsStream("/" + environment + ".properties")) { properties.load(resource); LOG.debug("File {}.properties loaded", environment); } catch (NullPointerException | IOException whenNotFound) { LOG.debug("Could not find the file " + environment + ".properties to load.", whenNotFound); } }

Target:
private void loadAndPut(String environment) { try (InputStream resource = getClass().getResourceAsStream("/" + environment + ".properties")) { properties.load(resource); LOG.debug("File {}.properties loaded", environment); } catch (NullPointerException | IOException whenNotFound) { LOG.warn("Could not find the file " + environment + ".properties to load."); LOG.debug("Exception was " + whenNotFound); } }
Source:
public void afterCompletion(boolean committed) throws EJBException, RemoteException { log.infof("afterCompletion: transaction was%s committed", committed ? "" : " not"); checker.setSynchronizedAfter(committed); }

Target:
public void afterCompletion(boolean committed) throws EJBException, RemoteException { log.tracef("afterCompletion: transaction was%s committed", committed ? "" : " not"); checker.setSynchronizedAfter(committed); }
Source:
public boolean validateLoginDataFast() { if ( loginData == null ) { return true; } try { final HttpClient httpClient = getHttpClient(); final URI uri = new URI( StringUtils.stripEnd( loginData.getUrl(), "/ " ) + TREE_API_URL_PART ); final Credentials credentials = new UsernamePasswordCredentials( loginData.getUsername(), loginData.getPassword() ); final HttpState state = new HttpState(); state.setCredentials( new AuthScope( uri.getHost(), uri.getPort(), AuthScope.ANY_REALM ), credentials ); httpClient.setState( state ); final HttpMethod get = new GetMethod( uri.toString() ); final String authenticationString = loginData.getUsername() + ":" + loginData.getPassword(); final String base64Credentials = new Base64Encoder().encode( authenticationString.getBytes( Charset.forName( "UTF-8" ) ) ); get.setRequestHeader( AUTHORIZATION, "Basic " + base64Credentials ); final int code = httpClient.executeMethod( get ); if ( code == HttpStatus.SC_OK ) { return true; } logger.info( "Can't log in with the provided credentials. Status code: " + code ); } catch ( final IOException | URISyntaxException | IllegalArgumentException e ) { logger.info( "Can't connect to the server", e ); } return false; }

Target:
public boolean validateLoginDataFast() { if ( loginData == null ) { return true; } try { final HttpClient httpClient = getHttpClient(); final URI uri = new URI( StringUtils.stripEnd( loginData.getUrl(), "/ " ) + TREE_API_URL_PART ); final Credentials credentials = new UsernamePasswordCredentials( loginData.getUsername(), loginData.getPassword() ); final HttpState state = new HttpState(); state.setCredentials( new AuthScope( uri.getHost(), uri.getPort(), AuthScope.ANY_REALM ), credentials ); httpClient.setState( state ); final HttpMethod get = new GetMethod( uri.toString() ); final int code = httpClient.executeMethod( get ); if ( code == HttpStatus.SC_OK ) { return true; } logger.info( "Can't log in with the provided credentials. Status code: " + code ); } catch ( final IOException | URISyntaxException | IllegalArgumentException e ) { logger.info( "Can't connect to the server", e ); } return false; }
Source:
private void writeAndClose(ByteBuffer data, OutputStream to) throws IOException { try { WritableByteChannel channel = Channels.newChannel(to); channel.write(data); } finally { to.close(); } }

Target:
private void writeAndClose(ByteBuffer data, OutputStream to) throws IOException { byte[] input = data.array(); int offset = data.arrayOffset() + data.position(); int length = data.remaining(); try { to.write(input, offset, length); } finally { to.close(); } }
Source:
protected void handleRepositoryModified( final MavenRepository mavenRepository ) { try { wlManager.forceUpdateWhitelist( mavenRepository ); } catch ( IllegalStateException e ) { getLogger().info( e.getMessage() ); } }

Target:
protected void handleRepositoryModified( final MavenRepository mavenRepository ) { try { wlManager.forceUpdateWhitelist( mavenRepository ); } catch ( IllegalStateException e ) { getLogger().debug( "Repository is in bad state for white-list update: {}", RepositoryStringUtils.getHumanizedNameString( mavenRepository ), e.getMessage() ); } }
Source:
private void initModule(InputStream modulesXML, boolean isCustom) throws ScriptException { try { Context cx = RhinoEngine.enterGlobalContext(); JAXBContext jaxbContext = JAXBContext.newInstance(Module.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Module moduleObject = (Module) jaxbUnmarshaller.unmarshal(modulesXML); String moduleName = moduleObject.getName(); if (modules.get(moduleName) != null) { log.info("A module with the name : " + moduleName + " already exists and it will be overwritten."); } String namespace = moduleObject.getNamespace(); boolean expose = ("true".equals(moduleObject.getExpose())); JavaScriptModule module = new JavaScriptModule(moduleName); module.setNamespace(namespace); module.setExpose(expose); initHostObjects(moduleObject, module); initMethods(moduleObject, module); initScripts(moduleObject, cx, module, isCustom); modules.put(moduleName, module); }catch (JAXBException e) { String msg = "Error while reading the module.xml"; log.error(msg, e); throw new ScriptException(msg, e); }finally { RhinoEngine.exitContext(); } }

Target:
private void initModule(InputStream modulesXML, boolean isCustom) throws ScriptException { try { Context cx = RhinoEngine.enterGlobalContext(); JAXBContext jaxbContext = JAXBContext.newInstance(Module.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Module moduleObject = (Module) jaxbUnmarshaller.unmarshal(modulesXML); String moduleName = moduleObject.getName(); if (modules.get(moduleName) != null) { log.info("A module with the name : " + moduleName + " already exists and it will be overwritten."); } String namespace = moduleObject.getNamespace(); boolean expose = (Boolean.parseBoolean(moduleObject.getExpose()) == true); JavaScriptModule module = new JavaScriptModule(moduleName); module.setNamespace(namespace); module.setExpose(expose); initHostObjects(moduleObject, module); initMethods(moduleObject, module); initScripts(moduleObject, cx, module, isCustom); modules.put(moduleName, module); } catch (JAXBException e) { String msg = "Error while reading the module.xml"; log.error(msg, e); throw new ScriptException(msg, e); } finally { RhinoEngine.exitContext(); } }
Source:
private UserConfig(Config rc) { authorName = getNameInternal(rc, Constants.GIT_AUTHOR_NAME_KEY); if (authorName == null) { authorName = getDefaultUserName(); isAuthorNameImplicit = true; } authorEmail = getEmailInternal(rc, Constants.GIT_AUTHOR_EMAIL_KEY); if (authorEmail == null) { authorEmail = getDefaultEmail(); isAuthorEmailImplicit = true; } committerName = getNameInternal(rc, Constants.GIT_COMMITTER_NAME_KEY); if (committerName == null) { committerName = getDefaultUserName(); isCommitterNameImplicit = true; } committerEmail = getEmailInternal(rc, Constants.GIT_COMMITTER_EMAIL_KEY); if (committerEmail == null) { committerEmail = getDefaultEmail(); isCommitterEmailImplicit = true; } commitTemplatePath = getCommitTemplatePathInternal(rc, Constants.GIT_COMMIT_TEMPLATE_KEY); }

Target:
private UserConfig(Config rc) { authorName = getNameInternal(rc, Constants.GIT_AUTHOR_NAME_KEY); if (authorName == null) { authorName = getDefaultUserName(); isAuthorNameImplicit = true; } authorEmail = getEmailInternal(rc, Constants.GIT_AUTHOR_EMAIL_KEY); if (authorEmail == null) { authorEmail = getDefaultEmail(); isAuthorEmailImplicit = true; } committerName = getNameInternal(rc, Constants.GIT_COMMITTER_NAME_KEY); if (committerName == null) { committerName = getDefaultUserName(); isCommitterNameImplicit = true; } committerEmail = getEmailInternal(rc, Constants.GIT_COMMITTER_EMAIL_KEY); if (committerEmail == null) { committerEmail = getDefaultEmail(); isCommitterEmailImplicit = true; } }
Source:
public void verifyTestContent(XdEnvironment hosts, URL url, String fileName, String data) throws IOException { if (hosts.isOnEc2()) { StreamUtils.transferResultsToLocal(hosts, url, fileName); } BufferedReader reader = new BufferedReader(new FileReader(fileName)); char cbuf[] = new char[15]; String result = ""; while (reader.ready()) { int size = reader.read(cbuf); result += String.valueOf(cbuf,0, size); } if (!result.equals(data+"\n")) { reader.close(); throw new ResourceAccessException( "Data in the result file is not what was sent. Read " + result + "\n but expected " + data); } reader.close(); }

Target:
public void verifyTestContent(XdEnvironment hosts, URL url, String fileName, String data) throws IOException { if (hosts.isOnEc2()) { StreamUtils.transferResultsToLocal(hosts, url, fileName); } Reader fileReader = new InputStreamReader(new FileInputStream(fileName)); String result = FileCopyUtils.copyToString(fileReader); if (!result.equals(data + "\n")) { fileReader.close(); throw new ResourceAccessException( "Data in the result file is not what was sent. Read " + result + "\n but expected " + data); } fileReader.close(); }
Source:
public void testImportInvalidAsset() throws Exception { final int nextNodeId = m_nodeDao.getNextNodeId(); assertEquals(0, m_nodeDao.countAll()); final Resource invalidAssetFieldResource = getResource("classpath:/import_invalidAssetFieldName.xml"); m_eventManager.getEventAnticipator().anticipateEvent(getStarted(invalidAssetFieldResource)); m_eventManager.getEventAnticipator().anticipateEvent(getSuccessful(invalidAssetFieldResource)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeAdded(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeGainedInterface(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeGainedService(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeScanCompleted(nextNodeId)); m_provisioner.doImport(invalidAssetFieldResource.getURL().toString(), Boolean.TRUE.toString()); waitForEverything(); m_eventManager.getEventAnticipator().verifyAnticipated(); assertEquals(1, m_nodeDao.countAll()); OnmsNode node = m_nodeDao.get(m_nodeDao.getNodeIds().iterator().next()); assertEquals("yellow human", node.getAssetRecord().getDescription()); assertNull(node.getAssetRecord().getPollerCategory()); }

Target:
public void testImportInvalidAsset() throws Exception { final int nextNodeId = m_nodeDao.getNextNodeId(); assertEquals(0, m_nodeDao.countAll()); final Resource invalidAssetFieldResource = getResource("classpath:/import_invalidAssetFieldName.xml"); m_eventManager.getEventAnticipator().anticipateEvent(getStarted(invalidAssetFieldResource)); m_eventManager.getEventAnticipator().anticipateEvent(getSuccessful(invalidAssetFieldResource)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeAdded(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeScanStarted(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeGainedInterface(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeGainedService(nextNodeId)); m_eventManager.getEventAnticipator().anticipateEvent(getNodeScanCompleted(nextNodeId)); m_provisioner.doImport(invalidAssetFieldResource.getURL().toString(), Boolean.TRUE.toString()); waitForEverything(); m_eventManager.getEventAnticipator().verifyAnticipated(); assertEquals(1, m_nodeDao.countAll()); OnmsNode node = m_nodeDao.get(m_nodeDao.getNodeIds().iterator().next()); assertEquals("yellow human", node.getAssetRecord().getDescription()); assertNull(node.getAssetRecord().getPollerCategory()); }
Source:
protected boolean doSend(Message<?> message, long timeout) { blockGenerator.addDataWithCallback(message.getPayload(), message.getHeaders()); headersList.add(message.getHeaders()); return true; }

Target:
protected synchronized boolean doSend(Message<?> message, long timeout) { try { headersList.put(message.getHeaders()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } blockGenerator.addDataWithCallback(message.getPayload(), message.getHeaders()); return true; }
Source:
public String onnxName() { return "Erf"; }

Target:
public String onnxName() { throw new NoOpNameFoundException("No onnx op opName found for " + opName()); }
Source:
public void run() { if (!processing.isEmpty()) { String files = processing .stream() .map(AsyncFileEntry::getName) .collect(Collectors.toList()) .toString(); LOGGER.debug("{} files being processed: {}", processing.size(), files); } }

Target:
public void run() { if (LOGGER.isDebugEnabled() && !processing.isEmpty()) { String files = processing.stream().map(AsyncFileEntry::getName).collect(Collectors.joining(", ")); LOGGER.debug("{} files being processed: {}", processing.size(), files); } }
Source:
private void stopBuild(final Run build, final String jobName) throws IOException, ServletException { final String buildName = build.getDisplayName(); Executor executor = build.getExecutor(); if (executor != null) { isAnyBuildStopped = true; executor.doStop(); stdout.println(String.format("Build %s stopped for job '%s';", buildName, jobName)); } else { stdout.println(String.format("Build %s in job %s not stopped", buildName, jobName)); } }

Target:
private void stopBuild(final Run build, final String jobName) { final String buildName = build.getDisplayName(); Executor executor = build.getExecutor(); if (executor != null) { try { executor.doStop(); isAnyBuildStopped = true; stdout.println(String.format("Build '%s' stopped for job '%s'", buildName, jobName)); } catch (final Exception e) { stdout.print(String.format("Exception occurred while trying to stop build '%s' for job '%s'. ", buildName, jobName)); stdout.println(String.format("Exception class: %s, message: %s", e.getClass().getSimpleName(), e.getMessage())); } } else { stdout.println(String.format("Build '%s' in job '%s' not stopped", buildName, jobName)); } }
Source:
public ListenableFuture<ControllerResult> sendCustomCommand(@NonNull SessionCommand2 command, @Nullable Bundle args) { synchronized (mLock) { if (!mConnected) { Log.w(TAG, "Session isn't active", new IllegalStateException()); return createFutureWithResult(RESULT_CODE_DISCONNECTED); } final ResolvableFuture<ControllerResult> result = ResolvableFuture.create(); ResultReceiver cb = new ResultReceiver(mHandler) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { result.set(new ControllerResult(resultCode, resultData)); } }; mControllerCompat.sendCommand(command.getCustomCommand(), args, cb); return result; } }

Target:
public ListenableFuture<ControllerResult> sendCustomCommand(@NonNull SessionCommand2 command, @Nullable Bundle args) { synchronized (mLock) { if (!mConnected) { Log.w(TAG, "Session isn't active", new IllegalStateException()); return createFutureWithResult(RESULT_CODE_DISCONNECTED); } if (mAllowedCommands.hasCommand(command)) { mControllerCompat.getTransportControls().sendCustomAction( command.getCustomCommand(), args); return createFutureWithResult(RESULT_CODE_SUCCESS); } final ResolvableFuture<ControllerResult> result = ResolvableFuture.create(); ResultReceiver cb = new ResultReceiver(mHandler) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { result.set(new ControllerResult(resultCode, resultData)); } }; mControllerCompat.sendCommand(command.getCustomCommand(), args, cb); return result; } }