auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Size autoConvert(long size, SizeUnit inUnit) { <START> for (long i = weightToUnit.size(); i >= inUnit.getUnitWeight(); i--) { <END> if (size / Math.pow(CONVERT_FACTOR, i - 1) >= 1) { return new SizeConverter.Size(SizeConverter.SizeUnit.getUnit(i), SizeConverter.convert(size, inUnit, SizeUnit.getUnit(i)).doubleValue()); } } return new Size(SizeUnit.BYTES, new Double(new Long(size))); }</code><technical_language>IIUC, usage of values is iterate bigger unit unit. instead of implementing a reverse order here, change implementation of CompareUnits.unit1Weight reversed iterate elements in a regular fashion. construct a simple list: private static List<SizeUnit> units = new ArrayList<SizeUnit>() {{ add(GB); add(MB); add(KB); add(BYTE); }} other variation of creating this list. reason i a tree is data structure for this need is: iterate elements. if agreed, drop tree compareUtils this list instead reside SizeUnit</technical_language>

Target:
public static Size autoConvert(long size, SizeUnit inUnit) { for (long i = weightToUnit.size(); i >= inUnit.getUnitWeight(); i--) { if (size / Math.pow(CONVERT_FACTOR, i - 1) >= 1) { return new Size(SizeConverter.SizeUnit.getUnit(i), Double.valueOf(SizeConverter.convert(size, inUnit, SizeUnit.getUnit(i)).doubleValue())); } } return new Size(SizeUnit.BYTES, new Double(new Long(size))); }
Source:
<code>public Intent generate(EvaluationContext ec) { Intent i = new Intent(); if(className != null){ i.setAction(className); } if(type != null){ i.setType(type); } if(data != null){ i.setData(Uri.parse(data)); } if(component != null){ <START> i.setComponent(new ComponentName(component, className)); <END> } for(Enumeration<String> en = refs.keys() ; en.hasMoreElements() ;) { String key = en.nextElement(); AbstractTreeElement e = ec.resolveReference(refs.get(key)); if(e != null && e.getValue() != null) { i.putExtra(key, e.getValue().uncast().getString()); } } return i; }</code><technical_language>want verify className null</technical_language>

Target:
public Intent generate(EvaluationContext ec) { Intent i = new Intent(); if(className != null){ i.setAction(className); if(component != null){ i.setComponent(new ComponentName(component, className)); } } if(type != null){ i.setType(type); } if(data != null){ i.setData(Uri.parse(data)); } for(Enumeration<String> en = refs.keys() ; en.hasMoreElements() ;) { String key = en.nextElement(); AbstractTreeElement e = ec.resolveReference(refs.get(key)); if(e != null && e.getValue() != null) { i.putExtra(key, e.getValue().uncast().getString()); } } return i; }
Source:
<code>protected void trackEventsProcessedProgress(int recordCount) { _eventsProcessedCount += recordCount; Duration timeSinceLastLog = Duration.between(_eventsProcessedCountLoggedTime, Instant.now()); if (timeSinceLastLog.compareTo(LOG_EVENTS_PROCESSED_PROGRESS_DURATION) > 0) { <START> _logger.info("Processed records in milliseconds for datastream {}", _eventsProcessedCount, <END> timeSinceLastLog.toMillis(), _datastreamName); _eventsProcessedCount = 0; _eventsProcessedCountLoggedTime = Instant.now(); } }</code><technical_language>in seconds nicer in milliseconds especially if duration is changed a bigger</technical_language>

Target:
protected void trackEventsProcessedProgress(int recordCount) { _eventsProcessedCount += recordCount; Duration timeSinceLastLog = Duration.between(_eventsProcessedCountLoggedTime, Instant.now()); if (timeSinceLastLog.compareTo(LOG_EVENTS_PROCESSED_PROGRESS_DURATION) > 0) { _logger.info("Processed records in seconds for datastream {}", _eventsProcessedCount, timeSinceLastLog.getSeconds(), _datastreamName); _eventsProcessedCount = 0; _eventsProcessedCountLoggedTime = Instant.now(); } }
Source:
<code>protected void addWrite(int size) { <START> if(size < 0) { <END> throw new IllegalArgumentException("Size must be positive number"); } super.addWrite(size); }</code><technical_language>If want save a code, "ArgumentVerifier" in org.threadly.utils. designed a save jar space reducing duplicated code</technical_language>

Target:
protected void addWrite(int size) { ArgumentVerifier.assertNotNegative(size, "size"); super.addWrite(size); }
Source:
<code>public static boolean workspaceLayerGroupInherit() { <START> String value = GeoServerExtensions.getProperty("GEOSERVER_GLOBAL_LAYER_GROUP_INHERIT"); <END> if(value != null){ return Boolean.parseBoolean(value); } else { return true; } }</code><technical_language>property changed runtime it? put in a static field avoid repeated lookups</technical_language>

Target:
public static boolean workspaceLayerGroupInherit() { if(groupInherit==null){ String value = GeoServerExtensions.getProperty("GEOSERVER_GLOBAL_LAYER_GROUP_INHERIT"); if(value != null){ groupInherit = Boolean.parseBoolean(value); } else { groupInherit = true; } } return groupInherit; }
Source:
<code>public GlusterGeoRepSessionDetails mapRow(ResultSet rs, int rowNum) throws SQLException { GlusterGeoRepSessionDetails entity = new GlusterGeoRepSessionDetails(); <START> entity.setSessionId(getGuidDefaultEmpty(rs, "session_id")); <END> entity.setMasterBrickId(getGuidDefaultEmpty(rs, "master_brick_id")); entity.setSlaveHostName(rs.getString("slave_host_name")); entity.setSlaveNodeUuid(getGuid(rs, "slave_host_uuid")); entity.setStatus(GeoRepSessionStatus.valueOf(rs.getString("status"))); entity.setCheckPointStatus(rs.getString("checkpoint_status")); entity.setCrawlStatus(GeoRepCrawlStatus.valueOf(rs.getString("crawl_status"))); entity.setFilesSynced(rs.getLong("files_synced")); entity.setFilesPending(rs.getLong("files_pending")); entity.setBytesPending(rs.getLong("bytes_pending")); entity.setDeletesPending(rs.getLong("deletes_pending")); entity.setFilesSkipped(rs.getLong("files_skipped")); return entity; }</code><technical_language>renamed setId in entity patch BusinessEntity<Guid> requires setId getId overriden I considered this id for it</technical_language>

