auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Map<String, List<TestEntity>> getTestsWithName(List<String> sessionIds, String testName){ List<Object[]> tasksEntities = getHibernateTemplate().findByNamedParam("select task, taskData.id from WorkloadTaskData task, TaskData taskData " + "where task.sessionId in (:sessionIds) and " + <START> " task.scenario.name like :name and " + <END> " taskData.sessionId in (:sessionIds) and "+ " taskData.taskId=task.taskId", new String[]{"sessionIds", "name"}, new Object[]{sessionIds, testName}); Map<String, List<TestEntity>> result = new HashMap<String, List<TestEntity>>(); for (Object[] taskEntity : tasksEntities){ WorkloadTaskData task = (WorkloadTaskData)taskEntity[0]; TestEntity entity = new TestEntity(); entity.setId((Long)taskEntity[1]); entity.setName(task.getScenario().getName()); entity.setDescription(task.getScenario().getDescription()); entity.setLoad(task.getClock()); entity.setTerminationStrategy(task.getTermination()); if (result.containsKey(task.getSessionId())){ result.get(task.getSessionId()).add(entity); }else{ List<TestEntity> list = new ArrayList<TestEntity>(); list.add(entity); result.put(task.getSessionId(), list); } } return result; }</code><technical_language>'like'</technical_language>

Target:
private Map<String, List<TestEntity>> getTestsWithName(List<String> sessionIds, String testName){ if (sessionIds.isEmpty()){ return Collections.EMPTY_MAP; } List<Object[]> tasksEntities = getHibernateTemplate().findByNamedParam("select task, taskData.id from WorkloadTaskData task, TaskData taskData " + "where task.sessionId in (:sessionIds) and " + " task.scenario.name like :name and " + " taskData.sessionId in (:sessionIds) and "+ " taskData.taskId=task.taskId", new String[]{"sessionIds", "name"}, new Object[]{sessionIds, testName}); Map<String, List<TestEntity>> result = new HashMap<String, List<TestEntity>>(); for (Object[] taskEntity : tasksEntities){ WorkloadTaskData task = (WorkloadTaskData)taskEntity[0]; TestEntity entity = new TestEntity(); entity.setId((Long)taskEntity[1]); entity.setName(task.getScenario().getName()); entity.setDescription(task.getScenario().getDescription()); entity.setLoad(task.getClock()); entity.setTerminationStrategy(task.getTermination()); if (result.containsKey(task.getSessionId())){ result.get(task.getSessionId()).add(entity); }else{ List<TestEntity> list = new ArrayList<TestEntity>(); list.add(entity); result.put(task.getSessionId(), list); } } return result; }
Source:
<code>private boolean isConnectionAvailable() throws InterruptedException { boolean knowIfServerUp = false; <START> int numTimes = 5; <END> while (!knowIfServerUp && numTimes > 0) { try { numTimes--; nwServer.testForConnection(); knowIfServerUp = true; } catch (Exception e) { OseeLog.log(HyperSqlDbServer.class, Level.SEVERE, "Unable to obtain a connection to network server, trying again after 3000 ms.", e); Thread.sleep(3000); } } return knowIfServerUp; }</code><technical_language>this number a parameter callers pull a property somewhere</technical_language>

