auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected boolean isDPValid() { this.counts.put("criteriaDpRequired", 1); boolean met = false; if (this.criteriaMet.containsKey("170.315 (h)(1)")) { this.counts.put("criteriaDpRequiredMet", 1); met = true; } if (this.criteriaMet.containsKey("170.315 (h)(2)")) { this.counts.put("criteriaDpRequiredMet", 1); met = true; } if(!met){ SortedSet<String> missing2 = new TreeSet<String>(); <START> missing2.add("170.315 (h)(1)"); <END> missing2.add("170.315 (h)(2)"); missingOr.add(missing2); } return (this.counts.get("criteriaDpRequiredMet") >= this.counts.get("criteriaDpRequired")); }</code><technical_language>"missing"</technical_language>

Target:
protected boolean isDPValid() { this.counts.put("criteriaDpRequired", 1); boolean met = false; if (this.criteriaMet.containsKey("170.315 (h)(1)")) { this.counts.put("criteriaDpRequiredMet", 1); met = true; } if (this.criteriaMet.containsKey("170.315 (h)(2)")) { this.counts.put("criteriaDpRequiredMet", 1); met = true; } if (!met) { ArrayList<String> missing = new ArrayList<String>(); missing.add("170.315 (h)(1)"); missing.add("170.315 (h)(2)"); missingOr.add(missing); } return (this.counts.get("criteriaDpRequiredMet") >= this.counts.get("criteriaDpRequired")); }
Source:
<code>public static <E extends CosmosClientException> void setRequestHeaders(CosmosClientException cosmosClientException, Map<String, String> requestHeaders) { <START> Map<String, String> requestHeadersMap = new HashMap<>(); <END> requestHeaders.forEach((key, value) -> { if (!key.equals(HttpConstants.HttpHeaders.AUTHORIZATION)) { requestHeadersMap.put(key, value); } }); cosmosClientException.requestHeaders = requestHeadersMap; }</code><technical_language>This create a new Map for headers, pay additional cost of Map creation. instead change filtering message is logged: this in CosmosClientException message is logged. this pay cost if message is logged. java @Override public String toString() { return getClass().getSimpleName() + "{" + "error=" + cosmosError + ", resourceAddress='" + resourceAddress + '\'' + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + filterSensitiveDate(responseHeaders) + ", requestHeaders=" + filterSensitiveDate(requestHeaders) + '}'; } private List<Map.Entry<String, String>> filterSensitiveDate(Map<String, String> requestHeaders) { return requestHeaders.entrySet().stream().filter(entry -> !HttpConstants.HttpHeaders.AUTHORIZATION.equalsIgnoreCase(entry.getKey())) .collect(Collectors.toList()); }</technical_language>

Target:
public static <E extends CosmosClientException> void setRequestHeaders(CosmosClientException cosmosClientException, Map<String, String> requestHeaders) { cosmosClientException.requestHeaders = requestHeaders; }
Source:
<code>private void cleanStartServers(final ModelNode servers, final ModelNode domainModel, OperationContext context) throws OperationFailedException { Map<String, ProcessInfo> processInfos = serverInventory.determineRunningProcesses(); for(final Property serverProp : servers.asPropertyList()) { String serverName = serverProp.getName(); String serverGroupName = serverProp.getValue().get(GROUP).asString(); <START> resolveExpressions(domainModel.require(SERVER_GROUP).require(serverGroupName), expressionResolver, true); <END> if (ServerConfigResourceDefinition.AUTO_START.resolveModelAttribute(context, serverProp.getValue()).asBoolean(true)) { ProcessInfo info = processInfos.get(serverInventory.getServerProcessName(serverName)); if ( info != null ){ serverInventory.reconnectServer(serverName, domainModel, info.getAuthKey(), info.isRunning(), info.isStopping()); } else { try { serverInventory.startServer(serverName, domainModel, START_BLOCKING, false); } catch (Exception e) { ROOT_LOGGER.failedToStartServer(e, serverName); } } } } }</code><technical_language>@soul2zimate I understand patch. Do need resolve expressions of server-groups? me, need check for presence of a server-group resource named serverGroupName. resolving expressions</technical_language>

Target:
private void cleanStartServers(final ModelNode servers, final ModelNode domainModel, OperationContext context) throws OperationFailedException { Map<String, ProcessInfo> processInfos = serverInventory.determineRunningProcesses(); for(final Property serverProp : servers.asPropertyList()) { String serverName = serverProp.getName(); if (ServerConfigResourceDefinition.AUTO_START.resolveModelAttribute(context, serverProp.getValue()).asBoolean(true)) { ProcessInfo info = processInfos.get(serverInventory.getServerProcessName(serverName)); if ( info != null ){ serverInventory.reconnectServer(serverName, domainModel, info.getAuthKey(), info.isRunning(), info.isStopping()); } else { try { serverInventory.startServer(serverName, domainModel, START_BLOCKING, false); } catch (Exception e) { ROOT_LOGGER.failedToStartServer(e, serverName); } } } } }
Source:
<code>public Response createFromWorkspace( @ApiParam( value = "Composite key", examples = @Example({ @ExampleProperty("workspace12345678"), @ExampleProperty("namespace/workspace_name"), @ExampleProperty("namespace_part_1/namespace_part_2/workspace_name") })) @PathParam("key") String key) throws NotFoundException, ServerException, BadRequestException, ConflictException, JsonProcessingException { throw new BadRequestException( <START> "This is an outdated method please use /api/workspace/devfile to create a new workspace"); <END> }</code><technical_language>Run-on sentence; explain user other api. Preferred: "This method is deprecated removed time. Please ..."</technical_language>