Target:
public GlusterGeoRepSessionDetails mapRow(ResultSet rs, int rowNum) throws SQLException { GlusterGeoRepSessionDetails entity = new GlusterGeoRepSessionDetails(); entity.setId(getGuidDefaultEmpty(rs, "session_id")); entity.setMasterBrickId(getGuidDefaultEmpty(rs, "master_brick_id")); entity.setSlaveHostName(rs.getString("slave_host_name")); entity.setSlaveNodeUuid(getGuid(rs, "slave_host_uuid")); entity.setStatus(GeoRepSessionStatus.valueOf(rs.getString("status"))); entity.setCheckPointStatus(rs.getString("checkpoint_status")); entity.setCrawlStatus(GeoRepCrawlStatus.valueOf(rs.getString("crawl_status"))); entity.setFilesSynced(rs.getLong("files_synced")); entity.setFilesPending(rs.getLong("files_pending")); entity.setBytesPending(rs.getLong("bytes_pending")); entity.setDeletesPending(rs.getLong("deletes_pending")); entity.setFilesSkipped(rs.getLong("files_skipped")); return entity; }
Source:
<code>public void start() { if (!isRunning()) { try { if (log.isDebugEnabled()) { <START> log.debug("starting process"); <END> } process = processBuilder.start(); stdout = process.getInputStream(); stdin = process.getOutputStream(); running.set(true); if (log.isDebugEnabled()) { log.debug("process started"); } } catch (IOException e) { log.error(e.getMessage(),e); throw new RuntimeException(e.getMessage(),e); } } }</code><technical_language>Add command is executed log</technical_language>

Target:
public void start() { if (!isRunning()) { if (log.isDebugEnabled()) { log.debug("starting process. Command = [" + command + "]"); } try { process = processBuilder.start(); } catch (IOException e) { log.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } if (!processBuilder.redirectErrorStream()) { monitorErrorStream(); } monitorProcess(); stdout = process.getInputStream(); stdin = process.getOutputStream(); running.set(true); if (log.isDebugEnabled()) { log.debug("process started. Command = [" + command + "]"); } } }
Source:
<code>protected Map getImgMetadata(File file) { logger.debug("Get image Metadata in Resource Action"); <START> Map<String, String> map = new HashMap<>(); <END> try { Metadata meta = ImageMetadataReader.readMetadata(file); map = processMetaData(meta); } catch (ImageProcessingException ex) { logger.error("Error reading metadata from file " + this.getFileName() + " - message " + ex.getMessage()); } catch (IOException ioex) { logger.error("Error reading file", ioex); } return map; }</code><technical_language>Change this variable declaration meaning in context. map is unclear</technical_language>

Target:
protected Map getImgMetadata(File file) { logger.debug("Get image Metadata in Resource Action"); Map<String, String> imgMetdata = new HashMap<>(); try { Metadata meta = ImageMetadataReader.readMetadata(file); imgMetdata = processMetaData(meta); } catch (ImageProcessingException ex) { logger.error("Error reading metadata from file " + this.getFileName() + " - message " + ex.getMessage(), ex); } catch (IOException ioex) { logger.error("Error reading file", ioex); } return imgMetdata; }
Source:
<code>public void checkAttributeValue(PerunSessionImpl sess, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException{ if(attribute.getValue() == null) return; String attrValue = (String) attribute.getValue(); if(!attrValue.equals("true") && !attrValue.equals("false")) { throw new WrongAttributeValueException(attribute, group, "If attribute is not null, only string 'true' or 'false' is correct format."); } try { if (attrValue.equals("true") && (sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROINTERVAL_ATTRNAME).getValue() == null || sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPMEMBERSQUERY_ATTRNAME).getValue() == null || sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPEXTSOURCE_ATTRNAME).getValue() == null)) { <START> throw new WrongReferenceAttributeValueException("At least one of required attributes " + GROUPSYNCHROINTERVAL_ATTRNAME + ", " + GROUPMEMBERSQUERY_ATTRNAME + " or " + GROUPEXTSOURCE_ATTRNAME + " is not set."); <END> } } catch (AttributeNotExistsException e) { throw new ConsistencyErrorException(e); } }</code><technical_language>This exception hold actual attributes, is convenient in GUI, state attributes wrong is value. please split this throwing 3 proper attributes passed exception. Thank you</technical_language>

Target:
public void checkAttributeValue(PerunSessionImpl sess, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException{ if(attribute.getValue() == null) return; String attrValue = (String) attribute.getValue(); if(!attrValue.equals("true") && !attrValue.equals("false")) { throw new WrongAttributeValueException(attribute, group, "If attribute is not null, only string 'true' or 'false' is correct format."); } try { if (attrValue.equals("true")) { Attribute requiredAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROINTERVAL_ATTRNAME); if (requiredAttribute.getValue() == null) { throw new WrongReferenceAttributeValueException(attribute, requiredAttribute, requiredAttribute.toString() + " must be set in order to enable synchronization."); } requiredAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPMEMBERSQUERY_ATTRNAME); if (requiredAttribute.getValue() == null) { throw new WrongReferenceAttributeValueException(attribute, requiredAttribute, requiredAttribute.toString() + " must be set in order to enable synchronization."); } requiredAttribute = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPEXTSOURCE_ATTRNAME); if (requiredAttribute.getValue() == null) { throw new WrongReferenceAttributeValueException(attribute, requiredAttribute, requiredAttribute.toString() + " must be set in order to enable synchronization."); } } } catch (AttributeNotExistsException e) { throw new ConsistencyErrorException(e); } }
Source:
<code>UnsynchronizedStaticFormatterRule(Class<?> formatterClassToCheck) { <START> this.formatterClassToCheck = formatterClassToCheck; <END> }</code><technical_language>this constructor rule chain... a call this(); is missing</technical_language>