Target:
private boolean isConnectionAvailable() throws InterruptedException { boolean knowIfServerUp = false; int numTimes = CHECK_ALIVE_NUMBER_OF_TIMES; while (!knowIfServerUp && numTimes > 0) { try { numTimes--; nwServer.testForConnection(); knowIfServerUp = true; } catch (Exception e) { OseeLog.log(HyperSqlDbServer.class, Level.SEVERE, "Unable to obtain a connection to network server, trying again after 3000 ms.", e); Thread.sleep(3000); } } return knowIfServerUp; }
Source:
<code><START> public void visitWhileStatement(WhileStatementTree tree) { <END> }</code><technical_language>This is broad results in false negative : while(true) { if ((a = b = 0) != null) { // Noncompliant detected. }</technical_language>

Target:
public void visitWhileStatement(WhileStatementTree tree) { scan(tree.statement()); }
Source:
<code>public boolean checkCurrentUserHasQueueSubscriptionClosePermission() throws BrokerManagerAdminException { boolean hasPermission = false; <START> String username = CarbonContext.getThreadLocalCarbonContext().getUsername(); <END> try { if (Utils.isAdmin(username)) { hasPermission = true; } else if (CarbonContext.getThreadLocalCarbonContext().getUserRealm().getAuthorizationManager() .isUserAuthorized(username, PERMISSION_ADMIN_MANAGE_QUEUE_SUBSCRIPTION_CLOSE, UI_EXECUTE)) { hasPermission = true; } } catch (UserStoreException | QueueManagerException e) { String errorMessage = e.getMessage(); log.error(errorMessage, e); throw new BrokerManagerAdminException(errorMessage, e); } return hasPermission; }</code><technical_language>define a private method for CarbonContext.getThreadLocalCarbonContext().getUsername(); is in couple of places</technical_language>

Target:
public boolean checkCurrentUserHasQueueSubscriptionClosePermission() throws BrokerManagerAdminException { boolean hasPermission = false; String username = getCurrentLoggedInUser(); try { if (Utils.isAdmin(username)) { hasPermission = true; } else if (CarbonContext.getThreadLocalCarbonContext().getUserRealm().getAuthorizationManager() .isUserAuthorized(username, PERMISSION_ADMIN_MANAGE_QUEUE_SUBSCRIPTION_CLOSE, UI_EXECUTE)) { hasPermission = true; } } catch (UserStoreException | QueueManagerException e) { String errorMessage = e.getMessage(); log.error(errorMessage, e); throw new BrokerManagerAdminException(errorMessage, e); } return hasPermission; }
Source:
<code>protected void checkProject(Project project) { assertNotNull(project.getId()); assertEquals(project.toString(), client.getProjectApi().getProject(project.getId()).toString()); <START> assertTrue(project.getState() != null && project.getState() != Project.State.UNRECOGNIZED); <END> }</code><technical_language>[minor] Split asserts add a message showing offending is</technical_language>

Target:
protected void checkProject(Project project) { assertNotNull(project.getId()); assertEquals(project.toString(), client.getProjectApi().getProject(project.getId()).toString()); assertTrue(project.getState() != null); assertTrue(project.getState() != Project.State.UNRECOGNIZED); }
Source:
<code>public void resetQueueState() throws IOException { queueFile = new File(r.jenkins.getRootDir(), "queue.xml"); XmlFile xmlFile = new XmlFile(Queue.XSTREAM, queueFile); xmlFile.write(new Queue.State()); <START> r.jenkins.getQueue().load(); <END> }</code><technical_language>is this necessary? test Jenkins Queue anyway</technical_language>

Target:
private void resetQueueState() throws IOException { File queueFile = r.jenkins.getQueue().getXMLQueueFile(); XmlFile xmlFile = new XmlFile(Queue.XSTREAM, queueFile); xmlFile.write(new Queue.State()); r.jenkins.getQueue().load(); }
Source:
<code>public void textPlainContentType() throws Exception { refreshIndex(); String json = JsonUtils.mapToFormattedJsonString(hashMap("name", "Solitaire2")); WebResource.Builder builder = app().collection("games").getResource(true, getAdminToken()) .accept(MediaType.APPLICATION_JSON) <START> .type(MediaType.APPLICATION_JSON); <END> ClientResponse clientResponse = builder.post(ClientResponse.class, json); assertEquals(200, clientResponse.getStatus()); MultivaluedMap<String, String> headers = clientResponse.getHeaders(); List<String> contentType = headers.get("Content-Type"); assertEquals(1, contentType.size()); assertEquals(MediaType.APPLICATION_JSON, contentType.get(0)); }</code><technical_language>this application_json_type</technical_language>

Target:
public void textPlainContentType() throws Exception { String json = JsonUtils.mapToFormattedJsonString(hashMap("name", "Solitaire2")); WebResource.Builder builder = app().collection("games").getResource(true, getAdminToken()) .accept(MediaType.APPLICATION_JSON) .type(MediaType.TEXT_PLAIN_TYPE); ClientResponse clientResponse = builder.post(ClientResponse.class, json); assertEquals(200, clientResponse.getStatus()); MultivaluedMap<String, String> headers = clientResponse.getHeaders(); List<String> contentType = headers.get("Content-Type"); assertEquals(1, contentType.size()); assertEquals(MediaType.APPLICATION_JSON, contentType.get(0)); }
Source:
<code>public final CharSequence getStr0(long offset, CharSequenceView view) { final int len = getInt(offset); <START> if (offset + len * 2 + Integer.BYTES <= size) { <END> if (len == TableUtils.NULL_LEN) { return null; } if (len == 0) { return ""; } return view.of(offset + VirtualMemory.STRING_LENGTH_BYTES, len); } throw CairoException.instance(0).put("String is outside of file boundary [offset=").put(offset).put(", len=").put(len).put(']'); }</code><technical_language>this needs fixing a bit more in checking if string fits page len = -1. I this emphasising hot path: java public final CharSequence getStr0(long offset, CharSequenceView view) { final int len = getInt(offset); if (len > -1 && offset + len * Character.BYTES + Integer.BYTES <= size) { return view.of(offset + VirtualMemory.STRING_LENGTH_BYTES, len); } if (len == TableUtils.NULL_LEN) { return null; } throw CairoException.instance(0).put("String is of file boundary [offset=").put(offset).put(", len=").put(len).put(']'); }</technical_language>

Target:
public final CharSequence getStr0(long offset, CharSequenceView view) { final int len = getInt(offset); if (len > -1 && offset + len * Character.BYTES + Integer.BYTES <= size) { return view.of(offset + VirtualMemory.STRING_LENGTH_BYTES, len); } if (len == TableUtils.NULL_LEN) { return null; } throw CairoException.instance(0).put("String is outside of file boundary [offset=").put(offset).put(", len=").put(len).put(']'); }
Source:
<code><START> public static void main(String[] args) throws Exception { <END> if (args.length == 0) { System.err.println("Usage: c2dts [FILES...]"); System.exit(1); } List<SourceFile> sources = new ArrayList<>(); List<SourceFile> externs = new ArrayList<>(); List<SourceFile> fill = sources; boolean outFile = false; for (String arg : args) { if (arg.equals("--externs")) { fill = externs; continue; } if (arg.equals("-o")) { outFile = true; continue; } if (outFile) { System.setOut(new PrintStream(new FileOutputStream(new File(arg)), true, "utf-8")); } File f = new File(arg); if (!f.exists()) { System.err.println("Input file not found: " + f.getPath()); System.exit(1); } fill.add(SourceFile.fromFile(f)); } DeclarationGenerator generator = new DeclarationGenerator(true); System.out.println(generator.generateDeclarations(sources, externs)); }</code><technical_language>catch this in time add proper error handling</technical_language>

Target:
public static void main(String[] args) { try { new DeclarationGenerator(new Options(args)).generateDeclarations(); } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("Usage: cl2dts [options...] arguments..."); e.getParser().printUsage(System.err); System.err.println(); System.exit(1); } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Uncaught exception in cl2dts, exiting."); System.exit(1); } System.exit(0); }
Source:
<code>public Observable<Pair<RealmResults<E>, OrderedCollectionChangeSet>> asChangesetObservable() { if (realm instanceof Realm) { return realm.configuration.getRxFactory().changesetsFrom((Realm) realm, this); <START> } else if (realm instanceof DynamicRealm) { <END> DynamicRealm dynamicRealm = (DynamicRealm) realm; RealmResults<DynamicRealmObject> dynamicResults = (RealmResults<DynamicRealmObject>) this; @SuppressWarnings("UnnecessaryLocalVariable") Observable results = realm.configuration.getRxFactory().changesetsFrom(dynamicRealm, dynamicResults); return results; } else { throw new UnsupportedOperationException(realm.getClass() + " does not support RxJava2."); } }</code><technical_language>else redundant</technical_language>

Target:
public Observable<CollectionChange<RealmResults<E>>> asChangesetObservable() { if (realm instanceof Realm) { return realm.configuration.getRxFactory().changesetsFrom((Realm) realm, this); } else if (realm instanceof DynamicRealm) { DynamicRealm dynamicRealm = (DynamicRealm) realm; RealmResults<DynamicRealmObject> dynamicResults = (RealmResults<DynamicRealmObject>) this; return (Observable) realm.configuration.getRxFactory().changesetsFrom(dynamicRealm, dynamicResults); } else { throw new UnsupportedOperationException(realm.getClass() + " does not support RxJava2."); } }
Source:
<code>public void checkWebJavaSpringProjectCommands() { consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, BUILD_GOAL, BUILD_COMMAND, BUILD_SUCCESS); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, BUILD_GOAL, BUILD_COMMAND_ITEM.getItem(WEB_JAVA_SPRING), BUILD_SUCCESS); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, RUN_GOAL, BUILD_AND_RUN_COMMAND_ITEM.getItem(WEB_JAVA_SPRING), SERVER_STARTUP_IN); <START> consoles.checkWebElementVisibilityAtPreviewPage(By.xpath(" END> consoles.closeProcessTabWithAskDialog(BUILD_AND_RUN_COMMAND_ITEM.getItem(WEB_JAVA_SPRING)); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, RUN_GOAL, RUN_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_SPRING), SERVER_STARTUP_IN); consoles.checkWebElementVisibilityAtPreviewPage(By.xpath(" projectExplorer.invokeCommandWithContextMenu( RUN_GOAL, WEB_JAVA_SPRING, STOP_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_SPRING)); consoles.selectProcessInProcessConsoleTreeByName("Terminal"); terminal.typeIntoTerminal("ps ax"); terminal.typeIntoTerminal(ENTER.toString()); terminal.waitExpectedTextNotPresentTerminal("/bin/bash -c $TOMCAT_HOME/bin/catalina.sh"); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING, DEBUG_GOAL, DEBUG_COMMAND_ITEM.getItem(WEB_JAVA_SPRING), LISTENING_AT_ADDRESS_8000); }</code><technical_language>Define "//span[text()='Enter name: ']" string a constant code clear, IMHO, allow avoid duplication</technical_language>

