auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void withExtensibleChannelTypeIds_shouldSetUnmodifiableExtensibleChannelTypeIds() { <START> @SuppressWarnings("null") <END> ThingType thingType = builder .withExtensibleChannelTypeIds(Arrays.asList(new String[] { "channelTypeId1", "channelTypeId2" })) .build(); assertThat(thingType.getExtensibleChannelTypeIds(), is(hasSize(2))); try { thingType.getExtensibleChannelTypeIds().add("channelTypeId"); fail(); } catch (UnsupportedOperationException e) { } }</code><technical_language>Is this needed global suppression class-level</technical_language>

Target:
public void withExtensibleChannelTypeIds_shouldSetUnmodifiableExtensibleChannelTypeIds() { ThingType thingType = builder .withExtensibleChannelTypeIds(Arrays.asList(new String[] { "channelTypeId1", "channelTypeId2" })) .build(); assertThat(thingType.getExtensibleChannelTypeIds(), is(hasSize(2))); try { thingType.getExtensibleChannelTypeIds().add("channelTypeId"); fail(); } catch (UnsupportedOperationException e) { } }
Source:
<code><START> private void startDeleteBlobAuthorizationFailTest(final OperationChain opChain) { <END> Callback<Void> callback = new TestCallback<>(opChain, false); BlobId originalId, fraudId; try { originalId = new BlobId(opChain.blobId, clusterMap); fraudId = BlobId.craft(originalId, originalId.getVersion(), (short) (originalId.getAccountId() + 1), (short) (originalId.getContainerId() + 1)); } catch (IOException e) { FutureResult<Void> future = new FutureResult<>(); future.done(null, null); callback.onCompletion(null, null); TestFuture<Void> testFuture = new TestFuture<Void>(future, genLabel("deleteBlob", true), opChain) { @Override void check() throws Exception { throw e; } }; opChain.testFutures.add(testFuture); return; } Future<Void> future = router.deleteBlob(fraudId.getID(), null, callback); TestFuture<Void> testFuture = new TestFuture<Void>(future, genLabel("deleteBlob", true), opChain) { @Override void check() throws Exception { checkExpectedRouterErrorCode(RouterErrorCode.BlobAuthorizationFailure); } }; opChain.testFutures.add(testFuture); }</code><technical_language>quick question: do blob authorization succeeded tests for delete get operations</technical_language>

Target:
private void startDeleteBlobAuthorizationFailTest(final OperationChain opChain) { Callback<Void> callback = new TestCallback<>(opChain, false); BlobId originalId, fraudId; try { originalId = new BlobId(opChain.blobId, clusterMap); fraudId = BlobId.craft(originalId, originalId.getVersion(), (short) (originalId.getAccountId() + 1), (short) (originalId.getContainerId() + 1)); } catch (IOException e) { FutureResult<Void> future = new FutureResult<>(); future.done(null, e); callback.onCompletion(null, e); TestFuture<Void> testFuture = new TestFuture<Void>(future, genLabel("deleteBlob", true), opChain) { @Override void check() throws Exception { throw e; } }; opChain.testFutures.add(testFuture); return; } Future<Void> future = router.deleteBlob(fraudId.getID(), null, callback); TestFuture<Void> testFuture = new TestFuture<Void>(future, genLabel("deleteBlob", true), opChain) { @Override void check() throws Exception { checkExpectedRouterErrorCode(RouterErrorCode.BlobAuthorizationFailure); } }; opChain.testFutures.add(testFuture); }
Source:
<code>public void testOneway() throws Exception { latch = new CountDownLatch(1); <START> Client client = ResteasyClientBuilder.newClient(); <END> WebTarget target = client.target("http://localhost:" + TestPortProvider.getPort() + "?oneway=true"); long start = System.currentTimeMillis(); Response response = target.request().put(Entity.entity("content", "text/plain")); long end = System.currentTimeMillis() - start; Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus()); Assert.assertTrue(end < 1000); Assert.assertTrue(latch.await(2, TimeUnit.SECONDS)); response.close(); }</code><technical_language>above, client needs closed</technical_language>

Target:
public void testOneway() throws Exception { latch = new CountDownLatch(1); WebTarget target = client.target("http://localhost:" + TestPortProvider.getPort() + "?oneway=true"); long start = System.currentTimeMillis(); Response response = target.request().put(Entity.entity("content", "text/plain")); long end = System.currentTimeMillis() - start; Assert.assertEquals(HttpServletResponse.SC_ACCEPTED, response.getStatus()); Assert.assertTrue(end < 1000); Assert.assertTrue(latch.await(2, TimeUnit.SECONDS)); response.close(); }
Source:
<code>public MessageGroup getMessageGroup(Object groupId) { List<Object> allMessages = new LinkedList<Object>(); List<String> list = sortedKeys((String) groupId); for (String key : list) { List<?> messages = this.getRedisTemplate().boundListOps(key).range(0, -1); allMessages.addAll(messages); } <START> return new SimpleMessageGroup((Collection<? extends Message<?>>) allMessages, groupId); <END> }</code><technical_language>I works for you, for fails: > incompatible types: List<Object> converted Collection<? extends Message<?>> > return new SimpleMessageGroup((Collection<? extends Message<?>>) allMessages, groupId);</technical_language>

Target:
public MessageGroup getMessageGroup(Object groupId) { Assert.isInstanceOf(String.class, groupId); List<Message<?>> allMessages = new LinkedList<Message<?>>(); List<String> list = sortedKeys((String) groupId); for (String key : list) { List<Message<?>> messages = this.getRedisTemplate().boundListOps(key).range(0, -1); allMessages.addAll(messages); } return new SimpleMessageGroup(allMessages, groupId); }
Source:
<code>public void testInvalidCondition() throws Exception { final String query = "and if(length(user())>0,sleep(10),2)"; <START> final String s = SQLUtil.sanitizeParameter( query ); <END> assertNotNull(s); assertEquals(StringPool.BLANK, s); }</code><technical_language>SQL.sanitizeCondition also</technical_language>