Target:
UnsynchronizedStaticFormatterRule(Class<?> formatterClassToCheck) { this(); this.formatterClassToCheck = formatterClassToCheck; }
Source:
<code>public LocalSearchMatcher newLocalSearchMatcher(Object[] parameters) throws ViatraQueryException, QueryProcessingException { ViatraQueryEngine engine = (ViatraQueryEngine) hintProvider; final ISearchContext searchContext = new ISearchContext.SearchContext(engine.getBaseIndex()); Set<EClass> classesToIndex = Sets.newHashSet(); Set<EStructuralFeature> featuresToIndex = Sets.newHashSet(); Set<EDataType> dataTypesToIndex = Sets.newHashSet(); final Set<PParameter> adornment = Sets.newHashSet(); for (int i = 0; i < parameters.length; i++) { if (parameters[i] != null) { adornment.add(query.getParameters().get(i)); } } final MatcherReference reference = new MatcherReference(query, adornment); Set<MatcherReference> dependencies = Sets.newHashSet(reference); Set<MatcherReference> processedDependencies = Sets.newHashSet(); Set<MatcherReference> todo = Sets.difference(dependencies, processedDependencies); while (!todo.isEmpty()) { final MatcherReference dependency = todo.iterator().next(); <START> Planner planner = new Planner(backend, plannerConfiguration); <END> planner.createPlan(dependency, planProvider, searchContext); planner.collectElementsToIndex(classesToIndex, featuresToIndex, dataTypesToIndex); planner.collectDependencies(dependencies); processedDependencies.add(dependency); } searchContext.registerObservedTypes(classesToIndex, dataTypesToIndex, featuresToIndex); return searchContext.getMatcher(reference); }</code><technical_language>I do understand this line. create a separate planner for dependency of query, of planners plannerConfiguration? How/when hints for called queries (if hints of calling query) account</technical_language>

Target:
public LocalSearchMatcher newLocalSearchMatcher(Object[] parameters) throws ViatraQueryException, QueryProcessingException { ViatraQueryEngine engine = (ViatraQueryEngine) hintProvider; final ISearchContext searchContext = new ISearchContext.SearchContext(engine.getBaseIndex()); Set<EClass> classesToIndex = Sets.newHashSet(); Set<EStructuralFeature> featuresToIndex = Sets.newHashSet(); Set<EDataType> dataTypesToIndex = Sets.newHashSet(); final Set<PParameter> adornment = Sets.newHashSet(); for (int i = 0; i < parameters.length; i++) { if (parameters[i] != null) { adornment.add(query.getParameters().get(i)); } } final MatcherReference reference = new MatcherReference(query, adornment); Set<MatcherReference> dependencies = Sets.newHashSet(reference); Set<MatcherReference> processedDependencies = Sets.newHashSet(); Set<MatcherReference> todo = Sets.difference(dependencies, processedDependencies); while (!todo.isEmpty()) { final MatcherReference dependency = todo.iterator().next(); Collection<SearchPlanForBody> compiledPlans = createPlan(dependency, planProvider, searchContext); collectElementsToIndex(compiledPlans, classesToIndex, featuresToIndex, dataTypesToIndex); collectDependencies(compiledPlans, dependencies); processedDependencies.add(dependency); } searchContext.registerObservedTypes(classesToIndex, dataTypesToIndex, featuresToIndex); return searchContext.getMatcher(reference); }
Source:
<code>public static void disableHealthMetrics() { <START> System.clearProperty(AbstractFolderConfiguration.class.getName() + ".ADD_HEALTH_METRICS"); <END> }</code><technical_language>I kind of picky, if this restore original (imagine running this system Jenkins is running)</technical_language>

Target:
public static void disableHealthMetrics() { if (HEALTH_METRIC_PROPERTY != null) { System.setProperty(AbstractFolderConfiguration.class.getName() + ".ADD_HEALTH_METRICS", HEALTH_METRIC_PROPERTY); } else { System.clearProperty(AbstractFolderConfiguration.class.getName() + ".ADD_HEALTH_METRICS"); } }
Source:
<code>private boolean isCcpEmpty() { <START> if(ccp.getSelectedCountryName()==null) <END> return true; return false; }</code><technical_language>For easier maintainability in future, I suggest curly braces for this if condition</technical_language>

Target:
private boolean isCcpEmpty() { return mCountryCodePicker.getSelectedCountryName() == null; }
Source:
<code>public void setPassword(Principal principal, PasswordCallback passwordCallback) throws IOException, AccountNotFoundException { if (principal == null) { throw new IllegalArgumentException("Principal should never be null"); } String userName = principal.getName(); String password = ""; if (passwordCallback instanceof PlainPasswordCallback) { password = ((PlainPasswordCallback) passwordCallback).getPlainPassword(); } boolean isAuthenticated = false; try { if (authenticationService != null) { isAuthenticated = authenticationService.isValidUser(userName, password); } else { logger.error("No AuthenticationService implementation is available"); } } catch (AuthenticationException e) { <START> logger.error("Error while validating user" + userName, e); <END> } if (passwordCallback instanceof PlainPasswordCallback) { ((PlainPasswordCallback) passwordCallback).setAuthenticated(isAuthenticated); } }</code><technical_language>need a space : user"+ userName</technical_language>