Target:
public Response createFromWorkspace( @ApiParam( value = "Composite key", examples = @Example({ @ExampleProperty("workspace12345678"), @ExampleProperty("namespace/workspace_name"), @ExampleProperty("namespace_part_1/namespace_part_2/workspace_name") })) @PathParam("key") String key) throws NotFoundException, ServerException, BadRequestException, ConflictException, JsonProcessingException { throw new BadRequestException( "This method is deprecated and may be removed at any time. Please use /api/workspace/devfile to create a new workspace"); }
Source:
<code>private Optional<String> getClassName(TestIdentifier testIdentifier) { TestSource testSource = testIdentifier.getSource().orElse(null); <START> if (testSource != null) { <END> if (testSource instanceof ClassSource) { return Optional.of(((ClassSource) testSource).getJavaClass().getName()); } if (testSource instanceof MethodSource) { return Optional.of(((MethodSource) testSource).getClassName()); } } return testPlan.flatMap(plan -> plan.getParent(testIdentifier)) .flatMap(this::getClassName); }</code><technical_language>This if is needed, is it</technical_language>

Target:
private Optional<String> getClassName(TestIdentifier testIdentifier) { TestSource testSource = testIdentifier.getSource().orElse(null); if (testSource instanceof ClassSource) { return Optional.of(((ClassSource) testSource).getJavaClass().getName()); } if (testSource instanceof MethodSource) { return Optional.of(((MethodSource) testSource).getClassName()); } final TestIdentifier parent = testPlan.flatMap(plan -> plan.getParent(testIdentifier)).orElse(null); if (parent == null) { return Optional.of(testClass.getName()); } return getClassName(parent); }
Source:
<code>protected void onDestroy() { <START> super.onDestroy(); <END> webView.setDownloadListener(null); }</code><technical_language>Please move super.onDestroy end of method</technical_language>

Target:
protected void onDestroy() { webView.setDownloadListener(null); super.onDestroy(); }
Source:
<code>protected TargetBundle[] resolveBundles(ITargetDefinition definition, IProgressMonitor monitor) throws CoreException { File dir = getDirectory(); if (dir.isDirectory()) { File site = getSite(dir); File[] files = site.listFiles(); SubMonitor localMonitor = SubMonitor.convert(monitor, Messages.DirectoryBundleContainer_0, files.length); List<TargetBundle> bundles = new ArrayList<>(files.length); for (File file : files) { try { TargetBundle rb = new TargetBundle(file); bundles.add(rb); } catch (CoreException e) { if (e.getStatus().getCode() == ManifestUtils.STATUS_CODE_PLUGIN_CONVERTER_UNAVAILABLE) { PDECore.log(e); } } localMonitor.step(1); } <START> localMonitor.done(); <END> return bundles.toArray(new TargetBundle[bundles.size()]); } throw new CoreException(new Status(IStatus.ERROR, PDECore.PLUGIN_ID, NLS.bind(Messages.DirectoryBundleContainer_1, dir.toString()))); }</code><technical_language>convention, code get a top-level progress monitor call done</technical_language>

Target:
protected TargetBundle[] resolveBundles(ITargetDefinition definition, IProgressMonitor monitor) throws CoreException { File dir = getDirectory(); if (dir.isDirectory()) { File site = getSite(dir); File[] files = site.listFiles(); SubMonitor localMonitor = SubMonitor.convert(monitor, Messages.DirectoryBundleContainer_0, files.length); List<TargetBundle> bundles = new ArrayList<>(files.length); for (File file : files) { try { TargetBundle rb = new TargetBundle(file); bundles.add(rb); } catch (CoreException e) { if (e.getStatus().getCode() == ManifestUtils.STATUS_CODE_PLUGIN_CONVERTER_UNAVAILABLE) { PDECore.log(e); } } localMonitor.step(1); } return bundles.toArray(new TargetBundle[bundles.size()]); } throw new CoreException(new Status(IStatus.ERROR, PDECore.PLUGIN_ID, NLS.bind(Messages.DirectoryBundleContainer_1, dir.toString()))); }
Source:
<code>public List<Object> getValue() { List<Object> values = super.getValue(); values.add( <START> new VisitableElement<Double>() { <END> @Override public String getName() { return null; } @Override public Double getValue() { return buffer; } @Override public void accept(FilterVisitor2 visitor) { visitor.visitDistanceType(this); } }); return values; }</code><technical_language>chance this cleaned up? a new subclass of VisitableXmlElementImpl LiteralElement, supports Serializable, enough</technical_language>

Target:
public List<Object> getValue() { List<Object> values = super.getValue(); values.add( new VisitableElement<Double>() { @Override public String getName() { return "Distance"; } @Override public Double getValue() { return buffer; } @Override public void accept(FilterVisitor2 visitor) { visitor.visitDistanceType(this); } }); return values; }
Source:
<code>public String toHtmlString() { StringBuilder str = new StringBuilder("<html>"); str.append("&nbsp;name: ").append("<b>") .append(component.getName()).append("</b><br>") .append("&nbsp;class: ").append("<b>") <START> .append(component.getClass().getName()).append("</b><br>"); <END> return str.toString(); }</code><technical_language>return new StringBuilder().append()....toString();</technical_language>

Target:
public String toHtmlString() { return new StringBuilder("<html>").append("&nbsp;name: ") .append("<b>").append(component.getName()) .append("</b><br>").append("&nbsp;class: ").append("<b>") .append(component.getClass().getName()).append("</b><br>") .toString(); }
Source:
<code>public void onCreate() { super.onCreate(); <START> HandlerThread thread = new HandlerThread("IntentService[" + mName + "]", Process.THREAD_PRIORITY_BACKGROUND); <END> thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); }</code><technical_language>100 columns, please :)</technical_language>

Target:
public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]", mPriority); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); }
Source:
<code>public void testHistogramMetric() { List<String> keys = new ArrayList<>(); List<String> values = new ArrayList<>(); <START> for (int i = 0; i < 1000; i++) { <END> keys.add(getRandomString()); values.add(getRandomString()); } Collections.shuffle(keys); Collections.shuffle(values); for (int i = 0; i < keys.size(); i++) { store.put(keys.get(i), values.get(i)); } metricsRegistry.getGroups().forEach(group -> metricsRegistry.getGroup(group.toString()).forEach((name, metric) -> { if (name.contains("size-bytes-histogram")) { metric.visit(new MetricsVisitor() { @Override public void counter(Counter counter) { } @Override public <T> void gauge(Gauge<T> gauge) { Assert.assertNotEquals(0D, (Double) gauge.getValue(), 0.0001); } @Override public void timer(Timer timer) { } }); } })); }</code><technical_language>builds long, do long this test runs? do instead of 1000? for max length random string generation</technical_language>