Target:
public void testInvalidCondition() throws Exception { final String query = "and if(length(user())>0,sleep(10),2)"; final String s = SQLUtil.sanitizeCondition( query ); assertNotNull(s); assertEquals(StringPool.BLANK, s); }
Source:
<code>public CompareWidget(final CompareConfig compareConfig, final String themeId, LoaderFactory loaderFactory) { this.compareConfig = compareConfig; this.frame = new Frame(GWT.getModuleBaseURL() + "/Compare.html"); initWidget(frame); setSize("100%", "100%"); <START> final MessageLoader loader = loaderFactory.newLoader(); <END> loader.show(); frame.getElement().getStyle().setBorderStyle(Style.BorderStyle.NONE); AsyncPromiseHelper.RequestCall<Window> call = new AsyncPromiseHelper.RequestCall<Window>() { @Override public void makeCall(final AsyncCallback<Window> callback) { frame.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { frame.getElement().cast(); final JsIFrameElement iFrame = frame.getElement().cast(); callback.onSuccess(iFrame.getContentWindow()); loader.hide(); } }); } }; framePromise = PromiseHelper.newPromise(call); framePromise.then(new Operation<Window>() { @Override public void apply(Window arg) throws OperationException { sendThemeId(arg, themeId); } }); framePromise.then(new Operation<Window>() { @Override public void apply(Window arg) throws OperationException { sendConfig(arg, compareConfig); } }); }</code><technical_language>need loader here</technical_language>

Target:
public CompareWidget(final CompareConfig compareConfig, final String themeId, LoaderFactory loaderFactory) { this.compareConfig = compareConfig; this.frame = new Frame(GWT.getModuleBaseURL() + "/Compare.html"); initWidget(frame); setSize("100%", "100%"); final MessageLoader loader = loaderFactory.newLoader(); loader.show(); frame.getElement().getStyle().setBorderStyle(Style.BorderStyle.NONE); AsyncPromiseHelper.RequestCall<Window> call = new AsyncPromiseHelper.RequestCall<Window>() { @Override public void makeCall(final AsyncCallback<Window> callback) { frame.addLoadHandler(new LoadHandler() { @Override public void onLoad(LoadEvent event) { frame.getElement().cast(); final JsIFrameElement iFrame = frame.getElement().cast(); callback.onSuccess(iFrame.getContentWindow()); loader.hide(); } }); } }; framePromise = PromiseHelper.newPromise(call); framePromise.then(new Operation<Window>() { @Override public void apply(Window arg) throws OperationException { sendThemeId(arg, themeId); } }); framePromise.then(new Operation<Window>() { @Override public void apply(final Window arg) throws OperationException { arg.getDocument().addEventListener("onThemeLoaded", new EventListener() { @Override public void handleEvent(Event evt) { sendConfig(arg, compareConfig); loader.hide(); } }, false); } }); }
Source:
<code><START> protected void checkRightFileType(ResourceInterface resourcePrototype, String fileName) { <END> boolean isRight = false; if (fileName.length() > 0) { String docType = fileName.substring(fileName.lastIndexOf('.') + 1).trim(); String[] types = resourcePrototype.getAllowedFileTypes(); isRight = isValidType(docType, types); } else { isRight = true; } if (!isRight) { this.addFieldError("upload", this.getText("error.resource.file.wrongFormat")); } }</code><technical_language>This method some logging. Especially in case file type is invalid</technical_language>

Target:
protected void checkRightFileType(ResourceInterface resourcePrototype, String fileName) { boolean isRight = false; if (fileName.length() > 0) { logger.debug("Check uploaded file type for ", fileName); String docType = fileName.substring(fileName.lastIndexOf('.') + 1).trim(); String[] types = resourcePrototype.getAllowedFileTypes(); isRight = isValidType(docType, types); } else { logger.debug("Check uploaded file type: file format is right for ", fileName); isRight = true; } if (!isRight) { logger.debug("Check uploaded file type: wrong file format for ", fileName); this.addFieldError("upload", this.getText("error.resource.file.wrongFormat")); } }
Source:
<code>public synchronized long skip(long n) throws IOException { <START> throw new IOException("skip not supported"); <END> }</code><technical_language>implement this</technical_language>

Target:
public synchronized long skip(long n) { if (n < 0) { return 0; } long totalSkippedBytes = min(n, remainingBytes); n = totalSkippedBytes; while (n > 0) { if (currentBufferPosition >= currentBuffer.length) { advanceCurrentBuffer(); } int skippedBytes = (int) min(n, currentBuffer.length - currentBufferPosition); n -= skippedBytes; currentBufferPosition += skippedBytes; } remainingBytes -= totalSkippedBytes; return totalSkippedBytes; }
Source:
<code>public void testAppendPath() { <START> assertEquals("services/data/v28.0/chatter/foo", new ConnectUriBuilder().appendPath("foo").toString()); <END> assertEquals("services/data/v28.0/chatter/foo/bar", new ConnectUriBuilder().appendPath("foo").appendPath("bar") .toString()); assertEquals("services/data/v28.0/chatter/foo/bar", new ConnectUriBuilder().appendPath("foo/bar").toString()); }</code><technical_language>wanna API version constant for v28.0, switching this up</technical_language>

Target:
public void testAppendPath() { assertEquals(connectPath + "foo", new ConnectUriBuilder().appendPath("foo").toString()); assertEquals(connectPath + "foo/bar", new ConnectUriBuilder().appendPath("foo").appendPath("bar") .toString()); assertEquals(connectPath + "foo/bar", new ConnectUriBuilder().appendPath("foo/bar").toString()); }
Source:
<code>public static <T> EventStep<AttributesImpl, T, byte[], String> binary() { return BinaryMarshaller.<AttributesImpl, T, byte[], String>builder() .map(AttributesImpl::marshal) .map(Accessor::extensionsOf) .map(ExtensionFormat::marshal) .map(HeaderMapper::map) <START> .map(Json::binaryMarshal) <END> .builder(Wire::new); }</code><technical_language>payload json</technical_language>