Target:
public void setPassword(Principal principal, PasswordCallback passwordCallback) throws IOException, AccountNotFoundException { if (principal == null) { throw new IllegalArgumentException("Principal should never be null"); } String userName = principal.getName(); char[] password = new char[10]; if (passwordCallback instanceof PlainPasswordCallback) { password = ((PlainPasswordCallback) passwordCallback).getPlainPassword().toCharArray(); } boolean isAuthenticated = false; try { if (authenticationService != null) { isAuthenticated = authenticationService.isValidUser(userName, password); } else { logger.error("No AuthenticationService implementation is available"); } } catch (AuthenticationException e) { logger.error("Error while validating user: " + userName, e); } if (passwordCallback instanceof PlainPasswordCallback) { ((PlainPasswordCallback) passwordCallback).setAuthenticated(isAuthenticated); } }
Source:
<code>public @Nullable ConfigDescription getConfigDescription(URI uri, Locale locale) { List<ConfigDescriptionParameter> parameters = new ArrayList<ConfigDescriptionParameter>(); List<ConfigDescriptionParameterGroup> parameterGroups = new ArrayList<ConfigDescriptionParameterGroup>(); URI aliasedURI = uri; <START> for (ConfigDescriptionAliasHandler aliasHandler : configDescriptionAliasHandlers) { <END> URI alias = aliasHandler.getAlias(uri); if (alias != null) { aliasedURI = alias; break; } } boolean found = false; for (ConfigDescriptionProvider configDescriptionProvider : this.configDescriptionProviders) { ConfigDescription config = configDescriptionProvider.getConfigDescription(aliasedURI, locale); if (config != null) { found = true; parameters.addAll(config.getParameters()); parameterGroups.addAll(config.getParameterGroups()); } } if (found) { List<ConfigDescriptionParameter> parametersWithOptions = new ArrayList<ConfigDescriptionParameter>( parameters.size()); for (ConfigDescriptionParameter parameter : parameters) { parametersWithOptions.add(getConfigOptions(aliasedURI, parameter, locale)); } return new ConfigDescription(aliasedURI, parametersWithOptions, parameterGroups); } else { return null; } }</code><technical_language>this code moved below. alias kick in a fallback, if other provider able provide a specific description. (request for -> desc -> thing-type desc of thing)</technical_language>

Target:
public @Nullable ConfigDescription getConfigDescription(URI uri, Locale locale) { List<ConfigDescriptionParameter> parameters = new ArrayList<ConfigDescriptionParameter>(); List<ConfigDescriptionParameterGroup> parameterGroups = new ArrayList<ConfigDescriptionParameterGroup>(); boolean found = fillFromProviders(uri, locale, parameters, parameterGroups); URI alias = null; if (!found) { for (ConfigDescriptionAliasProvider aliasProvider : configDescriptionAliasProviders) { alias = aliasProvider.getAlias(uri); if (alias != null) { logger.debug("No config description found for '{}', using alias '{}' instead", uri, alias); found = fillFromProviders(alias, locale, parameters, parameterGroups); break; } } } if (found) { List<ConfigDescriptionParameter> parametersWithOptions = new ArrayList<ConfigDescriptionParameter>( parameters.size()); for (ConfigDescriptionParameter parameter : parameters) { parametersWithOptions.add(getConfigOptions(uri, alias, parameter, locale)); } return new ConfigDescription(uri, parametersWithOptions, parameterGroups); } else { return null; } }
Source:
<code>public void testNoHangIfPartitionIsOffline() throws Exception { BackgroundHiveSplitLoader backgroundHiveSplitLoader = backgroundHiveSplitLoaderNoMetadata(); HiveSplitSource hiveSplitSource = hiveSplitSource(backgroundHiveSplitLoader, TupleDomain.none()); backgroundHiveSplitLoader.start(hiveSplitSource); try { drain(hiveSplitSource); } <START> catch (Exception e) { <END> assertEquals(e.getMessage(), "java.lang.Exception: OFFLINE"); } boolean failed = false; try { hiveSplitSource.isFinished(); } catch (Exception e) { failed = true; } assertEquals(failed, true); }</code><technical_language>drain is expected throw exception. If I right missed call fail drain drain thrown exception. Alternatively use: org.testng.Assert#assertThrows org.testng.Assert#expectThrows</technical_language>

Target:
public void testNoHangIfPartitionIsOffline() throws Exception { BackgroundHiveSplitLoader backgroundHiveSplitLoader = backgroundHiveSplitLoaderOfflinePartitions(); HiveSplitSource hiveSplitSource = hiveSplitSource(backgroundHiveSplitLoader, TupleDomain.all()); backgroundHiveSplitLoader.start(hiveSplitSource); assertThrows(RuntimeException.class, () -> drain(hiveSplitSource)); assertThrows(RuntimeException.class, () -> hiveSplitSource.isFinished()); }
Source:
<code>protected Menu getMenu(final MMenu mmenu, ToolItem toolItem) { Object obj = mmenu.getWidget(); if (obj instanceof Menu && !((Menu) obj).isDisposed()) { return (Menu) obj; } if (mmenu instanceof MRenderedMenu) { obj = ((MRenderedMenu) mmenu).getContributionManager(); if (obj instanceof IContextFunction) { final IEclipseContext lclContext = getContext(mmenu); obj = ((IContextFunction) obj).compute(lclContext, null); ((MRenderedMenu) mmenu).setContributionManager(obj); } if (obj instanceof IMenuCreator) { final IMenuCreator creator = (IMenuCreator) obj; final Menu menu = creator.getMenu(toolItem.getParent() .getShell()); if (menu != null) { toolItem.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (menu != null && !menu.isDisposed()) { creator.dispose(); ((MRenderedMenu) mmenu).setWidget(null); } } }); menu.setData(AbstractPartRenderer.OWNING_ME, menu); return menu; } } } else { final IEclipseContext lclContext = getContext(mmenu); IPresentationEngine engine = lclContext .get(IPresentationEngine.class); obj = engine.createGui(mmenu, toolItem.getParent(), lclContext); <START> if (obj instanceof Menu) { <END> return (Menu) obj; } System.err.println("Rendering returned " + obj); } return null; }</code><technical_language>a candidate for assertion</technical_language>