Target:
public void checkWebJavaSpringProjectCommands() { String tomcatIsRunning = "/bin/bash -c $TOMCAT_HOME/bin/catalina.sh"; consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING_PROJECT, BUILD_GOAL, BUILD_COMMAND, BUILD_SUCCESS); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING_PROJECT, BUILD_GOAL, BUILD_COMMAND_ITEM.getItem(WEB_JAVA_SPRING_PROJECT), BUILD_SUCCESS); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING_PROJECT, RUN_GOAL, BUILD_AND_RUN_COMMAND_ITEM.getItem(WEB_JAVA_SPRING_PROJECT), SERVER_STARTUP_IN); consoles.checkWebElementVisibilityAtPreviewPage(textOnPreviewPage); consoles.closeProcessTabWithAskDialog( BUILD_AND_RUN_COMMAND_ITEM.getItem(WEB_JAVA_SPRING_PROJECT)); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING_PROJECT, RUN_GOAL, RUN_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_SPRING_PROJECT), SERVER_STARTUP_IN); consoles.checkWebElementVisibilityAtPreviewPage(textOnPreviewPage); projectExplorer.invokeCommandWithContextMenu( RUN_GOAL, WEB_JAVA_SPRING_PROJECT, STOP_TOMCAT_COMMAND_ITEM.getItem(WEB_JAVA_SPRING_PROJECT)); consoles.selectProcessInProcessConsoleTreeByName("Terminal"); terminal.typeIntoTerminal("ps ax"); terminal.typeIntoTerminal(ENTER.toString()); terminal.waitExpectedTextNotPresentTerminal(tomcatIsRunning); consoles.executeCommandFromProjectExplorer( WEB_JAVA_SPRING_PROJECT, DEBUG_GOAL, DEBUG_COMMAND_ITEM.getItem(WEB_JAVA_SPRING_PROJECT), LISTENING_AT_ADDRESS_8000); }
Source:
<code>private boolean validate(){ Pattern userNamePattern = Pattern.compile("[a-z0-9]*"); Matcher userNameMatcher = userNamePattern.matcher(usernameText.getText().toString().trim()); if(!userNameMatcher.matches()) { usernameText.setError("This field can contain only lowercase alphabets and numbers."); usernameText.requestFocus(); return false; } if(!android.util.Patterns.EMAIL_ADDRESS.matcher(emailText.getText().toString().trim()).matches()) { emailText.setError("Please enter a valid email address"); emailText.requestFocus(); return false; } if (verificationMethod.equals(MOBILE)) { <START> boolean isPhoneValid; <END> if (isTwilioEnabled) { isPhoneValid = Validations.validateInternationalPhoneNumber(countryCodePicker); } else { isPhoneValid = Validations.validatePhoneNumber(phoneText.getText().toString().trim()); } if (!isPhoneValid) { phoneText.setError("Please enter a valid mobile number"); phoneText.requestFocus(); return false; } } if(passwordText.getText().toString().trim().length()<6){ passwordText.setError("Password should contain at least 6 digits"); passwordText.requestFocus(); return false; } if(!passwordText.getText().toString().equals(confirmPasswordText.getText().toString().trim())){ confirmPasswordText.setError("Passwords not matching"); confirmPasswordText.requestFocus(); return false; } return true; }</code><technical_language>suggestion boolean isPhoneNumberValid;</technical_language>

Target:
private boolean validate(){ Pattern userNamePattern = Pattern.compile("[a-z0-9]*"); Matcher userNameMatcher = userNamePattern.matcher(usernameText.getText().toString().trim()); if(!userNameMatcher.matches()) { usernameText.setError("This field can contain only lowercase alphabets and numbers."); usernameText.requestFocus(); return false; } if(!android.util.Patterns.EMAIL_ADDRESS.matcher(emailText.getText().toString().trim()).matches()) { emailText.setError("Please enter a valid email address"); emailText.requestFocus(); return false; } if (verificationMethod.equals(MOBILE)) { boolean isPhoneNumberValid; if (isTwilioEnabled) { isPhoneNumberValid = PhoneNumberValidator.validateInternationalPhoneNumber(countryCodePicker); } else { isPhoneNumberValid = PhoneNumberValidator.validatePhoneNumber(phoneText.getText().toString().trim()); } if (!isPhoneNumberValid) { phoneText.setError("Please enter a valid mobile number"); phoneText.requestFocus(); return false; } } if(passwordText.getText().toString().trim().length()<6){ passwordText.setError("Password should contain at least 6 digits"); passwordText.requestFocus(); return false; } if(!passwordText.getText().toString().equals(confirmPasswordText.getText().toString().trim())){ confirmPasswordText.setError("Passwords not matching"); confirmPasswordText.requestFocus(); return false; } return true; }
Source:
<code>public boolean isPageview( String uriHost, String uriPath, String uriQuery, String httpStatus, String contentType, String userAgent, Map<String,String> xAnalyticsMap ) { uriHost = uriHost.toLowerCase(); if (xAnalyticsMap.containsKey("preview")) { return false; <START> <END> } return ( httpStatusesSet.contains(httpStatus) && ( (contentTypesSet.contains(contentType) && !Utilities.stringContains(uriPath, uriPathAPI)) || isAppPageview(uriPath, uriQuery, contentType, userAgent, xAnalyticsMap) ) && ( Utilities.patternIsFound(uriHostWikimediaDomainPattern, uriHost) || Utilities.patternIsFound(uriHostOtherProjectsPattern, uriHost) || Utilities.patternIsFound(uriHostProjectDomainPattern, uriHost) ) && ( Utilities.patternIsFound(uriPathPattern, uriPath) || Utilities.patternIsFound(uriQueryPattern, uriQuery) ) && !Utilities.patternIsFound(uriPathUnwantedSpecialPagesPattern, uriPath) && !Utilities.patternIsFound(uriQueryUnwantedSpecialPagesPattern, uriQuery) && !Utilities.patternIsFound(uriQueryUnwantedActions, uriQuery) ); }</code><technical_language>Extraneous spacing</technical_language>