Target:
public static <T> EventStep<AttributesImpl, T, byte[], String> binary() { return binary(Json::binaryMarshal); }
Source:
<code>public void exportData(Configuration config, SessionManagementMethod sessionMethod) { if (!(sessionMethod instanceof ScriptBasedSessionManagementMethod)) { throw new UnsupportedSessionManagementMethodException( "Script based session management type only supports: " + ScriptBasedSessionManagementMethod.class.getName()); } <START> ScriptBasedSessionManagementMethod method = <END> (ScriptBasedSessionManagementMethod) sessionMethod; config.setProperty(CONTEXT_CONFIG_SESSION_MGMT_SCRIPT_NAME, method.script.getName()); config.setProperty( CONTEXT_CONFIG_SESSION_MGMT_SCRIPT_PARAMS, EncodingUtils.mapToString(method.paramValues)); }</code><technical_language>Needs read script name parameters session</technical_language>

Target:
public void exportData(Configuration config, SessionManagementMethod sessionMethod) { if (!(sessionMethod instanceof ScriptBasedSessionManagementMethod)) { throw new UnsupportedSessionManagementMethodException( "Script based session management type only supports: " + ScriptBasedSessionManagementMethod.class.getName()); } ScriptBasedSessionManagementMethod method = (ScriptBasedSessionManagementMethod) sessionMethod; if (method.script != null) { config.setProperty(CONTEXT_CONFIG_SESSION_MGMT_SCRIPT_NAME, method.script.getName()); } config.setProperty( CONTEXT_CONFIG_SESSION_MGMT_SCRIPT_PARAMS, EncodingUtils.mapToString(method.paramValues)); }
Source:
<code>public void setRadius(Long radius) { <START> if (geolocationType.toString().equalsIgnoreCase("Notification")) { <END> this.radius = radius; } else { this.radius = null; } }</code><technical_language>enum comparison if availabe string comparison... im this business logic here, a bit obscure</technical_language>

Target:
public void setRadius(Long radius) { if (geolocationType.toString().equals(GeolocationType.Notification)) { this.radius = radius; } else { this.radius = null; } }
Source:
<code>public PhoenixRemoteUserExtractor(Configuration conf) { this.requestRemoteUserExtractor = new HttpRequestRemoteUserExtractor(); this.doAsParam = conf.get(QueryServices.QUERY_SERVER_DOAS_PARAM, QueryServicesOptions.DEFAULT_QUERY_SERVER_DOAS_PARAM); this.paramRemoteUserExtractor = new HttpQueryStringParameterRemoteUserExtractor(doAsParam); <START> this.enableDoAs = conf.getBoolean(QueryServices.QUERY_SERVER_DOAS_ENABLED_ATTRIB, <END> QueryServicesOptions.DEFAULT_QUERY_SERVER_DOAS_ENABLED); }</code><technical_language>move this check of enable doAs selectively call withRemoteUserExtractor, please</technical_language>

Target:
public PhoenixRemoteUserExtractor(Configuration conf) { this.requestRemoteUserExtractor = new HttpRequestRemoteUserExtractor(); this.userExtractParam = conf.get(QueryServices.QUERY_SERVER_REMOTEUSEREXTRACTOR_PARAM, QueryServicesOptions.DEFAULT_QUERY_SERVER_REMOTEUSEREXTRACTOR_PARAM); this.paramRemoteUserExtractor = new HttpQueryStringParameterRemoteUserExtractor(userExtractParam); }
Source:
<code>protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().setSoftLimit(DateUtils.addMinutes(new Date(), <START> Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval))); <END> int maxSessionInterval = Config.<Integer> getValue(ConfigValues.MaxSessionTimeoutInterval); Date validTo = maxSessionInterval != 0 ? DateUtils.addMinutes(new Date(), maxSessionInterval) : null; try { Date fromExtension = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); if (validTo != null) { validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }</code><technical_language>call refresh</technical_language>

Target:
protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().refresh(); int userSessionHardLimit = Config.<Integer> getValue(ConfigValues.UserSessionHardLimit); Date validTo = userSessionHardLimit != 0 ? DateUtils.addMinutes(new Date(), userSessionHardLimit) : null; try { Date fromExtension = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); if (validTo != null) { validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } else { validTo = fromExtension; } } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }
Source:
<code>private String getName(ITestResult iTestResult) { String suitePrefix = getCurrentSuitePrefix(iTestResult); StringBuilder sb = new StringBuilder(suitePrefix); sb.append(iTestResult.getName()); if (!AllureConfig.newInstance().areTestNgParametersDisabled()) <START> { <END> Object[] parameters = iTestResult.getParameters(); if (parameters != null && parameters.length > 0) { sb.append("["); for (Object parameter : parameters) { sb.append(parameter).append(","); } sb.replace(sb.length() - 1, sb.length(), "]"); } } return sb.toString(); }</code><technical_language>remove new line</technical_language>

Target:
private String getName(ITestResult iTestResult) { String suitePrefix = getCurrentSuitePrefix(iTestResult); StringBuilder sb = new StringBuilder(suitePrefix); sb.append(iTestResult.getName()); if (AllureConfig.newInstance().areTestNgParametersEnabled()) { Object[] parameters = iTestResult.getParameters(); if (parameters != null && parameters.length > 0) { sb.append("["); for (Object parameter : parameters) { sb.append(parameter).append(","); } sb.replace(sb.length() - 1, sb.length(), "]"); } } return sb.toString(); }
Source:
<code><START> private void verifyCourseArchivedInDatastore(String instructorId, CourseAttributes course) { <END> ThreadHelper.waitFor(500); assertEquals(getArchivedCourse(instructorId, course.getId()), course); }</code><technical_language>methods instead of in backdoor? (just verifyPresentInDatastore for example)</technical_language>

Target:
private void verifyCourseArchivedInDatastore(String instructorId, CourseAttributes course) { int retryLimit = 5; CourseAttributes actual = getArchivedCourse(instructorId, course.getId()); while (actual == null && retryLimit > 0) { retryLimit--; ThreadHelper.waitFor(1000); actual = getArchivedCourse(instructorId, course.getId()); } assertEquals(actual, course); }
Source:
<code>public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final ActivityCalendar other = (ActivityCalendar) obj; <START> if (this.calendarName == null) { <END> if (other.calendarName != null) { return false; } } else if (!this.calendarName.equals(other.calendarName)) { return false; } if (this.activatePassiveCalendarTime == null) { if (other.activatePassiveCalendarTime != null) { return false; } } else if (!this.activatePassiveCalendarTime.equals(other.activatePassiveCalendarTime)) { return false; } if (this.seasonProfileList == null) { if (other.seasonProfileList != null) { return false; } } else if (!this.seasonProfileList.equals(other.seasonProfileList)) { return false; } return true; }</code><technical_language>If fields null, more null checks needed. In this case, I suggest lines for comparison, like: Objects.equals(this.calendarName, other.calendarName); If fields null, null-checking in equals hashCode</technical_language>