Target:
protected Menu getMenu(final MMenu mmenu, ToolItem toolItem) { Object obj = mmenu.getWidget(); if (obj instanceof Menu && !((Menu) obj).isDisposed()) { return (Menu) obj; } if (mmenu instanceof MRenderedMenu) { obj = ((MRenderedMenu) mmenu).getContributionManager(); if (obj instanceof IContextFunction) { final IEclipseContext lclContext = getContext(mmenu); obj = ((IContextFunction) obj).compute(lclContext, null); ((MRenderedMenu) mmenu).setContributionManager(obj); } if (obj instanceof IMenuCreator) { final IMenuCreator creator = (IMenuCreator) obj; final Menu menu = creator.getMenu(toolItem.getParent() .getShell()); if (menu != null) { toolItem.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (menu != null && !menu.isDisposed()) { creator.dispose(); ((MRenderedMenu) mmenu).setWidget(null); } } }); menu.setData(AbstractPartRenderer.OWNING_ME, menu); return menu; } } } else { final IEclipseContext lclContext = getContext(model); IPresentationEngine engine = lclContext .get(IPresentationEngine.class); obj = engine.createGui(mmenu, toolItem.getParent(), lclContext); if (obj instanceof Menu) { return (Menu) obj; } if (logger != null) { logger.debug("Rendering returned " + obj); } } return null; }
Source:
<code>public String login(String username, String password) { resetClientSettings(); updateClientBeforeCall(); restClient.setHttpBasicAuth(username, password); <START> Api api = restClient.loginV3(); <END> authenticator.setApiMajorVersion(api); setupVersionHeader(); String token = ""; if (!authenticator.enforceBasicAuth()) { if (isApiV3()) { setPersistentV3AuthHeaders(); restClient.setCookie(JSESSIONID, ""); restClient.loginV3(); token = restClient.getCookie(JSESSIONID); } else { resetClientSettings(); restClient.setRootUrl(authenticator.getBaseUrl()); token = restClient.loginV4(username, password).getAccessToken(); restClient.setRootUrl(authenticator.getApiUrl()); } } resetClientSettings(); return token; }</code><technical_language>@jhernand Juan, a detection of API version in order if work v3 v4. in order ask api version is, need log in (basic auth). Than, logged in, find out working new API login oauth. Im this is intended of API. Is a way? Or, more importantly, this work v3 removed? :)</technical_language>

Target:
public String login(String username, String password) { String token = ""; resetClientSettings(); setupVersionHeader(""); updateClientBeforeCall(); restClient.setRootUrl(authenticator.getBaseUrl()); try { token = restClient.loginV4(username, password).getAccessToken(); } catch (Exception x) { } restClient.setRootUrl(authenticator.getApiUrl()); boolean oldApi = StringUtils.isEmpty(token); restClient.setCookie(JSESSIONID, ""); if (oldApi) { restClient.setHttpBasicAuth(username, password); setPersistentV3AuthHeaders(); } else { restClient.setBearerAuth(token); } Api api = restClient.loginV3(); authenticator.setApiMajorVersion(api); setupVersionHeader(authenticator.getApiMajorVersion()); if (oldApi && api != null) { token = restClient.getCookie(JSESSIONID); } resetClientSettings(); return token; }
Source:
<code>protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(vmNetworkInterfaceDao.getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = vmTemplateDao.get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { vmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = DisksFilter.filterImageDisks(diskDao.getAllForVm(vm.getId()), ONLY_SNAPABLE, ONLY_ACTIVE); disks.addAll(imagesHandler.getCinderLeafImages(diskDao.getAllForVm(vm.getId()))); disks.addAll(imagesHandler.getManagedBlockStorageSnapshots(diskDao.getAllForVm(vm.getId()))); } populateDisksWithVmData(disks, vm.getId()); disks.forEach(image -> image.setStorageIds(null)); FullEntityOvfData fullEntityOvfData = new FullEntityOvfData(vm); fullEntityOvfData.setDiskImages(disks); <START> vmHandler.updateVmInitFromDB(vm.getStaticData(), true); <END> return ovfManager.exportVm(vm, fullEntityOvfData, clusterUtils.getCompatibilityVersion(vm)); }</code><technical_language>Please add a condition, VmInit is updated DB if is null. existing VmInit overridden. This needed snapshot is for VM next run</technical_language>

Target:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(vmNetworkInterfaceDao.getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = vmTemplateDao.get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { vmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = DisksFilter.filterImageDisks(diskDao.getAllForVm(vm.getId()), ONLY_SNAPABLE, ONLY_ACTIVE); disks.addAll(imagesHandler.getCinderLeafImages(diskDao.getAllForVm(vm.getId()))); disks.addAll(imagesHandler.getManagedBlockStorageSnapshots(diskDao.getAllForVm(vm.getId()))); } populateDisksWithVmData(disks, vm.getId()); disks.forEach(image -> image.setStorageIds(null)); FullEntityOvfData fullEntityOvfData = new FullEntityOvfData(vm); fullEntityOvfData.setDiskImages(disks); if (vm.getStaticData().getVmInit() == null) { vmHandler.updateVmInitFromDB(vm.getStaticData(), true); } return ovfManager.exportVm(vm, fullEntityOvfData, clusterUtils.getCompatibilityVersion(vm)); }
Source:
<code>private String getValidConfirmPatternOrThrow(String confirmPattern) { if (confirmPattern == null) { throw new IllegalArgumentException("Confirm pattern is null"); } try { Pattern.compile(confirmPattern); } catch (PatternSyntaxException ex) { throw new IllegalArgumentException("invalid " <START> + "regex provided for confirmPattern"); <END> } if (DEFAULT.equalsIgnoreCase(confirmPattern)) { set(CONFIRM_PATTERN, DEFAULT); return DEFAULT; } return confirmPattern; }</code><technical_language>sense check if confirmPattern is default of current confirmPattern first. In this case compilation is required</technical_language>

Target:
private String getValidConfirmPatternOrThrow(String confirmPattern) { if (confirmPattern == null) { throw new IllegalArgumentException("Confirm pattern is null"); } if (DEFAULT.equalsIgnoreCase(confirmPattern)) { confirmPattern = sqlLine.loc("default-confirm-pattern"); } set(CONFIRM_PATTERN, confirmPattern); try { compiledConfirmPattern = Pattern.compile(confirmPattern); } catch (PatternSyntaxException ex) { throw new IllegalArgumentException("invalid " + "regex provided for confirmPattern"); } return confirmPattern; }
Source:
<code>public Statement apply(final Statement base, final Description d) { return new Statement() { @Override public void evaluate() throws Throwable { <START> Class<?> testCase = d.getTestClass(); <END> check(d.getAnnotation(WithOS.class), testCase); check(testCase.getAnnotation(WithOS.class), testCase); base.evaluate(); } private void check(WithOS withos, Class<?> testCase) { if (withos == null) return; String errorMsg = "Test must be run on a machine running any of the following operating systems: " + Arrays.toString(withos.os()); for (OS _os : withos.os()) { switch (_os) { case LINUX: if (!SystemUtils.IS_OS_LINUX) { throw new AssumptionViolatedException(errorMsg); } break; case WINDOWS: if (!SystemUtils.IS_OS_WINDOWS) { throw new AssumptionViolatedException(errorMsg); } break; case MAC: if (!SystemUtils.IS_OS_MAC) { throw new AssumptionViolatedException(errorMsg); } break; default: break; } } } }; }</code><technical_language>Generally in JUnit this "suite", opposed method "case"</technical_language>