Target:
public boolean isPageview( String uriHost, String uriPath, String uriQuery, String httpStatus, String contentType, String userAgent, Map<String,String> xAnalyticsMap ) { uriHost = uriHost.toLowerCase(); if (xAnalyticsMap.containsKey("preview")) return false; return ( httpStatusesSet.contains(httpStatus) && ( (contentTypesSet.contains(contentType) && !Utilities.stringContains(uriPath, uriPathAPI)) || isAppPageview(uriPath, uriQuery, contentType, userAgent, xAnalyticsMap) ) && ( Utilities.patternIsFound(uriHostWikimediaDomainPattern, uriHost) || Utilities.patternIsFound(uriHostOtherProjectsPattern, uriHost) || Utilities.patternIsFound(uriHostProjectDomainPattern, uriHost) ) && ( Utilities.patternIsFound(uriPathPattern, uriPath) || Utilities.patternIsFound(uriQueryPattern, uriQuery) ) && !Utilities.patternIsFound(uriPathUnwantedSpecialPagesPattern, uriPath) && !Utilities.patternIsFound(uriQueryUnwantedSpecialPagesPattern, uriQuery) && !Utilities.patternIsFound(uriQueryUnwantedActions, uriQuery) ); }
Source:
<code>public String toASCII() throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { write(baos); <START> return baos.toString("US-ASCII"); <END> } }</code><technical_language>suggestion return baos.toString(StandardCharsets.US_ASCII.name()); standardization consistency method</technical_language>

Target:
public String toASCII() throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { write(baos); return baos.toString(StandardCharsets.US_ASCII.name()); } }
Source:
<code>public void calledWithTooManyCommandArguments_returnsError() { List<byte[]> commandsAsBytes = new ArrayList<>(); commandsAsBytes.add("EXPIREAT".getBytes()); commandsAsBytes.add("key".getBytes()); commandsAsBytes.add("1".getBytes()); commandsAsBytes.add("extra-argument".getBytes()); Command command = new Command(commandsAsBytes); Throwable thrown = catchThrowable(() -> command.execute(mockContext())); AssertionsForClassTypes.assertThat(thrown).hasMessageContaining("wrong number of arguments"); <START> AssertionsForClassTypes.assertThat(thrown).isInstanceOf(RedisParametersMismatchException.class); <END> }</code><technical_language>thing, for consistency, assertThat org.assertj.core.api.Assertions package</technical_language>

Target:
public void calledWithTooManyCommandArguments_returnsError() { List<byte[]> commandsAsBytes = new ArrayList<>(); commandsAsBytes.add("EXPIREAT".getBytes()); commandsAsBytes.add("key".getBytes()); commandsAsBytes.add("1".getBytes()); commandsAsBytes.add("extra-argument".getBytes()); Command command = new Command(commandsAsBytes); assertThatThrownBy(() -> command.execute(mockContext())) .hasMessageContaining("wrong number of arguments") .isInstanceOf(RedisParametersMismatchException.class); }
Source:
<code>public boolean upgradeCluster(long stackId, StatedImage currentImage, StatedImage targetImage) { Image targetIm = targetImage.getImage(); Image currentIm = currentImage.getImage(); <START> String currentRuntimeBuildNumber = currentIm.getStackDetails().getStackBuildNumber(); <END> boolean clusterManagerUpdateNeeded = !currentIm.getCmBuildNumber().equals(targetIm.getCmBuildNumber()); boolean clusterRuntimeUpgradeNeeded = !currentRuntimeBuildNumber.equals(targetIm.getStackDetails().getStackBuildNumber()); if (clusterManagerUpdateNeeded) { flowMessageService.fireEventAndLog(stackId, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_MANAGER_UPGRADE_FINISHED, targetIm.getVersion()); } clusterService.updateClusterStatusByStackId(stackId, Status.UPDATE_IN_PROGRESS); if (clusterRuntimeUpgradeNeeded) { flowMessageService.fireEventAndLog(stackId, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_UPGRADE); } else { flowMessageService.fireEventAndLog(stackId, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_UPGRADE_NOT_NEEDED, currentRuntimeBuildNumber); } return clusterRuntimeUpgradeNeeded; }</code><technical_language>Pls. ensure this is NPE safe</technical_language>

Target:
public boolean upgradeCluster(long stackId, StatedImage currentImage, StatedImage targetImage) { Image targetIm = targetImage.getImage(); Image currentIm = currentImage.getImage(); String currentRuntimeBuildNumber = NullUtil.getIfNotNull(currentIm.getStackDetails(), StackDetails::getStackBuildNumber); boolean clusterManagerUpdateNeeded = isUpdateNeeded(currentIm.getCmBuildNumber(), targetIm.getCmBuildNumber()); boolean clusterRuntimeUpgradeNeeded = isUpdateNeeded(currentRuntimeBuildNumber, NullUtil.getIfNotNull(targetIm.getStackDetails(), StackDetails::getStackBuildNumber)); if (clusterManagerUpdateNeeded) { flowMessageService.fireEventAndLog(stackId, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_MANAGER_UPGRADE_FINISHED, targetIm.getVersion()); } clusterService.updateClusterStatusByStackId(stackId, Status.UPDATE_IN_PROGRESS); if (clusterRuntimeUpgradeNeeded) { flowMessageService.fireEventAndLog(stackId, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_UPGRADE); } else { flowMessageService.fireEventAndLog(stackId, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_UPGRADE_NOT_NEEDED, currentRuntimeBuildNumber); } return clusterRuntimeUpgradeNeeded; }
Source:
<code>public static void createUser(final DB dbs, final SrlUser user, final String userId) throws DatabaseAccessException { final DBCollection users = dbs.getCollection(USER_COLLECTION); BasicDBObject query = null; LOG.info("userId: {}", userId); try { query = new BasicDBObject(SELF_ID, userId).append(COURSE_LIST, new ArrayList<String>()) .append(CREDENTIALS, PasswordHash.createHash(user.getEmail())).append(EMAIL, user.getEmail()) .append(ADMIN, PasswordHash.createHash(userId)); } catch (NoSuchAlgorithmException e) { <START> LOG.info("Exception: {}", e); <END> } catch (InvalidKeySpecException e) { LOG.info("Exception: {}", e); } if (query == null) { throw new DatabaseAccessException("An error occured creating password hash"); } users.insert(query); }</code><technical_language>this error constant rest of file</technical_language>