Target:
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final ActivityCalendar other = (ActivityCalendar) obj; if (!this.calendarName.equals(other.calendarName)) { return false; } if (!this.activatePassiveCalendarTime.equals(other.activatePassiveCalendarTime)) { return false; } if (!this.seasonProfileList.equals(other.seasonProfileList)) { return false; } return true; }
Source:
<code>public Profile getCurrentProfile() { if(cachedProfile != null) { return cachedProfile; } <START> return (Profile)storageManager.getStorage(Profile.STORAGE_KEY).read(profile); <END> }</code><technical_language>set cachedProfile return</technical_language>

Target:
public Profile getCurrentProfile() { if (cachedProfile == null) { this.cachedProfile = (Profile)storageManager.getStorage(Profile.STORAGE_KEY).read(profile); } return cachedProfile; }
Source:
<code>private String replaceQueriesWithVariables(String eval) { if (null == queryVars) { queryVars = new HashMap<>(); } queryVars.clear(); List<String> queries = new ArrayList<String>(); <START> Matcher m = Pattern.compile("q\\(.*?\\)").matcher(eval); <END> while (m.find()) { queries.add(m.group()); } int varNum = 0; for (String q : queries) { String var = null; QueryFunc qf = new QueryFunc(q); if (queryVars.containsValue(qf)) { for (Map.Entry<String, QueryFunc> e : queryVars.entrySet()) { if (e.getValue().equals(qf)) { var = e.getKey(); break; } } } else { var = "q" + varNum++; queryVars.put(var, qf); } eval = eval.replaceFirst("q\\(.*?\\)", var); } return eval; }</code><technical_language>Minor optimization. If this pattern is static part of class</technical_language>

Target:
private String replaceQueriesWithVariables(String eval) { if (null == queryVars) { queryVars = new HashMap<>(); } queryVars.clear(); List<String> queries = new ArrayList<String>(); Matcher m = PATTERN_QUERY_VAR.matcher(eval); while (m.find()) { queries.add(m.group()); } int varNum = 0; for (String q : queries) { String var = null; QueryFunc qf = new QueryFunc(q); if (queryVars.containsValue(qf)) { for (Map.Entry<String, QueryFunc> e : queryVars.entrySet()) { if (e.getValue().equals(qf)) { var = e.getKey(); break; } } } else { var = "q" + varNum++; queryVars.put(var, qf); } eval = eval.replaceFirst("q\\(.*?\\)", var); } return eval; }
Source:
<code>public int score() { <START> <END> switch(this.yachtCategory) { case ONES: return Arrays.stream(dice) .filter(n -> n==1) .sum(); case TWOS: return Arrays.stream(dice) .filter(n -> n==2) .sum(); case THREES: return Arrays.stream(dice) .filter(n -> n==3) .sum(); case FOURS: return Arrays.stream(dice) .filter(n -> n==4) .sum(); case FIVES: return Arrays.stream(dice) .filter(n -> n==5) .sum(); case SIXES: return Arrays.stream(dice) .filter(n -> n==6) .sum(); case FULL_HOUSE: Collection<Long> occurrences = Arrays.stream(dice) .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .values(); return occurrences.contains(2L) && occurrences.contains(3L) ? Arrays.stream(dice).sum() : 0; case FOUR_OF_A_KIND: return Arrays.stream(dice) .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(x -> x.getValue() >= 4) .map(Map.Entry::getKey) .findFirst() .orElse(0) * 4; case LITTLE_STRAIGHT: Arrays.sort(dice); return Arrays.equals(dice, new int[]{ 1, 2, 3, 4, 5 }) ? 30 : 0; case BIG_STRAIGHT: Arrays.sort(dice); return Arrays.equals(dice, new int[]{ 2, 3, 4, 5, 6 }) ? 30 : 0; case CHOICE: return Arrays.stream(dice).sum(); case YACHT: return (Arrays.stream(dice).distinct().count() == 1) ? 50 : 0; default: return 0; } }</code><technical_language>Extra line removed match constructor</technical_language>

Target:
int score() { switch(this.yachtCategory) { case ONES: return Arrays.stream(dice) .filter(n -> n == 1) .sum(); case TWOS: return Arrays.stream(dice) .filter(n -> n == 2) .sum(); case THREES: return Arrays.stream(dice) .filter(n -> n == 3) .sum(); case FOURS: return Arrays.stream(dice) .filter(n -> n == 4) .sum(); case FIVES: return Arrays.stream(dice) .filter(n -> n == 5) .sum(); case SIXES: return Arrays.stream(dice) .filter(n -> n == 6) .sum(); case FULL_HOUSE: Collection<Long> occurrences = Arrays.stream(dice) .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .values(); return occurrences.contains(2L) && occurrences.contains(3L) ? Arrays.stream(dice).sum() : 0; case FOUR_OF_A_KIND: return Arrays.stream(dice) .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(x -> x.getValue() >= 4) .map(Map.Entry::getKey) .findFirst() .orElse(0) * 4; case LITTLE_STRAIGHT: Arrays.sort(dice); return Arrays.equals(dice, new int[]{ 1, 2, 3, 4, 5 }) ? 30 : 0; case BIG_STRAIGHT: Arrays.sort(dice); return Arrays.equals(dice, new int[]{ 2, 3, 4, 5, 6 }) ? 30 : 0; case CHOICE: return Arrays.stream(dice).sum(); case YACHT: return (Arrays.stream(dice).distinct().count() == 1) ? 50 : 0; default: return 0; } }
Source:
<code>public MatchPredicateBuilder<ElasticsearchSearchPredicateBuilder> match(String absoluteFieldPath) { ElasticsearchScopedIndexFieldComponent<ElasticsearchFieldPredicateBuilderFactory> fieldComponent = scopeModel.getSchemaNodeComponent( <START> absoluteFieldPath, PREDICATE_BUILDER_FACTORY_RETRIEVAL_STRATEGY, DslConverter.DISABLED ); <END> return fieldComponent.getComponent().createMatchPredicateBuilder( searchContext, absoluteFieldPath, fieldComponent.getCompatibilityChecker() ); }</code><technical_language>in mind remove "DslConverter" parameter here</technical_language>