Target:
public Statement apply(final Statement base, final Description d) { return new Statement() { @Override public void evaluate() throws Throwable { Class<?> testSuite = d.getTestClass(); check(d.getAnnotation(WithOS.class), testSuite); check(testSuite.getAnnotation(WithOS.class), testSuite); base.evaluate(); } private void check(WithOS withos, Class<?> testCase) { if (withos == null) return; if (!(controller instanceof LocalController)) { throw new AssumptionViolatedException("Test skipped. WithOS should be used with a local controller, otherwise it cannot be fully trusted to work as expected."); } String errorMsg = "Test and Jenkins instance must be running on any of the following operating systems: " + Arrays.toString(withos.os()); for (OS _os : withos.os()) { switch (_os) { case LINUX: if (!SystemUtils.IS_OS_LINUX) { throw new AssumptionViolatedException(errorMsg); } break; case WINDOWS: if (!SystemUtils.IS_OS_WINDOWS) { throw new AssumptionViolatedException(errorMsg); } break; case MAC: if (!SystemUtils.IS_OS_MAC) { throw new AssumptionViolatedException(errorMsg); } break; default: break; } } } }; }
Source:
<code>private CompletableFuture<Void> handleDataWriteCommand(InvocationContext ctx, DataWriteCommand command, boolean assumeOriginKeptEntryInL1) throws Throwable { if (command.hasFlag(Flag.CACHE_MODE_LOCAL)) { if (trace) { log.tracef("local mode forced, suppressing L1 calls."); } return ctx.continueInvocation(); } Future<?> l1InvalidationFuture = invalidateL1InCluster(ctx, command, assumeOriginKeptEntryInL1); <START> return ctx.forkInvocation(command, (ctx1, command1, rv, throwable) -> { <END> if (throwable != null) throw throwable; processInvalidationResult(command, l1InvalidationFuture); return removeFromLocalL1(ctx, command, rv); }); }</code><technical_language>forkInvocation()? In this case, I expecting a onReturn() continueInvocation()</technical_language>

Target:
private CompletableFuture<Void> handleDataWriteCommand(InvocationContext ctx, DataWriteCommand command, boolean assumeOriginKeptEntryInL1) throws Throwable { if (command.hasFlag(Flag.CACHE_MODE_LOCAL)) { if (trace) { log.tracef("local mode forced, suppressing L1 calls."); } return ctx.continueInvocation(); } Future<?> l1InvalidationFuture = invalidateL1InCluster(ctx, command, assumeOriginKeptEntryInL1); return ctx.forkInvocation(command, (rCtx, rCommand, rv, throwable) -> { if (throwable != null) throw throwable; DataWriteCommand dataWriteCommand = (DataWriteCommand) rCommand; processInvalidationResult(dataWriteCommand, l1InvalidationFuture); return removeFromLocalL1(rCtx, dataWriteCommand, rv); }); }
Source:
<code>public BinaryResult apply(ChangeEditResource rsrc) throws ResourceNotFoundException, IOException, InvalidChangeOperationException { try { return fileContentUtil.getContent( rsrc.getChangeEdit().getChange().getProject(), rsrc.getChangeEdit().getRevision().get(), rsrc.getPath()); } catch (ResourceNotFoundException rnfe) { <START> return fileContentUtil.getContent( <END> rsrc.getChangeEdit().getChange().getProject(), rsrc.getChangeEdit().getBasePatchSet().getRevision().get(), rsrc.getPath()); } }</code><technical_language>if file is in tree of edit, fall file base patch set. This wrong. means if do DELETE /changes/X/edit/path GET /changes/X/edit/path get original contents, a 204? I this branch is covered in tests</technical_language>

Target:
public Response<?> apply(ChangeEditResource rsrc) throws ResourceNotFoundException, IOException, InvalidChangeOperationException { try { return Response.ok(fileContentUtil.getContent( rsrc.getChangeEdit().getChange().getProject(), rsrc.getChangeEdit().getRevision().get(), rsrc.getPath())); } catch (ResourceNotFoundException rnfe) { return Response.none(); } }
Source:
<code>public GlowSound getPlaceSound() { <START> return new GlowSound(Sound.DIG_WOOD); END> }</code><technical_language>easier maintain if for BlockType, a field sound, reference field here, instead of override sound methods this</technical_language>

Target:
public SoundInfo getPlaceSound() { return placeSound; }
Source:
<code>public synchronized boolean retry(ITestResult result) { if (currentTry < maxreruntimes) { <START> ++currentTry; <END> return true; } return false; }</code><technical_language>AtomicInteger get rid of synchronized keyword ? a side note, I noticed enabled parallel attribute @DataProvider annotation. completely get rid of need for ensuring Thread safety</technical_language>

Target:
public boolean retry(ITestResult result) { if (currentTry < maxreruntimes) { ++currentTry; return true; } return false; }
Source:
<code><START> public String getToken() throws NoSuchAlgorithmException { <END> createToken(); return token; }</code><technical_language>hmm. this throw exception a of handling this. this a fatal error</technical_language>