Target:
public static void createUser(final DB dbs, final SrlUser user, final String userId) throws DatabaseAccessException { final DBCollection users = dbs.getCollection(USER_COLLECTION); BasicDBObject query = null; LOG.debug("userId: {}", userId); try { query = new BasicDBObject(SELF_ID, userId).append(COURSE_LIST, new ArrayList<String>()) .append(CREDENTIALS, PasswordHash.createHash(user.getEmail())).append(EMAIL, user.getEmail()) .append(ADMIN, PasswordHash.createHash(userId)); } catch (NoSuchAlgorithmException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); } catch (InvalidKeySpecException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); } if (query == null) { throw new DatabaseAccessException("An error occured creating password hash"); } users.insert(query); }
Source:
<code>public void handleClick(@NonNull final View view) { super.handleClick( view ); parentNativeAd.launchClickTarget( view.getContext() ); <START> notifyAdClicked(); <END> }</code><technical_language>order previously? is 1. notify ad click, 2. launch click target</technical_language>

Target:
public void handleClick(@NonNull final View view) { super.handleClick( view ); notifyAdClicked(); parentNativeAd.launchClickTarget( view.getContext() ); }
Source:
<code>public String toString() { return toStringHelper(this) <START> .add("super", super.toString()) <END> .add("valuesBufferCapacity", valuesBuffer == null ? 0 : valuesBuffer.length) .add("valuesBufferIndex", valuesBufferIndex) .toString(); }</code><technical_language>I need call toString() explicitly (and in other similar places)</technical_language>

Target:
public String toString() { return toStringHelper(this) .add("super", super.toString()) .add("estimatedValueBufferMaxCapacity", estimatedValueBufferMaxCapacity) .add("valuesBufferCapacity", valuesBuffer == null ? 0 : valuesBuffer.length) .add("valuesBufferIndex", valuesBufferIndex) .toString(); }
Source:
<code>private void verifyBodyCloseBraceStyle(ParserRuleContext bodyCtx, String constructName) { ParseTree closeBrace = ParseTreeUtil.getLastChild(bodyCtx); Token closeBraceToken = ((TerminalNodeImpl)closeBrace).getSymbol(); Location closeBraceLocation = ListenerUtil.getTokenLocation(closeBraceToken); int closeBraceTokenIndex = closeBraceToken.getTokenIndex(); <START> if (closeBraceTokenIndex >= 0) { <END> List<Token> tokens = tokenStream.getHiddenTokensToLeft(closeBraceTokenIndex); if (tokens != null) { Token commentToken = getLastCommentToken(tokens); if (commentToken != null) { int commentEndLine = ListenerUtil.getEndLineOfToken(commentToken); if (commentEndLine == closeBraceLocation.line) { this.printer.warn(constructName + Messages.CLOSE_BRACKET_STYLE, closeBraceLocation); return; } } } } ParseTree closeBraceLeftSibling = ParseTreeUtil.getLeftSibling(closeBrace); Location closeBraceLeftSiblingLocation = ListenerUtil.getParseTreeStopLocation(closeBraceLeftSibling); if (closeBraceLocation.line == closeBraceLeftSiblingLocation.line) { if (!closeBraceLeftSibling.getText().equals("{")) { this.printer.warn(constructName + Messages.CLOSE_BRACKET_STYLE, closeBraceLocation); } else if (closeBraceLocation.column - closeBraceLeftSiblingLocation.column != 1) { this.printer.warn(Messages.EMPTY_BODY, closeBraceLeftSiblingLocation); } } }</code><technical_language>this check</technical_language>

Target:
private void verifyBodyCloseBraceStyle(ParserRuleContext bodyCtx, String constructName) { ParseTree closeBrace = ParseTreeUtil.getLastChild(bodyCtx); Token closeBraceToken = ((TerminalNodeImpl)closeBrace).getSymbol(); Location closeBraceLocation = ListenerUtil.getTokenLocation(closeBraceToken); List<Token> tokens = tokenStream.getHiddenTokensToLeft(closeBraceToken.getTokenIndex()); if (tokens != null) { Token commentToken = getLastCommentToken(tokens); if (commentToken != null) { int commentEndLine = ListenerUtil.getEndLineOfToken(commentToken); if (commentEndLine == closeBraceLocation.line) { this.printer.warn(constructName + Messages.CLOSE_BRACKET_STYLE, closeBraceLocation); return; } } } ParseTree closeBraceLeftSibling = ParseTreeUtil.getLeftSibling(closeBrace); Location closeBraceLeftSiblingLocation = ListenerUtil.getParseTreeStopLocation(closeBraceLeftSibling); if (closeBraceLocation.line == closeBraceLeftSiblingLocation.line) { if (!closeBraceLeftSibling.getText().equals("{")) { this.printer.warn(constructName + Messages.CLOSE_BRACKET_STYLE, closeBraceLocation); } else if (closeBraceLocation.column - closeBraceLeftSiblingLocation.column != 1) { this.printer.warn(Messages.EMPTY_BODY, closeBraceLeftSiblingLocation); } } }
Source:
<code>public void write() throws IOException { Splitter splitter = Splitter.on('.'); Iterable<String> folders = splitter.split(mPackageName); File file = new File(mOutFolder); for (String folder : folders) { file = new File(file, folder); } file.mkdirs(); <START> file = new File(file, "R.java"); <END> BufferedWriter writer = null; try { writer = Files.newWriter(file, Charsets.UTF_8); writer.write(" \n"); writer.write("package "); writer.write(mPackageName); writer.write(";\n\npublic final class R {\n"); Table<String, String, SymbolEntry> symbols = mSymbols.getSymbols(); Table<String, String, SymbolEntry> values = mValues.getSymbols(); for (String row : symbols.rowKeySet()) { writer.write("\tpublic static final class "); writer.write(row); writer.write(" {\n"); for (Map.Entry<String, SymbolEntry> symbol : symbols.row(row).entrySet()) { SymbolEntry value = values.get(row, symbol.getKey()); if (value != null) { writer.write("\t\tpublic static final "); writer.write(value.getType()); writer.write(" "); writer.write(value.getName()); writer.write(" = "); writer.write(value.getValue()); writer.write(";\n"); } } writer.write("\t}\n"); } writer.write("}\n"); } finally { if (writer != null) { writer.close(); } } }</code><technical_language>SdkConstants.FN_RESOURCE_CLASS</technical_language>