Target:
public MatchPredicateBuilder<ElasticsearchSearchPredicateBuilder> match(String absoluteFieldPath) { ElasticsearchScopedIndexFieldComponent<ElasticsearchFieldPredicateBuilderFactory> fieldComponent = scopeModel.getSchemaNodeComponent( absoluteFieldPath, PREDICATE_BUILDER_FACTORY_RETRIEVAL_STRATEGY, DslConverter.DISABLED ); return fieldComponent.getComponent().createMatchPredicateBuilder( searchContext, absoluteFieldPath, fieldComponent.getConverterCompatibilityChecker() ); }
Source:
<code>private void addError(final SAMValidationError error) { if (this.errorsToIgnore.contains(error.getType())) return; if ( error.getType().severity == SAMValidationError.Severity.WARNING) { if ( this.ignoreWarnings ) { return; } this.numWarnings++; <START> } else { <END> this.numErrors++; } this.errorsByType.increment(error.getType()); if (verbose) { out.println(error); out.flush(); if (this.errorsByType.getCount() >= maxVerboseOutput) { throw new MaxOutputExceededException(); } } }</code><technical_language>protect this a new Severity level</technical_language>

Target:
private void addError(final SAMValidationError error) { if (this.errorsToIgnore.contains(error.getType())) return; switch (error.getType().severity) { case WARNING: if ( this.ignoreWarnings ) { return; } this.numWarnings++; break; case ERROR: this.numErrors++; break; default: throw new SAMException("Unknown SAM validation error severity: " + error.getType().severity); } this.errorsByType.increment(error.getType()); if (verbose) { out.println(error); out.flush(); if (this.errorsByType.getCount() >= maxVerboseOutput) { throw new MaxOutputExceededException(); } } }
Source:
<code>public T createHosted(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "The Docker registry (Tools only)") @QueryParam("registry") String registry, @ApiParam(value = "The repository name", required = true) @QueryParam("name") String name, @ApiParam(value = "The descriptor type (Workflows only)") @QueryParam("descriptorType") String descriptorType, @ApiParam(value = "The Docker namespace (Tools only)") @QueryParam("namespace") String namespace, @ApiParam(value = "Optional entry name (Tools only)") @QueryParam("entryName") String entryName) { final long currentCount = getEntryDAO().countAllHosted(user.getId()); <START> User updatedUser = userDAO.findById(user.getId()); <END> final int limit = updatedUser.getHostedEntryCountLimit() != null ? updatedUser.getHostedEntryCountLimit() : calculatedEntryLimit; if (currentCount >= limit) { throw new CustomWebApplicationException("You have " + currentCount + " workflows which is at the current limit of " + limit, HttpStatus.SC_PAYMENT_REQUIRED); } DescriptorLanguage convertedDescriptorType = checkType(descriptorType); Registry convertedRegistry = checkRegistry(registry); T entry = getEntry(user, convertedRegistry, name, convertedDescriptorType, namespace, entryName); checkForDuplicatePath(entry); long l = getEntryDAO().create(entry); T byId = getEntryDAO().findById(l); elasticManager.handleIndexUpdate(byId, ElasticMode.UPDATE); return byId; }</code><technical_language>Hmmm, more efficient invalidate cache a user's limits changed checking time. <LINK_0></technical_language>

Target:
public T createHosted(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "The Docker registry (Tools only)") @QueryParam("registry") String registry, @ApiParam(value = "The repository name", required = true) @QueryParam("name") String name, @ApiParam(value = "The descriptor type (Workflows only)") @QueryParam("descriptorType") String descriptorType, @ApiParam(value = "The Docker namespace (Tools only)") @QueryParam("namespace") String namespace, @ApiParam(value = "Optional entry name (Tools only)") @QueryParam("entryName") String entryName) { final long currentCount = getEntryDAO().countAllHosted(user.getId()); final int limit = user.getHostedEntryCountLimit() != null ? user.getHostedEntryCountLimit() : calculatedEntryLimit; if (currentCount >= limit) { throw new CustomWebApplicationException("You have " + currentCount + " workflows which is at the current limit of " + limit, HttpStatus.SC_PAYMENT_REQUIRED); } DescriptorLanguage convertedDescriptorType = checkType(descriptorType); Registry convertedRegistry = checkRegistry(registry); T entry = getEntry(user, convertedRegistry, name, convertedDescriptorType, namespace, entryName); checkForDuplicatePath(entry); long l = getEntryDAO().create(entry); T byId = getEntryDAO().findById(l); elasticManager.handleIndexUpdate(byId, ElasticMode.UPDATE); return byId; }
Source:
<code>public GDAXTrades getGDAXTradesExtended(CurrencyPair currencyPair, Long after, Integer limit) throws IOException { for (;;) { try { if (rateLimited) { long delta = Duration.between(lastCall, Instant.now()).toMillis(); log.debug("Last call ms ago", delta); if (delta < 333) { try { log.debug("Sleeping for {}ms", 333-delta); Thread.sleep(333-delta); } catch (InterruptedException e) { e.printStackTrace(); } } else if (delta > 3000) { log.debug("Clearing rate limiter"); rateLimited = false; } } lastCall = Instant.now(); GDAXTrades gdaxTrades = this.gdax.getTradesPageable( currencyPair.base.getCurrencyCode(), currencyPair.counter.getCurrencyCode(), after, limit); log.debug("GDAXTrades: earliest={}, latest={}, {}", gdaxTrades.getEarliestTradeId(), gdaxTrades.getLatestTradeId(), gdaxTrades); return gdaxTrades; } catch (GDAXException e) { if (e.getHttpStatusCode() == 429) { log.debug("Rate limit exceeded, sleeping for 1000ms"); rateLimited = true; try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); <START> } <END> log.debug("Retrying"); } else { e.printStackTrace(); throw handleError(e); } } } }</code><technical_language>this PR build maven pushing? seams maven fix formatting</technical_language>