Target:
public String getToken() { createToken(); return token; }
Source:
<code>public void testCreateAnAPIThroughThePublisherRest() throws Exception { String apiContext = "apim574PublisherTestAPI"; String apiDescription = "This is Test API Created by API Manager Integration Test"; String apiTags = "tag574-1, tag574-2, tag587-3"; APICreationRequestBean apiCreationRequestBean = new APICreationRequestBean(apiNameTest, apiContext, apiVersion, apiProvider, new URL(apiEndPointUrl)); apiCreationRequestBean.setTags(apiTags); apiCreationRequestBean.setDescription(apiDescription); apiCreationRequestBean.setTiersCollection("Gold,Bronze"); apiCreationRequestBean.setDefaultVersion("default_version"); apiCreationRequestBean.setDefaultVersionChecked("default_version"); apiCreationRequestBean.setBizOwner("api574b"); apiCreationRequestBean.setBizOwnerMail("api574b@ee.com"); apiCreationRequestBean.setTechOwner("api574t"); apiCreationRequestBean.setTechOwnerMail("api574t@ww.com"); APIDTO apiCreationResponse = restAPIPublisher.addAPI(apiCreationRequestBean); String status = apiCreationResponse.getLifeCycleStatus(); apiId = apiCreationResponse.getId(); HttpResponse apiResponsePublisher = restAPIPublisher.getAPI(apiId); assertEquals(apiResponsePublisher.getResponseCode(), Response.Status.OK.getStatusCode(), apiNameTest + " is not visible in publisher"); assertTrue(apiCreationResponse.getName().equals(apiNameTest), apiNameTest + " is not visible in " + "publisher"); <START> assertTrue(status.equals("CREATED"), "Status of the " + apiNameTest + "is not a valid status"); <END> }</code><technical_language>Lets lifecycle status constant</technical_language>

Target:
public void testCreateAnAPIThroughThePublisherRest() throws Exception { String apiContext = "apim574PublisherTestAPI"; String apiDescription = "This is Test API Created by API Manager Integration Test"; String apiTags = "tag574-1, tag574-2, tag587-3"; APICreationRequestBean apiCreationRequestBean = new APICreationRequestBean(apiNameTest, apiContext, apiVersion, apiProvider, new URL(apiEndPointUrl)); apiCreationRequestBean.setTags(apiTags); apiCreationRequestBean.setDescription(apiDescription); apiCreationRequestBean.setTiersCollection("Gold,Bronze"); apiCreationRequestBean.setDefaultVersion("default_version"); apiCreationRequestBean.setDefaultVersionChecked("default_version"); apiCreationRequestBean.setBizOwner("api574b"); apiCreationRequestBean.setBizOwnerMail("api574b@ee.com"); apiCreationRequestBean.setTechOwner("api574t"); apiCreationRequestBean.setTechOwnerMail("api574t@ww.com"); APIDTO apiCreationResponse = restAPIPublisher.addAPI(apiCreationRequestBean); String status = apiCreationResponse.getLifeCycleStatus(); apiId = apiCreationResponse.getId(); HttpResponse apiResponsePublisher = restAPIPublisher.getAPI(apiId); assertEquals(apiResponsePublisher.getResponseCode(), Response.Status.OK.getStatusCode(), apiNameTest + " is not visible in publisher"); assertTrue(apiNameTest.equals(apiCreationResponse.getName()), apiNameTest + " is not visible in publisher"); assertTrue(APILifeCycleState.CREATED.getState().equalsIgnoreCase(status), "Status of the " + apiNameTest + "is not a valid status"); }
Source:
<code>public CacheStatistics getStatistics(String scope) { <START> return CacheStatistics.EMPTY; <END> }</code><technical_language>return size in case of MapCacheStoreAdapter</technical_language>