Target:
public void write() throws IOException { Splitter splitter = Splitter.on('.'); Iterable<String> folders = splitter.split(mPackageName); File file = new File(mOutFolder); for (String folder : folders) { file = new File(file, folder); } file.mkdirs(); file = new File(file, SdkConstants.FN_RESOURCE_CLASS); BufferedWriter writer = null; try { writer = Files.newWriter(file, Charsets.UTF_8); writer.write(" \n"); writer.write("package "); writer.write(mPackageName); writer.write(";\n\npublic final class R {\n"); Table<String, String, SymbolEntry> symbols = mSymbols.getSymbols(); Table<String, String, SymbolEntry> values = mValues.getSymbols(); for (String row : symbols.rowKeySet()) { writer.write("\tpublic static final class "); writer.write(row); writer.write(" {\n"); for (Map.Entry<String, SymbolEntry> symbol : symbols.row(row).entrySet()) { SymbolEntry value = values.get(row, symbol.getKey()); if (value != null) { writer.write("\t\tpublic static final "); writer.write(value.getType()); writer.write(" "); writer.write(value.getName()); writer.write(" = "); writer.write(value.getValue()); writer.write(";\n"); } } writer.write("\t}\n"); } writer.write("}\n"); } finally { Closeables.closeQuietly(writer); } }
Source:
<code>private RetryStatus getRetryStatus(ChangeMessage msg) { try { ChangeMessage last = Iterables.getLast(db.changeMessages().byChange( msg.getPatchSetId().getParentKey()), null); if (last != null) { long lastMs = last.getWrittenOn().getTime(); long msgMs = msg.getWrittenOn().getTime(); if (Objects.equal(last.getAuthor(), msg.getAuthor()) && Objects.equal(last.getMessage(), msg.getMessage())) { <START> return msgMs - lastMs > DUPLICATE_MESSAGE_INTERVAL <END> ? RetryStatus.UNSUBMIT : RetryStatus.RETRY_NO_MESSAGE; } } } catch (OrmException err) { log.warn("Cannot check previous merge failure message", err); } return RetryStatus.RETRY_ADD_MESSAGE; }</code><technical_language>I this constant needs renamed</technical_language>

Target:
private RetryStatus getRetryStatus(ChangeMessage msg) { try { ChangeMessage last = Iterables.getLast(db.changeMessages().byChange( msg.getPatchSetId().getParentKey()), null); if (last != null) { if (Objects.equal(last.getAuthor(), msg.getAuthor()) && Objects.equal(last.getMessage(), msg.getMessage())) { long lastMs = last.getWrittenOn().getTime(); long msgMs = msg.getWrittenOn().getTime(); return msgMs - lastMs > DUPLICATE_MESSAGE_INTERVAL ? RetryStatus.UNSUBMIT : RetryStatus.RETRY_NO_MESSAGE; } } return RetryStatus.RETRY_ADD_MESSAGE; } catch (OrmException err) { log.warn("Cannot check previous merge failure, unsubmitting", err); return RetryStatus.UNSUBMIT; } }
Source:
<code>public Ample.TabletMutator putFlushId(long flushId) { Preconditions.checkState(updatesEnabled, "Cannot make updates after calling mutate."); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(mutation, <START> new Value(("" + flushId).getBytes())); <END> return this; }</code><technical_language>constuctor takes String encodes UTF8</technical_language>

Target:
public Ample.TabletMutator putFlushId(long flushId) { Preconditions.checkState(updatesEnabled, "Cannot make updates after calling mutate."); TabletsSection.ServerColumnFamily.FLUSH_COLUMN.put(mutation, new Value(Long.toString(flushId))); return this; }
Source:
<code>private void sendRequest(final String message) { String ticket; JsonObject jMessage; try { jMessage = (JsonObject) Json.parse(message); ticket = jMessage.getString("ticket", null); } catch (Throwable t) { LOG.error(String.format("Unexpected exception pending request message handling.\n", message), t); return; } try { String endpoint = jMessage.getString("ep", null); if (!isResponsibleFor(endpoint)) return; Client destination = clientRegistry.get(endpoint); if (destination == null) { sendError(ticket, String.format("No registration for this endpoint %s.", endpoint)); } DownlinkRequest<?> request = DownlinkRequestSerDes.deserialize((JsonObject) jMessage.get("req")); sendAck(ticket); server.send(destination, ticket, request); <START> } catch (Throwable t) { <END> String errorMessage = String.format("Unexpected exception pending request message handling.(%s:%s)", t.toString(), t.getMessage()); LOG.error(errorMessage, t); sendError(ticket, errorMessage); } }</code><technical_language>catch RuntimeException</technical_language>