Target:
public GDAXTrades getGDAXTradesExtended(CurrencyPair currencyPair, Long after, Integer limit) throws IOException { for (; ; ) { try { if (rateLimited) { long delta = Duration.between(lastCall, Instant.now()).toMillis(); log.debug("Last call ms ago", delta); if (delta < 333) { try { log.debug("Sleeping for {}ms", 333 - delta); Thread.sleep(333 - delta); } catch (InterruptedException e) { log.debug("Unexpected exception in getGDAXTradesExtended", e); } } else if (delta > 3000) { log.debug("Clearing rate limiter"); rateLimited = false; } } lastCall = Instant.now(); GDAXTrades gdaxTrades = this.gdax.getTradesPageable( currencyPair.base.getCurrencyCode(), currencyPair.counter.getCurrencyCode(), after, limit); log.debug( "GDAXTrades: earliest={}, latest={}, {}", gdaxTrades.getEarliestTradeId(), gdaxTrades.getLatestTradeId(), gdaxTrades); return gdaxTrades; } catch (GDAXException e) { if (e.getHttpStatusCode() == 429) { log.debug("Rate limit exceeded, sleeping for 1000ms"); rateLimited = true; try { Thread.sleep(1000); } catch (InterruptedException e1) { log.debug("Unexpected exception in getGDAXTradesExtended", e1); } log.debug("Retrying"); } else { log.debug("Uncaught exception in getGDAXTradesExtended", e); throw handleError(e); } } } }
Source:
<code>public FormValidation doCheckEndPointUrl(@QueryParameter String value) { <START> Jenkins.getActiveInstance().checkPermission(Jenkins.ADMINISTER); <END> if (Util.fixEmpty(value) == null) return FormValidation.validateRequired(value); try { new URL(value); } catch (MalformedURLException ex) { return FormValidation.error(ex, "The endpoint must be URL"); } return FormValidation.ok(); }</code><technical_language>Hmm... getActiveInstance() is deprecated in modern versions of Jenkins (as is getInstance()) - Jenkins.get() is favored days (ever Jenkins version 2.98). update this code already-outdated call, a idea bump minimum version of Jenkins required 2.98 (we require Java 8, _actually_ Jenkins 1.642.3 anymore) call Jenkins.get() instead. @olivergondza WDYT</technical_language>

Target:
public FormValidation doCheckEndPointUrl(@QueryParameter String value) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); if (Util.fixEmpty(value) == null) return FormValidation.validateRequired(value); try { new URL(value); } catch (MalformedURLException ex) { return FormValidation.error(ex, "The endpoint must be URL"); } return FormValidation.ok(); }
Source:
<code>private void testOldClientNewServer() throws Exception { if (!config.mvStore) { <START> return; <END> } Server server = org.h2.tools.Server.createTcpServer(); server.start(); int port = server.getPort(); assertThrows(ErrorCode.DRIVER_VERSION_ERROR_2, driver).connect( "jdbc:h2:tcp://localhost:" + port + "/mem:test", null); server.stop(); Class<?> serverClass = cl.loadClass("org.h2.tools.Server"); Method m; m = serverClass.getMethod("createTcpServer", String[].class); Object serverOld = m.invoke(null, new Object[] { new String[] { "-tcpPort", "" + port } }); m = serverOld.getClass().getMethod("start"); m.invoke(serverOld); Connection conn; conn = org.h2.Driver.load().connect("jdbc:h2:mem:", null); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("call 1"); rs.next(); assertEquals(1, rs.getInt(1)); conn.close(); m = serverOld.getClass().getMethod("stop"); m.invoke(serverOld); }</code><technical_language>test is PageStore-only. disabled, especially in way. I a fix in #1123</technical_language>

Target:
private void testOldClientNewServer() throws Exception { Server server = org.h2.tools.Server.createTcpServer(); server.start(); int port = server.getPort(); assertThrows(ErrorCode.DRIVER_VERSION_ERROR_2, driver).connect( "jdbc:h2:tcp://localhost:" + port + "/mem:test", null); server.stop(); Class<?> serverClass = cl.loadClass("org.h2.tools.Server"); Method m; m = serverClass.getMethod("createTcpServer", String[].class); Object serverOld = m.invoke(null, new Object[] { new String[] { "-tcpPort", "" + port } }); m = serverOld.getClass().getMethod("start"); m.invoke(serverOld); Connection conn; conn = org.h2.Driver.load().connect("jdbc:h2:mem:", null); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("call 1"); rs.next(); assertEquals(1, rs.getInt(1)); conn.close(); m = serverOld.getClass().getMethod("stop"); m.invoke(serverOld); }
Source:
<code>public abstract List<FindResult> getAll() throws IOException; public abstract long getLastModifiedTime(UUID id) throws IOException; public abstract VideoInfo getVideoInfo(UUID id) throws IOException; public abstract Video getVideo(UUID id) throws IOException; public abstract void save(Video video) throws IOException; public abstract void delete(UUID id) throws IOException; <START> public void invalidate(UUID id) { <END> }</code><technical_language>// Do nothing</technical_language>

Target:
public abstract FindResults getAll() throws IOException; public abstract long getLastModifiedTime(UUID id) throws IOException; public abstract VideoInfo getVideoInfo(UUID id) throws IOException; public abstract Video getVideo(UUID id) throws IOException; public abstract void save(Video video) throws IOException; public abstract void delete(UUID id) throws IOException; public void invalidate(UUID id) { }
Source:
<code><START> protected DefaultRecord(int sizeInBytes, <END> byte attributes, long offset, long timestamp, int sequence, ByteBuffer key, ByteBuffer value, Header[] headers) { this.sizeInBytes = sizeInBytes; this.attributes = attributes; this.offset = offset; this.timestamp = timestamp; this.sequence = sequence; this.key = key; this.value = value; this.headers = headers; }</code><technical_language>Default access is good enough is consistent PartialDefaultRecord</technical_language>