Target:
public void testHistogramMetric() { List<String> keys = new ArrayList<>(); List<String> values = new ArrayList<>(); for (int i = 0; i < 300; i++) { keys.add(getRandomString()); values.add(getRandomString()); } for (int i = 0; i < keys.size(); i++) { store.put(keys.get(i), values.get(i)); } Set<String> names = new HashSet<>(); for (Double p : serializedKeyValueStoreMetrics.record_key_size_percentiles()) { names.add(storeName + "-" + keyPrefix + "_" + p); } for (Double p : serializedKeyValueStoreMetrics.record_value_size_percentiles()) { names.add(storeName + "-" + valuePrefix + "_" + p); } metricsRegistry.getGroups().forEach(group -> metricsRegistry.getGroup(group.toString()).forEach((name, metric) -> { if (names.contains(name)) { metric.visit(new MetricsVisitor() { @Override public void counter(Counter counter) { } @Override public <T> void gauge(Gauge<T> gauge) { Double num = (Double) gauge.getValue(); Assert.assertNotEquals(0D, (Double) gauge.getValue(), 0.0001); } @Override public void timer(Timer timer) { } }); } })); }
Source:
<code>private ObjList<ExpressionNode> getOrderByAdvice(QueryModel model) { orderByAdvice.clear(); final ObjList<ExpressionNode> orderBy = model.getOrderBy(); final int len = orderBy.size(); if (len == 0) { return orderByAdvice; } CharSequenceObjHashMap<QueryColumn> map = model.getAliasToColumnMap(); for (int i = 0; i < len; i++) { <START> QueryColumn queryColumn = map.get(orderBy.getQuick(i).token); <END> if (queryColumn.getAst().type == ExpressionNode.LITERAL) { orderByAdvice.add(nextLiteral(queryColumn.getAst().token)); } } return orderByAdvice; }</code><technical_language>need more tests. is written in email - if order non-literal columns, advice empty. give selective advice sub=query</technical_language>

Target:
private ObjList<ExpressionNode> getOrderByAdvice(QueryModel model) { orderByAdvice.clear(); final ObjList<ExpressionNode> orderBy = model.getOrderBy(); final int len = orderBy.size(); if (len == 0) { return orderByAdvice; } CharSequenceObjHashMap<QueryColumn> map = model.getAliasToColumnMap(); for (int i = 0; i < len; i++) { QueryColumn queryColumn = map.get(orderBy.getQuick(i).token); if (queryColumn.getAst().type == ExpressionNode.LITERAL) { orderByAdvice.add(nextLiteral(queryColumn.getAst().token)); } else { orderByAdvice.clear(); break; } } return orderByAdvice; }
Source:
<code>public FutureResult<Void> loadDatasets(final Project project, final Collection<DatasetManifest> datasets) { notNull(project, "project"); notEmpty(datasets, "datasets"); for (DatasetManifest datasetManifest : datasets) { if (datasetManifest.getSource() == null) { <START> throw new IllegalArgumentException(format("Source for dataset '%s' is null", datasetManifest.getDataSet())); <END> } } final List<String> datasetsNames = new ArrayList<>(datasets.size()); try { final Path dirPath = Paths.get("/", project.getId() + "_" + RandomStringUtils.randomAlphabetic(3), "/"); for (DatasetManifest datasetManifest : datasets) { datasetsNames.add(datasetManifest.getDataSet()); dataStoreService.upload(dirPath.resolve(datasetManifest.getFile()).toString(), datasetManifest.getSource()); } final String manifestJson = mapper.writeValueAsString(new DatasetManifestList(datasets)); final ByteArrayInputStream inputStream = new ByteArrayInputStream(manifestJson.getBytes(UTF_8)); dataStoreService.upload(dirPath.resolve(MANIFEST_FILE_NAME).toString(), inputStream); return pullLoad(project, dirPath, datasetsNames); } catch (IOException e) { throw new DatasetException("Unable to serialize manifest", datasetsNames, e); } catch (DataStoreException | GoodDataRestException | RestClientException e) { throw new DatasetException("Unable to load", datasetsNames, e); } }</code><technical_language>check file dataset</technical_language>

Target:
public FutureResult<Void> loadDatasets(final Project project, final Collection<DatasetManifest> datasets) { notNull(project, "project"); validateUploadManifests(datasets); final List<String> datasetsNames = new ArrayList<>(datasets.size()); try { final Path dirPath = Paths.get("/", project.getId() + "_" + RandomStringUtils.randomAlphabetic(3), "/"); for (DatasetManifest datasetManifest : datasets) { datasetsNames.add(datasetManifest.getDataSet()); dataStoreService.upload(dirPath.resolve(datasetManifest.getFile()).toString(), datasetManifest.getSource()); } final String manifestJson = mapper.writeValueAsString(new DatasetManifests(datasets)); final ByteArrayInputStream inputStream = new ByteArrayInputStream(manifestJson.getBytes(UTF_8)); dataStoreService.upload(dirPath.resolve(MANIFEST_FILE_NAME).toString(), inputStream); return pullLoad(project, dirPath, datasetsNames); } catch (IOException e) { throw new DatasetException("Unable to serialize manifest", datasetsNames, e); } catch (DataStoreException | GoodDataRestException | RestClientException e) { throw new DatasetException("Unable to load", datasetsNames, e); } }
Source:
<code>public <K, V> void forward(final K key, final V value, final To to) { throwUnsupportedOperationExceptionIfStandby("forward"); final ProcessorNode<?, ?> previousNode = currentNode(); final ProcessorRecordContext previousContext = recordContext; try { toInternal.update(to); if (toInternal.hasTimestamp()) { recordContext = new ProcessorRecordContext( toInternal.timestamp(), recordContext.offset(), recordContext.partition(), recordContext.topic(), recordContext.headers()); } final String sendTo = toInternal.child(); if (currentNode() == null) { <START> throw new StreamsException("Current node is unknown when forwarding to: " + key); <END> } if (sendTo == null) { final List<ProcessorNode<?, ?>> children = currentNode().children(); for (final ProcessorNode<?, ?> child : children) { forward((ProcessorNode<K, V>) child, key, value); } } else { final ProcessorNode<K, V> child = currentNode().getChild(sendTo); if (child == null) { throw new StreamsException("Unknown downstream node: " + sendTo + " either does not exist or is not connected to this processor."); } forward(child, key, value); } } finally { recordContext = previousContext; setCurrentNode(previousNode); } }</code><technical_language>do add key ? useful potentially leak data logs. add a sentence a potential root (even if add other guards for in this PR): throw new StreamsException("Current node is unknown. This happen if forward() is called in illegal scope. root a Processor Transformer instance is shared. avoid this error, suppliers return new instances time get() is called do return object reference multiple times.");</technical_language>