Target:
private void sendRequest(final String message) { String ticket; JsonObject jMessage; try { jMessage = (JsonObject) Json.parse(message); ticket = jMessage.getString("ticket", null); } catch (RuntimeException t) { LOG.error(String.format("Unexpected exception pending request message handling.\n", message), t); return; } try { String endpoint = jMessage.getString("ep", null); if (!isResponsibleFor(endpoint)) return; Client destination = clientRegistry.get(endpoint); if (destination == null) { sendError(ticket, String.format("No registration for this endpoint %s.", endpoint)); } DownlinkRequest<?> request = DownlinkRequestSerDes.deserialize((JsonObject) jMessage.get("req")); sendAck(ticket); server.send(destination, ticket, request); } catch (RuntimeException t) { String errorMessage = String.format("Unexpected exception pending request message handling.(%s:%s)", t.toString(), t.getMessage()); LOG.error(errorMessage, t); sendError(ticket, errorMessage); } }
Source:
<code>protected Constraint twoExamsInADay(ConstraintFactory constraintFactory) { return constraintFactory.from(TopicConflict.class) .join(Exam.class, equal(TopicConflict::getLeftTopic, Exam::getTopic), filtering((topicConflict, leftExam) -> leftExam.getPeriod() != null)) .ifExists(Exam.class, equal((topicConflict, leftExam) -> topicConflict.getRightTopic(), Exam::getTopic), equal((topicConflict, leftExam) -> leftExam.getDayIndex(), Exam::getDayIndex), filtering((topicConflict, leftExam, rightExam) -> getPeriodIndexDifferenceBetweenExams(leftExam, rightExam) > 1)) <START> .join(ExaminationConstraintConfiguration.class) .penalize("Two exams in a day", HardSoftScore.ONE_SOFT, (topicConflict, leftExam, config) -> topicConflict.getStudentSize() * config.getTwoInADayPenalty()); <END> }</code><technical_language>I is a ConstraintConfiguration available. Yet, penalize() instead of penalizeConfigurable(). I suggest change that, @michaltomco</technical_language>

Target:
protected Constraint twoExamsInADay(ConstraintFactory constraintFactory) { return constraintFactory.from(TopicConflict.class) .join(Exam.class, equal(TopicConflict::getLeftTopic, Exam::getTopic), filtering((topicConflict, leftExam) -> leftExam.getPeriod() != null)) .ifExists(Exam.class, equal((topicConflict, leftExam) -> topicConflict.getRightTopic(), Exam::getTopic), equal((topicConflict, leftExam) -> leftExam.getDayIndex(), Exam::getDayIndex), filtering((topicConflict, leftExam, rightExam) -> getPeriodIndexDifferenceBetweenExams(leftExam, rightExam) > 1)) .penalizeConfigurable("twoExamsInADay", (topicConflict, leftExam) -> topicConflict.getStudentSize()); }
Source:
<code>public static int compareAnnotationMirrors(AnnotationMirror a1, AnnotationMirror a2) { if (!AnnotationUtils.areSameByName(a1, a2)) { return annotationName(a1).compareTo(annotationName(a2)); } if (AnnotationUtils.sameElementValues(a1, a2)) { return 0; } Map<? extends ExecutableElement, ? extends AnnotationValue> vals1 = a1.getElementValues(); Map<? extends ExecutableElement, ? extends AnnotationValue> vals2 = a2.getElementValues(); Set<ExecutableElement> sortedElements = new TreeSet<>(Comparator.comparing(ElementUtils::getSimpleName)); sortedElements.addAll( ElementFilter.methodsIn(a1.getAnnotationType().asElement().getEnclosedElements())); for (ExecutableElement method : sortedElements) { AnnotationValue value1 = vals1.get(method); AnnotationValue value2 = vals2.get(method); if (value1 == null) { value1 = method.getDefaultValue(); } if (value2 == null) { value2 = method.getDefaultValue(); } if (value1 == value2) { continue; } else if (value1 == null) { return -1; } else if (value2 == null) { return 1; } <START> int result = value1.getValue().toString().compareTo(value2.getValue().toString()); <END> if (result != 0) { return result; } } return 0; }</code><technical_language>Instead of String comparison here, nicer change boolean sameAnnotationValueValue(Object val1, Object val2) <LINK_0> a comparator? is, a version returns int boolean version compares 0</technical_language>

Target:
public static int compareAnnotationMirrors(AnnotationMirror a1, AnnotationMirror a2) { if (!AnnotationUtils.areSameByName(a1, a2)) { return annotationName(a1).compareTo(annotationName(a2)); } Map<? extends ExecutableElement, ? extends AnnotationValue> vals1 = a1.getElementValues(); Map<? extends ExecutableElement, ? extends AnnotationValue> vals2 = a2.getElementValues(); Set<ExecutableElement> sortedElements = new TreeSet<>(Comparator.comparing(ElementUtils::getSimpleName)); sortedElements.addAll( ElementFilter.methodsIn(a1.getAnnotationType().asElement().getEnclosedElements())); for (ExecutableElement meth : sortedElements) { AnnotationValue aval1 = vals1.get(meth); AnnotationValue aval2 = vals2.get(meth); if (aval1 == null) { aval1 = meth.getDefaultValue(); } if (aval2 == null) { aval2 = meth.getDefaultValue(); } int result = compareAnnotationValue(aval1, aval2); if (result != 0) { return result; } } return 0; }
Source:
<code><START> public void testSubscriptionWithManyEventTypesIsNotCreated() { <END> final List<String> eventTypes = IntStream.range(0, 31).mapToObj(i -> createEventType()) .map(et -> et.getName()) .collect(Collectors.toList()); final String subscription = "{\"owning_application\":\"app\",\"event_types\":" + "[" + eventTypes.stream().map(et -> "\"" + et + "\"").collect(Collectors.joining(",")) + "]}"; final Response response = given() .body(subscription) .contentType(JSON) .post(SUBSCRIPTIONS_URL); response .then() .statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY) .contentType(JSON) .body("title", equalTo("Unprocessable Entity")) .body("detail", equalTo("total partition count for subscription is 31 while only 30 allowed")); }</code><technical_language>I tests unit tests. I reason for acceptance tests</technical_language>