Target:
public CacheStatistics getStatistics(String scope) { return new CacheStatistics(getScopeCache(scope).size()); }
Source:
<code>public E get(long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException { if (timeout < 0 || timeUnit == null) { throw new IllegalArgumentException("Invalid timeout or timeUnit for MessageFuture.get()"); } long remainingTimeoutNanos = timeUnit.toNanos(timeout); synchronized (this) { while (NO_RESULT.equals(result) && remainingTimeoutNanos > 0) { long started = System.nanoTime(); <START> wait(TimeUnit.NANOSECONDS.toMillis(remainingTimeoutNanos)); <END> remainingTimeoutNanos -= System.nanoTime() - started; } if (NO_RESULT.equals(result)) { throw new TimeoutException(format("Timeout while executing message, total timeout: %d ms", timeUnit.toMillis(timeout))); } if (result instanceof Throwable) { throw new ExecutionException((Throwable) result); } return result; } }</code><technical_language>this lead 0 due rounding errors -> wait() treat indefinite timeout</technical_language>

Target:
public E get(long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException { if (timeout < 0 || timeUnit == null) { throw new IllegalArgumentException("Invalid timeout or timeUnit for MessageFuture.get()"); } long remainingTimeoutNanos = timeUnit.toNanos(timeout); synchronized (this) { while (NO_RESULT.equals(result) && remainingTimeoutNanos > ONE_MILLISECOND) { long started = System.nanoTime(); wait(TimeUnit.NANOSECONDS.toMillis(remainingTimeoutNanos)); remainingTimeoutNanos -= System.nanoTime() - started; } E tmpResult = result; if (NO_RESULT.equals(tmpResult)) { throw new TimeoutException(format("Timeout while waiting for message (%d ms)", timeUnit.toMillis(timeout))); } if (tmpResult instanceof Throwable) { throw new ExecutionException((Throwable) tmpResult); } futureMap.remove(key); return tmpResult; } }
Source:
<code>public boolean handles(String source) { <START> return source.equals("github"); <END> }</code><technical_language>change this sort of check "github".equals(source) this inversion avoid NPE in case source is null</technical_language>

Target:
public boolean handles(String source) { return "github".equals(source); }
Source:
<code>public void addChangeListener_shouldAddTheObjectToHandlerRealmObjects() { looperThread.realm.beginTransaction(); AllTypesPrimaryKey allTypesPrimaryKey = looperThread.realm.createObject(AllTypesPrimaryKey.class, 1); looperThread.realm.commitTransaction(); <START> assertTrue(looperThread.realm.handlerController.realmObjects.isEmpty()); <END> allTypesPrimaryKey.addChangeListener(new RealmChangeListener<RealmModel>() { @Override public void onChange(RealmModel element) { } }); assertEquals(1, looperThread.realm.handlerController.realmObjects.size()); for (WeakReference<RealmObjectProxy> ref : looperThread.realm.handlerController.realmObjects.keySet()) { assertTrue(ref.get() == allTypesPrimaryKey); } looperThread.testComplete(); }</code><technical_language>pull realm.handlerController.realmObjects variable is a number of times</technical_language>

Target:
public void addChangeListener_shouldAddTheObjectToHandlerRealmObjects() { realm.beginTransaction(); AllTypesPrimaryKey allTypesPrimaryKey = realm.createObject(AllTypesPrimaryKey.class, 1); realm.commitTransaction(); final Map<WeakReference<RealmObjectProxy>, RealmQuery<? extends RealmModel>> realmObjects = realm.handlerController.realmObjects; assertTrue(realmObjects.isEmpty()); allTypesPrimaryKey.addChangeListener(new RealmChangeListener<AllTypesPrimaryKey>() { @Override public void onChange(AllTypesPrimaryKey element) { } }); assertEquals(1, realmObjects.size()); for (WeakReference<RealmObjectProxy> ref : realmObjects.keySet()) { assertTrue(ref.get() == allTypesPrimaryKey); } }
Source:
<code>private Set<String> validateJobHostName(final String hostname) { final Set<String> errors = Sets.newHashSet(); <START> if (hostname == null || hostname.isEmpty()) { <END> return errors; } if (!HOSTNAME_PATTERN.matcher(hostname).matches()) { errors.add( format("Invalid hostname (%s), only [a-z0-9][a-z0-9-] are allowed, size between 1 and 63", hostname)); } return errors; }</code><technical_language>Nitpick: Strings.isNullOrEmpty() do rest of code</technical_language>

Target:
private Set<String> validateJobHostName(final String hostname) { final Set<String> errors = Sets.newHashSet(); if (isNullOrEmpty(hostname)) { return errors; } if (!HOSTNAME_PATTERN.matcher(hostname).matches()) { errors.add( format("Invalid hostname (%s), only [a-z0-9][a-z0-9-] are allowed, size between 1 and 63", hostname)); } return errors; }
Source:
<code>boolean isValidVersion(WorkflowVersion version) { SortedSet<VersionValidation> versionValidations = version.getValidations(); boolean isValid = true; <START> for (VersionValidation versionValidation : versionValidations) { <END> if (!versionValidation.isValid()) { isValid = false; break; } } return isValid; }</code><technical_language>Trivial lambda</technical_language>

Target:
public boolean isValidVersion(WorkflowVersion version) { return !version.getValidations().stream().filter(versionValidation -> !versionValidation.isValid()).findFirst().isPresent(); }
Source:
<code>private void initCe() { processingScheduler.startScheduling(); cleaningScheduler.startScheduling(); <START> ceDistributedInformation.broadcastWorkerUUIDs(); <END> }</code><technical_language>put this right starting CE worker processes is need wait for cleaning process broadcasting worker uuids soon is important</technical_language>

Target:
private void initCe() { ceDistributedInformation.broadcastWorkerUUIDs(); processingScheduler.startScheduling(); cleaningScheduler.startScheduling(); }
Source:
<code>public void updateMapping(FriendlyCodeVO vo) { Connection conn = null; try { conn = this.getConnection(); conn.setAutoCommit(false); <START> this.deleteRecord(vo.getFriendlyCode(), null, null, conn); <END> this.addRecord(vo, conn); conn.commit(); } catch (Throwable t) { this.executeRollback(conn); _logger.error("Error update the mapping", t); throw new RuntimeException("Error update the mapping", t); } finally { this.closeConnection(conn); } }</code><technical_language>is this safe? method signature changed? records in DB? Do need a migration script</technical_language>

Target:
public void updateMapping(FriendlyCodeVO vo) { Connection conn = null; try { conn = this.getConnection(); conn.setAutoCommit(false); super.executeQueryWithoutResultset(conn, DELETE_FROM_FRIENDLYCODE, vo.getFriendlyCode()); this.addRecord(vo, conn); conn.commit(); } catch (Throwable t) { this.executeRollback(conn); _logger.error("Error update the mapping", t); throw new RuntimeException("Error update the mapping", t); } finally { this.closeConnection(conn); } }
Source:
<code>public void sortElements(String envVar, String criteria, String order) { String value = ThreadProperty.get(envVar); JsonArray jsonArr = JsonValue.readHjson(value).asArray(); List<JsonValue> jsonValues = new ArrayList<JsonValue>(); for (int i = 0; i < jsonArr.size(); i++) { jsonValues.add(jsonArr.get(i)); } Comparator<JsonValue> comparator; switch (criteria) { <START> case "alphabtical": <END> commonspec.getLogger().debug("Alphabetic criteria selected."); comparator = new Comparator<JsonValue>() { public int compare(JsonValue json1, JsonValue json2) { int res = String.CASE_INSENSITIVE_ORDER.compare(json1.toString(), json2.toString()); if (res == 0) { res = json1.toString().compareTo(json2.toString()); } return res; } }; break; default: commonspec.getLogger().debug("No criteria selected."); comparator = null; } if ("ascending".equals(order)) { Collections.sort(jsonValues,comparator); } else { Collections.sort(jsonValues,comparator.reversed()); } ThreadProperty.set(envVar,jsonValues.toString()); }</code><technical_language>This a typo</technical_language>

Target:
public void sortElements(String envVar, String criteria, String order) { String value = ThreadProperty.get(envVar); JsonArray jsonArr = JsonValue.readHjson(value).asArray(); List<JsonValue> jsonValues = new ArrayList<JsonValue>(); for (int i = 0; i < jsonArr.size(); i++) { jsonValues.add(jsonArr.get(i)); } Comparator<JsonValue> comparator; switch (criteria) { case "alphabetical": commonspec.getLogger().debug("Alphabetical criteria selected."); comparator = new Comparator<JsonValue>() { public int compare(JsonValue json1, JsonValue json2) { int res = String.CASE_INSENSITIVE_ORDER.compare(json1.toString(), json2.toString()); if (res == 0) { res = json1.toString().compareTo(json2.toString()); } return res; } }; break; default: commonspec.getLogger().debug("No criteria selected."); comparator = null; } if ("ascending".equals(order)) { Collections.sort(jsonValues,comparator); } else { Collections.sort(jsonValues,comparator.reversed()); } ThreadProperty.set(envVar,jsonValues.toString()); }