Target:
public <K, V> void forward(final K key, final V value, final To to) { throwUnsupportedOperationExceptionIfStandby("forward"); final ProcessorNode<?, ?> previousNode = currentNode(); final ProcessorRecordContext previousContext = recordContext; try { toInternal.update(to); if (toInternal.hasTimestamp()) { recordContext = new ProcessorRecordContext( toInternal.timestamp(), recordContext.offset(), recordContext.partition(), recordContext.topic(), recordContext.headers()); } final String sendTo = toInternal.child(); if (currentNode() == null) { throw new StreamsException("Current node is unknown. This can happen if 'forward()' is called " + "in an illegal scope. The root cause could be that a 'Processor' or 'Transformer' instance" + " is shared. To avoid this error, make sure that your suppliers return new instances " + "each time 'get()' of Supplier is called and do not return the same object reference " + "multiple times."); } if (sendTo == null) { final List<ProcessorNode<?, ?>> children = currentNode().children(); for (final ProcessorNode<?, ?> child : children) { forward((ProcessorNode<K, V>) child, key, value); } } else { final ProcessorNode<K, V> child = currentNode().getChild(sendTo); if (child == null) { throw new StreamsException("Unknown downstream node: " + sendTo + " either does not exist or is not connected to this processor."); } forward(child, key, value); } } finally { recordContext = previousContext; setCurrentNode(previousNode); } }
Source:
<code>public Matrix select(int[] rowIndices, int[] columnIndices, Factory factory) { int newRows = rowIndices.length; int newCols = columnIndices.length; checkIndexBounds(rowIndices, this.rows); checkIndexBounds(columnIndices, this.columns); <START> Matrix newMat = factory.createMatrix(newRows, newCols); <END> for (int i = 0; i < newRows; i++) { for (int j = 0; j < newCols; j++) { newMat.set(i, j, get(rowIndices[i], columnIndices[j])); } } return newMat; }</code><technical_language>call result instead newMat</technical_language>

Target:
public Matrix select(int[] rowIndices, int[] columnIndices, Factory factory) { int newRows = rowIndices.length; int newCols = columnIndices.length; if (newRows == 0 || newCols == 0) { fail("No rows or columns selected"); } checkIndexBounds(rowIndices, rows); checkIndexBounds(columnIndices, columns); Matrix result = factory.createMatrix(newRows, newCols); for (int i = 0; i < newRows; i++) { for (int j = 0; j < newCols; j++) { result.set(i, j, get(rowIndices[i], columnIndices[j])); } } return result; }
Source:
<code>public PagingLinks build() { List<String> urls = new ArrayList<String>(); PagingLinks pagingList = new PagingLinks(); if (offset == null || limit == null || total == null) { return pagingList; } for (long i = 0; i < total; i += limit) { <START> StringBuilder url = new StringBuilder(baseUrl); <END> url.append("?"); url.append(buildParameter(offsetParameter, String.valueOf(startIndex + i))); url.append("&"); url.append(buildParameter(limitParameter, String.valueOf(limit))); for (String curKey : parameters.keySet()) { Object[] value = parameters.get(curKey); if (value != null) { url.append("&"); url.append(buildParameter(curKey, value)); } } if (i + startIndex == offset) { pagingList.setCurLink(url.toString()); } urls.add(url.toString()); } if (pagingList.getCurLink() == null) { pagingList.setCurLink(urls.get(urls.size() - 1)); } pagingList.setLinks(urls); if (pagingList.getLinks().size() > 0) { int indexOfCurLink = pagingList.getLinks().indexOf(pagingList.getCurLink()); if (indexOfCurLink != -1) { if ((indexOfCurLink + 1) < pagingList.getLinks().size()) { pagingList.setNextLink(pagingList.getLinks().get(indexOfCurLink + 1)); } if ((indexOfCurLink - 1) >= 0 && pagingList.getLinks().size() != 0) { pagingList.setPrevLink(pagingList.getLinks().get(indexOfCurLink - 1)); } } } return pagingList; }</code><technical_language>a UriBuilder (OsiamConnector/AuthService/line231</technical_language>

Target:
public PagingLinks build() { PagingLinks pagingList = new PagingLinks(); if (offset == null || limit == null || total == null) { return pagingList; } configurePagingLinks(pagingList); configurePrevAndNext(pagingList); return pagingList; }
Source:
<code>public RuntimeContext( T internalEnvironment, RuntimeIdentity identity, RuntimeInfrastructure infrastructure) { <START> this.environment = internalEnvironment; <END> this.identity = identity; this.infrastructure = infrastructure; }</code><technical_language>This is a breaking change want add some checks later. leave exceptions for now</technical_language>

Target:
public RuntimeContext( T internalEnvironment, RuntimeIdentity identity, RuntimeInfrastructure infrastructure) throws ValidationException, InfrastructureException { this.environment = internalEnvironment; this.identity = identity; this.infrastructure = infrastructure; }
Source:
<code>public boolean isGenerateDroolsTestOnError() { <START> return generateDroolsTestOnError != null && generateDroolsTestOnError.booleanValue(); <END> }</code><technical_language>getter return null if null. For Config classes, important distinguish null (= filled in) default (the null). This for example impacts programmatic API reading a solver config XML file. note solver config files written XML (see benchmark report)</technical_language>

Target:
public Boolean isGenerateDroolsTestOnError() { return generateDroolsTestOnError; }
Source:
<code>private boolean isSessionTokenValid(String actualToken) { String sessionId = request.getRequestedSessionId(); if (sessionId == null) { sessionId = session.getId(); } else { <START> sessionId = sessionId.replaceFirst("\\.node0$", ""); <END> } String expectedToken = CryptoHelper.computeSessionToken(sessionId); return actualToken.equals(expectedToken); }</code><technical_language>getRequestedSessionId is controlled front-end (client). <LINK_0> changes suggested get rid of implementation dependent removal of \\.node0$ Double submit cookie pattern is safe scenarios this: <LINK_1> of scenarios apply case (usage of subdomain HTTP instead of HTTPS)</technical_language>

Target:
private boolean isSessionTokenValid(String actualToken) { String sessionId = request.getRequestedSessionId(); if (sessionId == null) { sessionId = session.getId(); } try { return sessionId.startsWith(StringHelper.decrypt(actualToken)); } catch (InvalidParametersException e) { return false; } }
Source:
<code>public void show() { DataModelerPropertyEditorFieldInfo fieldInfo = (DataModelerPropertyEditorFieldInfo) property; RelationType relationTypeValue = (RelationType) fieldInfo.getCurrentValue( RELATION_TYPE ); if ( relationTypeValue != null ) { relationType.setSelectedValue( relationTypeValue.name( ) ); } else { relationType.setSelectedValue( DataModelerUtils.NOT_SELECTED ); } <START> GWT.log( "relationTypeValue: " + relationTypeValue ); <END> enableRelationDependentFields( relationTypeValue ); GWT.log( "1 relationTypeValue: " + relationTypeValue ); GWT.log( "2 fieldInfo.getCurrentValue( CASCADE ): " + fieldInfo.getCurrentValue( CASCADE ) ); CascadeType cascadeTypeValue = (CascadeType) fieldInfo.getCurrentValue( CASCADE ); GWT.log( "3 xxxxxxx"); if ( cascadeTypeValue != null ) { cascadeType.setSelectedValue( cascadeTypeValue.name() ); } else { cascadeType.setSelectedValue( DataModelerUtils.NOT_SELECTED ); } FetchMode fetchModeValue = (FetchMode) fieldInfo.getCurrentValue( FETCH ); if ( fetchModeValue != null ) { fetchMode.setSelectedValue( fetchModeValue.name() ); } else { fetchMode.setSelectedValue( DataModelerUtils.NOT_SELECTED ); } String mappedBy = (String) fieldInfo.getCurrentValue( MAPPED_BY ); this.mappedBy.setText( mappedBy ); Boolean orphanRemovalValue = (Boolean) fieldInfo.getCurrentValue( ORPHAN_REMOVAL ); if ( orphanRemovalValue != null) orphanRemoval.setValue( orphanRemovalValue ); super.show(); }</code><technical_language>Ouch.. GWT debugging code... I guess this problematic developing ;)</technical_language>