Target:
DefaultRecord(int sizeInBytes, byte attributes, long offset, long timestamp, int sequence, ByteBuffer key, ByteBuffer value, Header[] headers) { this.sizeInBytes = sizeInBytes; this.attributes = attributes; this.offset = offset; this.timestamp = timestamp; this.sequence = sequence; this.key = key; this.value = value; this.headers = headers; }
Source:
<code><START> private boolean isTryStatementResource(VariableTree variable) { <END> final TryStatementTree tryStatement = getEnclosingTryStatement(variable); return tryStatement != null && tryStatement.resources().contains(variable); }</code><technical_language>This static</technical_language>

Target:
private static boolean isTryStatementResource(VariableTree variable) { final TryStatementTree tryStatement = getEnclosingTryStatement(variable); return tryStatement != null && tryStatement.resources().contains(variable); }
Source:
<code>protected Factory<?> createValueFactory(final Parameter parameter) { final Class<?> classType = parameter.getRawType(); <START> Auth auth = parameter.getAnnotation(Auth.class); <END> if (auth == null) { return null; } if (classType.isAssignableFrom(this.factory.getGeneratedClass())) { return this.factory.clone(auth.required()); } else { return null; } }</code><technical_language>this final</technical_language>

Target:
protected Factory<?> createValueFactory(final Parameter parameter) { final Class<?> classType = parameter.getRawType(); final Auth auth = parameter.getAnnotation(Auth.class); if (auth != null && classType.isAssignableFrom(factory.getGeneratedClass())) { return factory.clone(auth.required()); } else { return null; } }
Source:
<code>public byte[] toBinary() { return new byte[] { (byte) maxVertices, (byte) simpVertMin, <START> (byte) tolerance <END> }; }</code><technical_language>casting a byte work</technical_language>

Target:
public byte[] toBinary() { final byte[] backingBuffer = new byte[Integer.BYTES * 2 + Double.BYTES]; ByteBuffer buf = ByteBuffer.wrap(backingBuffer); buf.putInt( maxVertices).putInt( simpVertMin).putDouble( tolerance); return backingBuffer; }
Source:
<code>public EndNode onboardEndnodeWithGateway( @NonNull PendingEndNode pendingEndNode, @NonNull String endnodePassword, @Nullable OnboardEndnodeWithGatewayOptions options) throws ThingIFException { <START> return thingIfApi.onboardEndnodeWithGateway(pendingEndNode, endnodePassword, options); <END> }</code><technical_language>Adding this a field is good manner</technical_language>

Target:
public EndNode onboardEndnodeWithGateway( @NonNull PendingEndNode pendingEndNode, @NonNull String endnodePassword, @Nullable OnboardEndnodeWithGatewayOptions options) throws ThingIFException { return this.thingIfApi.onboardEndnodeWithGateway(pendingEndNode, endnodePassword, options); }
Source:
<code>public abstract InterpreterResult interpret(String st, InterpreterContext context) throws InterpreterException; @ZeppelinApi public abstract void cancel(InterpreterContext context) throws InterpreterException; @ZeppelinApi public abstract FormType getFormType() throws InterpreterException; @ZeppelinApi public abstract int getProgress(InterpreterContext context) throws InterpreterException; @ZeppelinApi public List<InterpreterCompletion> completion(String buf, int cursor, InterpreterContext interpreterContext) throws InterpreterException { <START> return new ArrayList<>(); <END> }</code><technical_language>do need mutable List here? If not, Collections.emptyList()</technical_language>

Target:
public abstract InterpreterResult interpret(String st, InterpreterContext context) throws InterpreterException; @ZeppelinApi public abstract void cancel(InterpreterContext context) throws InterpreterException; @ZeppelinApi public abstract FormType getFormType() throws InterpreterException; @ZeppelinApi public abstract int getProgress(InterpreterContext context) throws InterpreterException; @ZeppelinApi public List<InterpreterCompletion> completion(String buf, int cursor, InterpreterContext interpreterContext) throws InterpreterException { return Collections.emptyList(); }
Source:
<code>private void updatePresenceStatusForXmppProviders() { SipGateway sipGateway= ServiceUtils.getService( osgiContext, SipGateway.class); TranscriptionGateway transcriptionGateway = ServiceUtils.getService( osgiContext, TranscriptionGateway.class); int participants = 0; int sessions = 0; if(sipGateway != null) { <START> for(SipGatewaySession ses : sipGateway.getActiveSessions()) <END> { participants += ses.getJvbChatRoom().getMembersCount(); sessions++; } } if(transcriptionGateway != null) { for(TranscriptionGatewaySession ses : transcriptionGateway.getActiveSessions()) { participants += ses.getJvbChatRoom().getMembersCount(); sessions++; } } Collection<ServiceReference<ProtocolProviderService>> refs = ServiceUtils.getServiceReferences( osgiContext, ProtocolProviderService.class); for (ServiceReference<ProtocolProviderService> ref : refs) { updatePresenceStatusForXmppProvider( osgiContext.getService(ref), participants, sessions); } }</code><technical_language>collecting active sessions looping (avoid duplicating counting code)</technical_language>