Target:
public void testSubscriptionWithManyEventTypesIsNotCreated() { final List<String> eventTypes = IntStream.range(0, 31).mapToObj(i -> createEventType()) .map(et -> et.getName()) .collect(Collectors.toList()); final String subscription = "{\"owning_application\":\"app\",\"event_types\":" + "[" + eventTypes.stream().map(et -> "\"" + et + "\"").collect(Collectors.joining(",")) + "]}"; final Response response = given() .body(subscription) .contentType(JSON) .post(SUBSCRIPTIONS_URL); response .then() .statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY) .contentType(JSON) .body("title", equalTo("Unprocessable Entity")) .body("detail", equalTo( "total partition count for subscription is 31, but the maximum partition count is 30")); }
Source:
<code>private void deleteMapFamily(EntityId entityId, FamilyLayout familyLayout, long upToTimestamp) throws IOException { final State state = mState.get(); Preconditions.checkState(state == State.OPEN, "Cannot delete map family while KijiTableWriter %s is in state %s.", this, state); final String familyName = familyLayout.getName(); final HBaseColumnName hbaseColumnName = mWriterLayoutCapsule.getColumnNameTranslator() .toHBaseColumnName(new KijiColumnName(familyName)); final byte[] hbaseRow = entityId.getHBaseRowKey(); final Scanner scanner = mHBClient.newScanner(mTable.getName()); scanner.setFilter(new ColumnPrefixFilter(hbaseColumnName.getQualifier())); <START> scanner.setStartKey(hbaseRow); <END> final ArrayList<KeyValue> results; try { results = scanner.nextRows(1).join().get(0); } catch (Exception e) { ZooKeeperUtils.wrapAndRethrow(e); throw new InternalKijiError(e); } scanner.close(); if (results.isEmpty()) { LOG.debug("No qualifiers to delete in map family: " + familyName); } else { for (KeyValue keyValue : results) { final DeleteRequest delete = new DeleteRequest( Bytes.toBytes(mTable.getName()), hbaseRow, keyValue.family(), keyValue.qualifier(), upToTimestamp); try { mHBClient.delete(delete).join(); } catch (Exception e) { ZooKeeperUtils.wrapAndRethrow(e); } } } }</code><technical_language>set end key of row, causing server do a lot of extra work retrieving more rows use</technical_language>

Target:
private void deleteMapFamily(EntityId entityId, FamilyLayout familyLayout, long upToTimestamp) throws IOException { final State state = mState.get(); Preconditions.checkState(state == State.OPEN, "Cannot delete map family while KijiTableWriter %s is in state %s.", this, state); final String familyName = familyLayout.getName(); final HBaseColumnName hbaseColumnName = mWriterLayoutCapsule.getColumnNameTranslator() .toHBaseColumnName(new KijiColumnName(familyName)); final byte[] hbaseRow = entityId.getHBaseRowKey(); final Scanner scanner = mHBClient.newScanner(mTable.getName()); scanner.setFilter(new ColumnPrefixFilter(hbaseColumnName.getQualifier())); scanner.setStartKey(hbaseRow); scanner.setStopKey(hbaseRow); final ArrayList<KeyValue> results; try { results = scanner.nextRows(1).join().get(0); } catch (Exception e) { ZooKeeperUtils.wrapAndRethrow(e); throw new InternalKijiError(e); } scanner.close(); if (results.isEmpty()) { LOG.debug("No qualifiers to delete in map family: " + familyName); } else { for (KeyValue keyValue : results) { final DeleteRequest delete = new DeleteRequest( mTableName, hbaseRow, keyValue.family(), keyValue.qualifier(), upToTimestamp); try { mHBClient.delete(delete).join(); } catch (Exception e) { ZooKeeperUtils.wrapAndRethrow(e); } } } }
Source:
<code>public List<TaskDescriptor> getTasksToSchedule() throws NotConnectedException, PermissionException { Policy policy = null; List<TaskDescriptor> eligibleTasks = new ArrayList<>(); <START> Map<JobId, JobDescriptor> jobMap = schedulingService.lockJobsToSchedule(); <END> try { policy = (Policy) Class.forName(getCurrentPolicy()).newInstance(); if (jobMap.isEmpty()) { return eligibleTasks; } List<JobDescriptor> descriptors = new ArrayList<>(jobMap.values()); LinkedList<EligibleTaskDescriptor> taskRetrievedFromPolicy = policy.getOrderedTasks(descriptors); if (taskRetrievedFromPolicy.isEmpty()) { return eligibleTasks; } eligibleTasks = (List) taskRetrievedFromPolicy; } catch (Exception e) { logger.error("Error Loading Current Policy:", e); } finally { schedulingService.unlockJobsToSchedule(jobMap.values()); } return eligibleTasks; }</code><technical_language>move this instruction in try bloc. If leave there, if is exception in lockJobsToSchedule(), lock released in finally bloc</technical_language>

Target:
public List<TaskDescriptor> getTasksToSchedule() throws NotConnectedException, PermissionException { Policy policy = null; List<TaskDescriptor> eligibleTasks = new ArrayList<>(); Map<JobId, JobDescriptor> jobMap = null; try { jobMap = schedulingService.lockJobsToSchedule(); policy = (Policy) Class.forName(getCurrentPolicy()).newInstance(); if (jobMap.isEmpty()) { return eligibleTasks; } List<JobDescriptor> descriptors = new ArrayList<>(jobMap.values()); LinkedList<EligibleTaskDescriptor> taskRetrievedFromPolicy = policy.getOrderedTasks(descriptors); if (taskRetrievedFromPolicy.isEmpty()) { return eligibleTasks; } eligibleTasks = (List) taskRetrievedFromPolicy; } catch (Exception e) { logger.error("Error Loading Current Policy:", e); } finally { schedulingService.unlockJobsToSchedule(jobMap.values()); } return eligibleTasks; }
Source:
<code>public static Ownership getLockOwnership(Object key, ClusteringDependentLogic clusteringDependentLogic) { Object keyToCheck = key instanceof DeltaCompositeKey ? ((DeltaCompositeKey) key).getDeltaAwareValueKey() : key; DistributionInfo distributionInfo = clusteringDependentLogic.getCacheTopology().getDistribution(keyToCheck); <START> return distributionInfo.isPrimary() ? Ownership.PRIMARY : <END> (distributionInfo.isWriteBackup() ? Ownership.BACKUP : Ownership.NON_OWNER); }</code><technical_language>I add DistributionInfo.getOwnership()</technical_language>

Target:
public static Ownership getLockOwnership(Object key, ClusteringDependentLogic clusteringDependentLogic) { Object keyToCheck = key instanceof DeltaCompositeKey ? ((DeltaCompositeKey) key).getDeltaAwareValueKey() : key; DistributionInfo distributionInfo = clusteringDependentLogic.getCacheTopology().getDistribution(keyToCheck); return distributionInfo.writeOwnership(); }
Source:
<code>public String getObjectIdentifier(JobProperty<?> obj){ if (JobPropertyImpl.class.getName().equals(obj.getClass().getName())){ return "JobPropertyImpl"; } <START> return null; <END> }</code><technical_language>null safe</technical_language>

Target:
public String getObjectIdentifier(JobProperty<?> obj){ if ( obj!=null && JobPropertyImpl.class.getName().equals(obj.getClass().getName())){ return JobPropertyImplSelector.class.getName(); } return null; }