Target:
public void show() { DataModelerPropertyEditorFieldInfo fieldInfo = (DataModelerPropertyEditorFieldInfo) property; RelationType relationTypeValue = (RelationType) fieldInfo.getCurrentValue( RELATION_TYPE ); if ( relationTypeValue != null ) { relationType.setSelectedValue( relationTypeValue.name( ) ); } else { relationType.setSelectedValue( DataModelerUtils.NOT_SELECTED ); } enableRelationDependentFields( relationTypeValue ); CascadeType cascadeTypeValue = (CascadeType) fieldInfo.getCurrentValue( CASCADE ); if ( cascadeTypeValue != null ) { cascadeType.setSelectedValue( cascadeTypeValue.name() ); } else { cascadeType.setSelectedValue( DataModelerUtils.NOT_SELECTED ); } FetchMode fetchModeValue = (FetchMode) fieldInfo.getCurrentValue( FETCH ); if ( fetchModeValue != null ) { fetchMode.setSelectedValue( fetchModeValue.name() ); } else { fetchMode.setSelectedValue( DataModelerUtils.NOT_SELECTED ); } String mappedBy = (String) fieldInfo.getCurrentValue( MAPPED_BY ); this.mappedBy.setText( mappedBy ); Boolean orphanRemovalValue = (Boolean) fieldInfo.getCurrentValue( ORPHAN_REMOVAL ); if ( orphanRemovalValue != null) orphanRemoval.setValue( orphanRemovalValue ); super.show(); }
Source:
<code>private KeyPair getKeyPairFromAndroidKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException, InvalidAlgorithmParameterException, UnrecoverableEntryException { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); if (!keyStore.containsAlias("AdalKey")) { Logger.v(TAG, "Key entry is not available"); Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 100); final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext) .setAlias("AdalKey") .setSubject( new X500Principal(String.format("CN=%s, OU=%s", "AdalKey", mContext.getPackageName()))).setSerialNumber(BigInteger.ONE) .setStartDate(start.getTime()).setEndDate(end.getTime()).build(); final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); generator.initialize(spec); generator.generateKeyPair(); <START> Logger.v(TAG, "Key entry is generated"); <END> } else { Logger.v(TAG, "Key entry is available"); } Logger.v(TAG, "Reading Key entry"); final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry( "AdalKey", null); return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); }</code><technical_language>Suggest add additional details key added, CN=, OU = .</technical_language>