Target:
private void updatePresenceStatusForXmppProviders() { Collection<ServiceReference<ProtocolProviderService>> refs = ServiceUtils.getServiceReferences( osgiContext, ProtocolProviderService.class); for (ServiceReference<ProtocolProviderService> ref : refs) { updatePresenceStatusForXmppProvider(osgiContext.getService(ref)); } }
Source:
<code>public void required_mustRequestFromUpstreamForElementsThatHaveBeenRequestedLongAgo() throws Throwable { optionalMultipleSubscribersTest(2, new Function<Long,TestSetup>() { @Override public TestSetup apply(Long subscribers) throws Throwable { return new TestSetup(env, processorBufferSize) {{ ManualSubscriber<T> sub1 = newSubscriber(); sub1.request(20); long totalRequests = expectRequest(); final T x = sendNextTFromUpstream(); expectNextElement(sub1, x); if (totalRequests == 1) { totalRequests += expectRequest(); } final T y = sendNextTFromUpstream(); expectNextElement(sub1, y); if (totalRequests == 2) { totalRequests += expectRequest(); } final ManualSubscriber<T> sub2 = newSubscriber(); if (doesCoordinatedEmission()) { sub2.expectNone(); sub2.request(1); final T z = sendNextTFromUpstream(); expectNextElement(sub1, z); expectNextElement(sub2, z); <START> if (totalRequests == 3) { <END> expectRequest(); } } else { final T z = sendNextTFromUpstream(); expectNextElement(sub1, z); sub2.expectNone(); sub2.request(1); expectNextElement(sub2, z); if (totalRequests == 3) { expectRequest(); } } sendCompletion(); sub1.expectCompletion(env.defaultTimeoutMillis()); sub2.expectCompletion(env.defaultTimeoutMillis()); env.verifyNoAsyncErrorsNoDelay(); }}; } }); }</code><technical_language>this is behavior side of branch, put branch</technical_language>

Target:
public void required_mustRequestFromUpstreamForElementsThatHaveBeenRequestedLongAgo() throws Throwable { optionalMultipleSubscribersTest(2, new Function<Long,TestSetup>() { @Override public TestSetup apply(Long subscribers) throws Throwable { return new TestSetup(env, processorBufferSize) {{ ManualSubscriber<T> sub1 = newSubscriber(); sub1.request(20); long totalRequests = expectRequest(); final T x = sendNextTFromUpstream(); expectNextElement(sub1, x); if (totalRequests == 1) { totalRequests += expectRequest(); } final T y = sendNextTFromUpstream(); expectNextElement(sub1, y); if (totalRequests == 2) { totalRequests += expectRequest(); } final ManualSubscriber<T> sub2 = newSubscriber(); if (doesCoordinatedEmission()) { sub2.expectNone(); sub2.request(1); final T z = sendNextTFromUpstream(); expectNextElement(sub1, z); expectNextElement(sub2, z); } else { final T z = sendNextTFromUpstream(); expectNextElement(sub1, z, "If the Processor coordinates requests/emissions when having multiple Subscribers" + " at once, please override doesCoordinatedEmission() to return true in this " + "IdentityProcessorVerification to allow this test to pass."); sub2.expectNone(); sub2.request(1); expectNextElement(sub2, z); } if (totalRequests == 3) { expectRequest(); } sendCompletion(); sub1.expectCompletion(env.defaultTimeoutMillis()); sub2.expectCompletion(env.defaultTimeoutMillis()); env.verifyNoAsyncErrorsNoDelay(); }}; } }); }
Source:
<code>private TupleBatchBuffer fillInputTbb(final int numTuples) { final Schema schema = <START> new Schema(ImmutableList.of(Type.INT_TYPE, Type.DOUBLE_TYPE, Type.FLOAT_TYPE, Type.LONG_TYPE, <END> Type.DATETIME_TYPE, Type.STRING_TYPE, Type.BOOLEAN_TYPE, Type.LONG_TYPE), ImmutableList.of("Int", "Double", "Float", "Long", "Datetime", "String", "Boolean", "value")); final TupleBatchBuffer source = new TupleBatchBuffer(schema); for (int i = 0; i < numTuples; i++) { int value = i / (numTuples / 10); source.putInt(0, value); source.putDouble(1, value); source.putFloat(2, value); source.putLong(3, value); source.putDateTime(4, new DateTime(2010 + value, 1, 1, 0, 0)); source.putString(5, "" + value); source.putBoolean(6, (i / (numTuples / 2) == 0)); source.putLong(7, 2L); } return source; }</code><technical_language>Readability improved Schema.ofFields(name1, type1, name2, type2, ...) factory method</technical_language>

Target:
private TupleBatchBuffer fillInputTbb(final int numTuples) { final Schema schema = Schema.ofFields(Type.INT_TYPE, "Int", Type.DOUBLE_TYPE, "Double", Type.FLOAT_TYPE, "Float", Type.LONG_TYPE, "Long", Type.DATETIME_TYPE, "Datetime", Type.STRING_TYPE, "String", Type.BOOLEAN_TYPE, "Boolean", Type.LONG_TYPE, "value"); final TupleBatchBuffer source = new TupleBatchBuffer(schema); for (int i = 0; i < numTuples; i++) { int value = i / (numTuples / 10); source.putInt(0, value); source.putDouble(1, value); source.putFloat(2, value); source.putLong(3, value); source.putDateTime(4, new DateTime(2010 + value, 1, 1, 0, 0)); source.putString(5, "" + value); source.putBoolean(6, (i / (numTuples / 2) == 0)); source.putLong(7, 2L); } return source; }
Source:
<code>public void testRequestToken() { Map<String, String> userDTO = new HashMap<>(); userDTO.put("username", user.getUsername()); userDTO.put("password", userCleartextPassword); given(). when(). content(userDTO).contentType(ContentType.JSON). post("/token"). then(). statusCode(HttpStatus.SC_OK); AuthenticationToken authenticationToken1 = authenticationTokenRepository.findByUserUsername(user.getUsername()).orElse(null); given(). when(). content(userDTO).contentType(ContentType.JSON). post("/token"). then(). statusCode(HttpStatus.SC_OK); AuthenticationToken authenticationToken2 = authenticationTokenRepository.findByUserUsername(user.getUsername()).orElse(null); <START> Assert.assertFalse(authenticationToken1.equals(authenticationToken2)); <END> }</code><technical_language>I a 'equals' implementation in AuthenticationToken Token class itself. If correct this means checks for object equality (similar ==) throw false if comparing repo results</technical_language>

Target:
public void testRequestToken() { Map<String, String> userDTO = new HashMap<>(); userDTO.put("username", user.getUsername()); userDTO.put("password", userCleartextPassword); Response response = given(). when(). content(userDTO).contentType(ContentType.JSON). post("/token"); Optional<AuthenticationToken> authenticationToken = authenticationTokenRepository.findByUserUsername(user.getUsername()); Assert.assertTrue(authenticationToken.isPresent()); response.then().statusCode(HttpStatus.SC_OK).body("object", containsString(authenticationToken.get().getToken())); }