Target:
private synchronized KeyPair getKeyPairFromAndroidKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException, InvalidAlgorithmParameterException, UnrecoverableEntryException { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); if (!keyStore.containsAlias(KEY_STORE_CERT_ALIAS)) { Logger.v(TAG, "Key entry is not available"); Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 100); String certInfo = String.format("CN=%s, OU=%s", KEY_STORE_CERT_ALIAS, mContext.getPackageName()); final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext) .setAlias(KEY_STORE_CERT_ALIAS).setSubject(new X500Principal(certInfo)) .setSerialNumber(BigInteger.ONE).setStartDate(start.getTime()) .setEndDate(end.getTime()).build(); final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); generator.initialize(spec); generator.generateKeyPair(); Logger.v(TAG, "Key entry is generated for cert " + certInfo); } else { Logger.v(TAG, "Key entry is available"); } Logger.v(TAG, "Reading Key entry"); final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry( KEY_STORE_CERT_ALIAS, null); return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); }
Source:
<code>public void testSubSliceAndCopy() { byte[] byteArray = {(byte) 0, (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5}; Slice slice = new Slice(byteArray); assertCompact(slice.slice(0, slice.length())); assertCompact(Slices.copyOf(slice)); assertCompact(Slices.copyOf(slice, 0, slice.length() - 1)); <START> assertCompact(Slices.copyOf(slice, 1, slice.length() - 1)); <END> Slice subSlice1 = slice.slice(0, slice.length() - 1); Slice subSlice2 = slice.slice(1, slice.length() - 1); assertNotCompact(subSlice1); assertNotCompact(subSlice2); assertCompact(Slices.copyOf(subSlice1)); assertCompact(Slices.copyOf(subSlice2)); }</code><technical_language>Do want validate this is object? java assertSame(slice.slice(0, slice.length()), slice);</technical_language>

Target:
public void testSubSliceAndCopy() { byte[] byteArray = {(byte) 0, (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5}; Slice slice = new Slice(byteArray); assertCompact(slice); assertCompact(slice.slice(0, slice.length())); assertSame(slice.slice(0, slice.length()), slice); assertCompact(Slices.copyOf(slice)); assertNotSame(Slices.copyOf(slice).getBase(), slice.getBase()); assertCompact(Slices.copyOf(slice, 0, slice.length() - 1)); assertCompact(Slices.copyOf(slice, 1, slice.length() - 1)); Slice subSlice1 = slice.slice(0, slice.length() - 1); Slice subSlice2 = slice.slice(1, slice.length() - 1); assertNotCompact(subSlice1); assertNotCompact(subSlice2); assertCompact(Slices.copyOf(subSlice1)); assertCompact(Slices.copyOf(subSlice2)); }
Source:
<code>public static ICPPFunction createForName(char[] name) { <START> return new CPPDeferredFunction(null, name, new ICPPFunction[]{}); <END> }</code><technical_language>sense extract a constant for new ICPPFunction[]{}</technical_language>

Target:
public static ICPPFunction createForName(char[] name) { return new CPPDeferredFunction(null, name, NO_CANDIDATES); }
Source:
<code>private static void writeCookie(Writer writer, HttpCookie cookie, URL url, Date creationDate) throws IOException { String domain = ""; if (cookie.isHttpOnly()) { domain = HTTP_ONLY_PREAMBLE; } if (cookie.getDomain() != null) { domain += cookie.getDomain(); } else { domain += url.getHost(); } writer.write(domain); writer.write(COLUMN_SEPARATOR); writer.write("TRUE"); writer.write(COLUMN_SEPARATOR); String path = cookie.getPath(); if (path == null) { path = url.getPath(); } writer.write(path); writer.write(COLUMN_SEPARATOR); writer.write(Boolean.toString(cookie.getSecure()).toUpperCase()); writer.write(COLUMN_SEPARATOR); final String expirationDate; if (cookie.getMaxAge() == -1) { expirationDate = "0"; } else { <START> if (creationDate == null) { creationDate = new Date(); } <END> expirationDate = String .valueOf(creationDate.getTime() + (cookie.getMaxAge() * 1000)); } writer.write(expirationDate); writer.write(COLUMN_SEPARATOR); writer.write(cookie.getName()); writer.write(COLUMN_SEPARATOR); writer.write(cookie.getValue()); writer.write(LINE_SEPARATOR); }</code><technical_language>more consistent if cookies written creationDate</technical_language>

Target:
private static void writeCookie(Writer writer, HttpCookie cookie, URL url, Date creationDate) throws IOException { String domain = ""; if (cookie.isHttpOnly()) { domain = HTTP_ONLY_PREAMBLE; } if (cookie.getDomain() != null) { domain += cookie.getDomain(); } else { domain += url.getHost(); } writer.write(domain); writer.write(COLUMN_SEPARATOR); writer.write("TRUE"); writer.write(COLUMN_SEPARATOR); String path = cookie.getPath(); if (path == null) { path = url.getPath(); } writer.write(path); writer.write(COLUMN_SEPARATOR); writer.write(Boolean.toString(cookie.getSecure()).toUpperCase()); writer.write(COLUMN_SEPARATOR); final String expirationDate; if (cookie.getMaxAge() == -1) { expirationDate = "0"; } else { expirationDate = String .valueOf(creationDate.getTime() + (cookie.getMaxAge() * 1000)); } writer.write(expirationDate); writer.write(COLUMN_SEPARATOR); writer.write(cookie.getName()); writer.write(COLUMN_SEPARATOR); writer.write(cookie.getValue()); writer.write(LINE_SEPARATOR); }
Source:
<code>public void addLogMessageConsumer(Consumer<String> consumer) { <START> addOutPutStream(new OutputStream() { <END> StringBuilder lineBuilder = new StringBuilder(); @Override public void write(int chr) throws IOException { try { lineBuilder.append((char) chr); Matcher matcher = LOG_MESSAGE_PATTERN.matcher(lineBuilder.toString()); if (matcher.matches()) { consumer.accept(matcher.group(1)); lineBuilder = new StringBuilder(); } } catch (Exception e) { LOG.warn("Log message consumer crashed!", e); } } }); }</code><technical_language>Output</technical_language>

Target:
public void addLogMessageConsumer(Consumer<String> consumer) { checkNotNull(consumer, "consumer parameter is NULL!"); addOutPutStream(new OutputStream() { StringBuilder lineBuilder = new StringBuilder(); @Override public void write(int chr) throws IOException { try { lineBuilder.append((char) chr); Matcher matcher = LOG_MESSAGE_PATTERN.matcher(lineBuilder.toString()); if (matcher.matches()) { consumer.accept(matcher.group(1)); lineBuilder = new StringBuilder(); } } catch (Exception e) { LOG.warn("Log message consumer crashed!", e); } } }); }
Source:
<code>public String generateScript(Condition condition) throws GenerateConditionException { <START> final StringBuilder script = new StringBuilder(); <END> if (condition == null) { throw new GenerateConditionException(MISSING_CONDITION_ERROR); } if (!isValidFunction(condition.getFunction())) { throw new GenerateConditionException(MessageFormat.format(FUNCTION_NOT_FOUND_ERROR, condition.getFunction())); } String function = condition.getFunction().trim(); script.append("return "); script.append(ConditionParser.KIE_FUNCTIONS); script.append(function); script.append("("); boolean first = true; for (String param : condition.getParams()) { if (first) { script.append(param); first = false; } else { script.append(", "); script.append("\""); script.append(escapeJavaNonUTFChars(param)); script.append("\""); } if (param == null || param.isEmpty()) { throw new GenerateConditionException(PARAMETER_NULL_EMPTY); } } script.append(");"); return script.toString(); }</code><technical_language>Variable initialization closer usage</technical_language>

Target:
public String generateScript(Condition condition) throws GenerateConditionException { if (condition == null) { throw new GenerateConditionException(MISSING_CONDITION_ERROR); } if (!isValidFunction(condition.getFunction())) { throw new GenerateConditionException(MessageFormat.format(FUNCTION_NOT_FOUND_ERROR, condition.getFunction())); } final String function = condition.getFunction().trim(); final StringBuilder script = new StringBuilder(); script.append("return "); script.append(ConditionParser.KIE_FUNCTIONS); script.append(function); script.append("("); boolean first = true; for (String param : condition.getParams()) { if (param == null || param.isEmpty()) { throw new GenerateConditionException(PARAMETER_NULL_EMPTY); } if (first) { script.append(param); first = false; } else { script.append(", "); script.append("\""); script.append(escapeJavaNonUTFChars(param)); script.append("\""); } } script.append(");"); return script.toString(); }
Source:
<code>public void mustEvaluateEqualsTest() throws Exception { final Take take = req -> new RsEmpty(); new Assertion<>( "Must evaluate true equality", new FkContentType( <START> "text/xml", <END> take ), new IsEqual<>( new FkContentType( "text/xml", take ) ) ).affirm(); }</code><technical_language>@fanifieiev put content share this in local variable</technical_language>

Target:
public void mustEvaluateEqualsTest() throws Exception { final Take take = req -> new RsEmpty(); final String type = "text/xml"; new Assertion<>( "Must evaluate true equality", new FkContentType(type, take), new IsEqual<>(new FkContentType(type, take)) ).affirm(); }
Source:
<code>private void completeShutdown(final boolean cleanRun) { ENDING_SHUTDOWN so it will return false but we setState(State.PENDING_SHUTDOWN); <START> log.info("Shutting down with cleanRun {}", cleanRun); <END> try { taskManager.shutdown(cleanRun); } catch (final Throwable e) { log.error("Failed to close task manager due to the following error:", e); } try { consumer.close(); } catch (final Throwable e) { log.error("Failed to close consumer due to the following error:", e); } try { restoreConsumer.close(); } catch (final Throwable e) { log.error("Failed to close restore consumer due to the following error:", e); } streamsMetrics.removeAllThreadLevelSensors(); setState(State.DEAD); log.info("Shutdown complete"); }</code><technical_language>if need this? If shutdown is clean, logged ERROR in StreamThread#run()</technical_language>

Target:
private void completeShutdown(final boolean cleanRun) { ENDING_SHUTDOWN so it will return false but we setState(State.PENDING_SHUTDOWN); log.info("Shutting down"); try { taskManager.shutdown(cleanRun); } catch (final Throwable e) { log.error("Failed to close task manager due to the following error:", e); } try { consumer.close(); } catch (final Throwable e) { log.error("Failed to close consumer due to the following error:", e); } try { restoreConsumer.close(); } catch (final Throwable e) { log.error("Failed to close restore consumer due to the following error:", e); } streamsMetrics.removeAllThreadLevelSensors(); setState(State.DEAD); log.info("Shutdown complete"); }
Source:
<code>public static OzoneAclInfo convertOzoneAcl(OzoneAcl acl) { OzoneAclInfo.OzoneAclType aclType; switch(acl.getType()) { case USER: aclType = OzoneAclType.USER; break; case GROUP: aclType = OzoneAclType.GROUP; break; case WORLD: aclType = OzoneAclType.WORLD; break; default: throw new IllegalArgumentException("ACL type is not recognized"); } List<OzoneAclRights> aclRights = new ArrayList<>(); for(ACLType right: acl.getRights()) { try { aclRights.add(OzoneAclRights.valueOf(right.name())); } catch (IllegalArgumentException iae) { <START> LOG.error("ACL:{} right is not recognized.", acl); <END> } } return OzoneAclInfo.newBuilder().setType(aclType) .setName(acl.getName()) .addAllRights(aclRights) .build(); }</code><technical_language>This more a LOG.Error? if recognize ACL return error caller instead of ignoring continue</technical_language>

Target:
public static OzoneAclInfo convertOzoneAcl(OzoneAcl acl) { OzoneAclInfo.OzoneAclType aclType; switch (acl.getType()) { case USER: aclType = OzoneAclType.USER; break; case GROUP: aclType = OzoneAclType.GROUP; break; case WORLD: aclType = OzoneAclType.WORLD; break; case ANONYMOUS: aclType = OzoneAclType.ANONYMOUS; break; case CLIENT_IP: aclType = OzoneAclType.CLIENT_IP; break; default: throw new IllegalArgumentException("ACL type is not recognized"); } List<OzoneAclRights> aclRights = new ArrayList<>(); for (ACLType right : acl.getRights()) { aclRights.add(OzoneAclRights.valueOf(right.name())); } return OzoneAclInfo.newBuilder().setType(aclType) .setName(acl.getName()) .addAllRights(aclRights) .build(); }
Source:
<code>protected HazelcastInstance createInstance(Config config) { if (instanceFactory != null) { throw new IllegalStateException("There should not be multiple creation of TestHazelcastFactory!"); } instanceFactory = new TestHazelcastFactory(); ownerInstance = instanceFactory.newHazelcastInstance(config); ClientConfig clientConfig = new ClientConfig(); <START> clientConfig.getConnectionStrategyConfig().getConnectionRetryConfig().setClusterConnectTimeoutMillis(1_000); <END> if (config.getClassLoader() != null) { final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { clientConfig.setClassLoader(config.getClassLoader()); Thread.currentThread().setContextClassLoader(config.getClassLoader()); return instanceFactory.newHazelcastClient(clientConfig); } finally { Thread.currentThread().setContextClassLoader(tccl); } } else { return instanceFactory.newHazelcastClient(clientConfig); } }</code><technical_language>curious: motivation for this change? this lead more frequent test failures in case of hiccups</technical_language>

Target:
protected HazelcastInstance createInstance(Config config) { if (instanceFactory != null) { throw new IllegalStateException("There should not be multiple creation of TestHazelcastFactory!"); } instanceFactory = new TestHazelcastFactory(); ownerInstance = instanceFactory.newHazelcastInstance(config); ClientConfig clientConfig = new ClientConfig(); clientConfig.getConnectionStrategyConfig().getConnectionRetryConfig().setClusterConnectTimeoutMillis(10_000); if (config.getClassLoader() != null) { final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { clientConfig.setClassLoader(config.getClassLoader()); Thread.currentThread().setContextClassLoader(config.getClassLoader()); return instanceFactory.newHazelcastClient(clientConfig); } finally { Thread.currentThread().setContextClassLoader(tccl); } } else { return instanceFactory.newHazelcastClient(clientConfig); } }
Source:
<code>public JobDetails getJobById(@PathParam("cluster") String cluster, @PathParam("jobId") String jobId, @QueryParam("include") List<String> includeFields) throws IOException { LOG.info("Fetching JobDetails for jobId=" + jobId); Stopwatch timer = new Stopwatch().start(); Predicate<String> includeFilter = null; if (includeFields != null && !includeFields.isEmpty()) { includeFilter = new SerializationContext.FieldNameFilter(includeFields); } serializationContext.set(new SerializationContext( SerializationContext.DetailLevel.EVERYTHING, null, null, includeFilter, null)); JobDetails jobDetails = getJobHistoryService().getJobByJobID(cluster, jobId); timer.stop(); StringBuilder builderIncludeJobRegex = new StringBuilder(); for(String s : includeFields) { <START> builderIncludeJobRegex.append(s); <END> } if (jobDetails != null) { LOG.info("For job/{cluster}/{jobId} with input query:" + " job/" + cluster + SLASH + jobId + "&includeJobField=" + builderIncludeJobRegex + " fetched jobDetails for " + jobDetails.getJobName() + " in " + timer); } else { LOG.info("For job/{cluster}/{jobId} with input query:" + " job/" + cluster + SLASH + jobId + "&includeJobField=" + builderIncludeJobRegex + " No jobDetails found, but spent " + timer); } HravenResponseMetrics.JOB_API_LATENCY_VALUE .set(timer.elapsed(TimeUnit.MILLISECONDS)); return jobDetails; }</code><technical_language>this work? Do concatenate fields in this param delimiters</technical_language>

Target:
public JobDetails getJobById(@PathParam("cluster") String cluster, @PathParam("jobId") String jobId, @QueryParam("include") List<String> includeFields) throws IOException { LOG.info("Fetching JobDetails for jobId=" + jobId); Stopwatch timer = new Stopwatch().start(); Predicate<String> includeFilter = null; if (includeFields != null && !includeFields.isEmpty()) { includeFilter = new SerializationContext.FieldNameFilter(includeFields); } serializationContext.set(new SerializationContext( SerializationContext.DetailLevel.EVERYTHING, null, null, includeFilter, null)); JobDetails jobDetails = getJobHistoryService().getJobByJobID(cluster, jobId); timer.stop(); if (jobDetails != null) { LOG.info("For job/{cluster}/{jobId} with input query:" + " job/" + cluster + SLASH + jobId + "&" + StringUtil.buildParam("include", includeFields) + " fetched jobDetails for " + jobDetails.getJobName() + " in " + timer); } else { LOG.info("For job/{cluster}/{jobId} with input query:" + " job/" + cluster + SLASH + jobId + "&" + StringUtil.buildParam("include",includeFields) + " No jobDetails found, but spent " + timer); } HravenResponseMetrics.JOB_API_LATENCY_VALUE .set(timer.elapsed(TimeUnit.MILLISECONDS)); return jobDetails; }
Source:
<code>public void testCreateWebhookFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_webhook_create_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); WebhookApi api = autoscaleApi.getWebhookApiForZoneAndGroupAndPolicy("DFW", "1234567890", "321456"); FluentIterable<WebhookResponse> webhooks = api.create("PagerDuty", ImmutableMap.<String, Object>of("notes", "PagerDuty will fire this webhook")); assertAuthentication(server); assertRequest(server.takeRequest(), "POST", "/v1.0/888888/groups/1234567890/policies/321456/webhooks", "/autoscale_webhook_create_request.json"); <START> assertTrue(webhooks.isEmpty()); <END> } finally { server.shutdown(); } }</code><technical_language>webhooks.isEmpty(), "Expected webhooks was: " + webhooks, that</technical_language>

Target:
public void testCreateWebhookFail() throws IOException, InterruptedException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource("/autoscale_webhook_create_response.json")))); try { AutoscaleApi autoscaleApi = api(server.getUrl("/").toString(), "rackspace-autoscale", overrides); WebhookApi api = autoscaleApi.getWebhookApiForZoneAndGroupAndPolicy("DFW", "1234567890", "321456"); FluentIterable<WebhookResponse> webhooks = api.create("PagerDuty", ImmutableMap.<String, Object>of("notes", "PagerDuty will fire this webhook")); assertAuthentication(server); assertRequest(server.takeRequest(), "POST", "/v1.0/888888/groups/1234567890/policies/321456/webhooks", "/autoscale_webhook_create_request.json"); assertTrue(webhooks.isEmpty(), "Expected no webhooks, but was: " + webhooks); } finally { server.shutdown(); } }