auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void onBreedFeed(EntityPlayer player, EnumHand hand, CallbackInfoReturnable<Boolean> cir, ItemStack itemStack) { SpongeImpl.postEvent(SpongeEventFactory.createFeedAnimalEventLove(Cause.of(NamedCause.source(player)), Optional.of(this.getLocation()), itemStack.createSnapshot(), this)); }

Target:
private void onBreedFeed(EntityPlayer player, EnumHand hand, CallbackInfoReturnable<Boolean> cir, ItemStack itemStack) { Sponge.getCauseStackManager().pushCause(player); FeedAnimalEvent.Love event = SpongeEventFactory.createFeedAnimalEventLove(Sponge.getCauseStackManager().getCurrentCause(), Optional.of(this.getLocation()), ((org.spongepowered.api.item.inventory.ItemStack) itemStack).createSnapshot(), this); if (SpongeImpl.postEvent(event)) { cir.setReturnValue(true); } Sponge.getCauseStackManager().popCause(); }
Source:
public void performEngineNicsHealthCheck() { List<NetworkInterface> nicsToCheck = networkInterfacesToCheck(); log.debug("Performing engine NICs health check on: " + StringUtils.join(toNicsDisplayNames(nicsToCheck), ", ")); checkNicsAndUpdateEngineStatus(nicsToCheck); log.debug("Health check done, engine NICs are {}.", engineNicHealthCache.isAllNicHealthy() ? "healthy" : "unhealthy"); }

Target:
public void performEngineNicsHealthCheck() { List<NetworkInterface> nicsToCheck = networkInterfacesToCheck(); log.debug("Performing engine NICs health check on: {}", StringUtils.join(toNicsDisplayNames(nicsToCheck), ", ")); checkNicsAndUpdateEngineStatus(nicsToCheck); log.debug("Health check done, engine NICs are {}.", engineNicHealthCache.isAllNicHealthy() ? "healthy" : "unhealthy"); }
Source:
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getStatus() != VDSStatus.Down) { long timeoutToFence = calcTimeoutToFence(vds.getVmCount(), vds.getSpmStatus()); if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) || (lastUpdate + timeoutToFence) > System.currentTimeMillis()) { boolean result = false; if (vds.getStatus() != VDSStatus.Connecting && vds.getStatus() != VDSStatus.PreparingForMaintenance && vds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getStatus() == VDSStatus.NonResponsive || vds.getStatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.infoFormat( "Server failed to respond, vds_id = {0}, vds_name = {1}, vm_count = {2}, " + "spm_status = {3}, non-responsive_timeout (seconds) = {4}, error = {5}", vds.getId(), vds.getName(), vds.getVmCount(), vds.getSpmStatus(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); boolean executeSshSoftFencing = false; if (!sshSoftFencingExecuted.getAndSet(true)) { executeSshSoftFencing = true; } ResourceManager.getInstance().getEventListener().vdsNotResponding(vds, executeSshSoftFencing); } return true; }

Target:
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getStatus() != VDSStatus.Down) { long timeoutToFence = calcTimeoutToFence(vds.getVmCount(), vds.getSpmStatus()); if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) || (lastUpdate + timeoutToFence) > System.currentTimeMillis()) { boolean result = false; if (vds.getStatus() != VDSStatus.Connecting && vds.getStatus() != VDSStatus.PreparingForMaintenance && vds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getStatus() == VDSStatus.NonResponsive || vds.getStatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.infoFormat( "Server failed to respond, vds_id = {0}, vds_name = {1}, vm_count = {2}, " + "spm_status = {3}, non-responsive_timeout (seconds) = {4}, error = {5}", vds.getId(), vds.getName(), vds.getVmCount(), vds.getSpmStatus(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); logable.updateCallStackFromThrowable(ex); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); boolean executeSshSoftFencing = false; if (!sshSoftFencingExecuted.getAndSet(true)) { executeSshSoftFencing = true; } ResourceManager.getInstance().getEventListener().vdsNotResponding(vds, executeSshSoftFencing); } return true; }
Source:
public String getUUID() { String uuid = EntityPlayer.getUUID(player.getGameProfile()).toString().toLowerCase(); if (uuid != null && !uuid.equals("")) return uuid; return EntityPlayer.getOfflineUUID(player.getName()).toString().toLowerCase(); }

Target:
public String getUUID() { UUID uuid = null; if (player.getGameProfile() != null) { uuid = EntityPlayer.getUUID(player.getGameProfile()); } if(uuid == null) { uuid = EntityPlayer.getOfflineUUID(getName()); } if(uuid == null) { CraftTweakerAPI.logError("Could not get UUID for player " + getName()); return ""; } return uuid.toString().toLowerCase(); }
Source:
protected String getKey(String name) { return null; }

Target:
protected String getKey(String name) { return Encryptor.hash(name + "W00h00t!11", name + "G@nd01f"); }
Source:
public boolean isExtensionLoaded(String classname) { getLoadedExtensions(); getLoadedExtensionsWithDeps(); for (Extension extension : getLoadedExtensions()) { if (classname.equals(extension.getClass().getCanonicalName())) { return true; } } return false; }

Target:
public boolean isExtensionLoaded(String classname) { for (Extension extension : getLoadedExtensions()) { if (classname.equals(extension.getClass().getCanonicalName())) { return true; } } return false; }
Source:
public Runnable getWrappedRunnable() { return get(); }

Target:
public Runnable getWrappedRunnable() { Runnable r = get(); return r != null ? r : Functions.EMPTY_RUNNABLE; }
Source:
private void deleteOldPacks(Collection<PackFile> oldPacks, Collection<PackFile> newPacks) throws ParseException, IOException { final HashSet<ObjectId> ids = new HashSet<>(); for (PackFile pack : newPacks) { for (PackIndex.MutableEntry entry : pack) { ids.add(entry.toObjectId()); } } final ObjectReader reader = repo.newObjectReader(); final ObjectDirectory dir = repo.getObjectDatabase(); final ObjectDirectoryInserter inserter = dir.newInserter(); final boolean shouldLoosen = getExpireDate() < Long.MAX_VALUE; prunePreserved(); long packExpireDate = getPackExpireDate(); oldPackLoop: for (PackFile oldPack : oldPacks) { String oldName = oldPack.getPackName(); for (PackFile newPack : newPacks) if (oldName.equals(newPack.getPackName())) continue oldPackLoop; if (!oldPack.shouldBeKept() && repo.getFS().lastModified( oldPack.getPackFile()) < packExpireDate) { oldPack.close(); if (shouldLoosen) { loosen(inserter, reader, oldPack, ids); } prunePack(oldName); } } repo.getObjectDatabase().close(); }

Target:
private void deleteOldPacks(Collection<PackFile> oldPacks, Collection<PackFile> newPacks) throws ParseException, IOException { HashSet<ObjectId> ids = new HashSet<>(); for (PackFile pack : newPacks) { for (PackIndex.MutableEntry entry : pack) { ids.add(entry.toObjectId()); } } ObjectReader reader = repo.newObjectReader(); ObjectDirectory dir = repo.getObjectDatabase(); ObjectDirectoryInserter inserter = dir.newInserter(); boolean shouldLoosen = getExpireDate() < Long.MAX_VALUE; prunePreserved(); long packExpireDate = getPackExpireDate(); oldPackLoop: for (PackFile oldPack : oldPacks) { String oldName = oldPack.getPackName(); for (PackFile newPack : newPacks) if (oldName.equals(newPack.getPackName())) continue oldPackLoop; if (!oldPack.shouldBeKept() && repo.getFS().lastModified( oldPack.getPackFile()) < packExpireDate) { oldPack.close(); if (shouldLoosen) { loosen(inserter, reader, oldPack, ids); } prunePack(oldName); } } repo.getObjectDatabase().close(); }
Source:
public void init(FMLInitializationEvent event) { if (DISABLED) return; try { TestEnum.class.getDeclaredMethod("$$newInstance", String.class, int.class); } catch (NoSuchMethodException e){ throw new Error("$$newInstance method not present", e); } for (int i = 1; i <= 10000; i++) { EnumHelper.addEnum(TestEnum.class, "V_" + i, EMPTY_CLASSES, EMPTY_ARGS); TestEnum.values(); } TestEnum[] arr = TestEnum.values(); last = arr[arr.length - 1]; if (!last.name().equals("V_10000")) throw new Error("The enum values field was incorrectly inlined!"); LogManager.getLogger(EnumValuesInlineTest.class).info("EnumValuesInlineTest completed successfully."); }

Target:
public void init(FMLInitializationEvent event) { if (DISABLED) return; try { TestEnum.class.getDeclaredMethod("$$newInstance", String.class, int.class); } catch (NoSuchMethodException e){ throw new Error("$$newInstance method not present", e); } for (int i = 1; i <= 10000; i++) { EnumHelper.addEnum(TestEnum.class, "V_" + i, EMPTY_CLASSES, EMPTY_ARGS); TestEnum.values(); } TestEnum[] arr = TestEnum.values(); last = arr[arr.length - 1]; if (!last.name().equals("V_10000")) throw new Error("The enum values field was incorrectly inlined!"); LogManager.getLogger(MOD_ID).info("EnumValuesInlineTest completed successfully."); }
Source:
@Override public void handleClick(MonthCellDescriptor cell) { if (!betweenDates(cell.getDate(), minCal, maxCal)) { String errMessage = getResources().getString(R.string.invalid_date, fullDateFormat.format(minCal.getTime()), fullDateFormat.format(maxCal.getTime())); Toast.makeText(getContext(), errMessage, Toast.LENGTH_SHORT).show(); } else { selectedCell.setSelected(false); selectedCell = cell; selectedCell.setSelected(true); selectedCal.setTime(cell.getDate()); adapter.notifyDataSetChanged(); if(mOnDateSelectedListener != null) mOnDateSelectedListener.onDateSelected(cell.getDate()); } }

Target:
@Override public void handleClick(MonthCellDescriptor cell) { if (!betweenDates(cell.getDate(), minCal, maxCal)) { String errMessage = getResources().getString(R.string.invalid_date, fullDateFormat.format(minCal.getTime()), fullDateFormat.format(maxCal.getTime())); Toast.makeText(getContext(), errMessage, Toast.LENGTH_SHORT).show(); } else { selectedCell.setSelected(false); selectedCell = cell; selectedCell.setSelected(true); selectedCal.setTime(cell.getDate()); adapter.notifyDataSetChanged(); if (dateListener != null) { dateListener.onDateSelected(cell.getDate()); } } }
Source:
String[] getValueAsStringArray(Object value) { if (value instanceof String) { LOGGER.trace("requestMap value '" + value + "'"); return new String[] { value.toString() }; } else if (value instanceof String[]) { LOGGER.trace("requestMap value '" + Arrays.toString((String[]) value) + "'"); return (String[]) value; } else { throw new IllegalArgumentException("Invalid requestMap value type"); } }

Target:
String[] getValueAsStringArray(Object value) { if (value instanceof String) { LOGGER.trace("requestMap value '" + value + "'"); return new String[] { value.toString() }; } else if (value instanceof String[]) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("requestMap value '" + Arrays.toString((String[]) value) + "'"); } return (String[]) value; } else { throw new IllegalArgumentException("Invalid requestMap value type"); } }
Source:
public final List<IElkProgressMonitor> getSubMonitors() { return children; }

Target:
public final List<IElkProgressMonitor> getSubMonitors() { return Collections.unmodifiableList(children); }
Source:
public void commitKey(OmKeyArgs args, long clientID) throws IOException { Preconditions.checkNotNull(args); String volumeName = args.getVolumeName(); String bucketName = args.getBucketName(); String keyName = args.getKeyName(); List<OmKeyLocationInfo> locationInfoList = args.getLocationInfoList(); String objectKey = metadataManager .getOzoneKey(volumeName, bucketName, keyName); String openKey = metadataManager .getOpenKey(volumeName, bucketName, keyName, clientID); Preconditions.checkNotNull(locationInfoList); try { metadataManager.getLock().acquireBucketLock(volumeName, bucketName); validateBucket(volumeName, bucketName); OmKeyInfo keyInfo = metadataManager.getOpenKeyTable().get(openKey); if (keyInfo == null) { throw new OMException("Commit a key without corresponding entry " + openKey, KEY_NOT_FOUND); } keyInfo.setDataSize(args.getDataSize()); keyInfo.setModificationTime(Time.now()); keyInfo.updateLocationInfoList(locationInfoList); metadataManager.getStore().move( openKey, objectKey, keyInfo, metadataManager.getOpenKeyTable(), metadataManager.getKeyTable()); } catch (OMException e) { throw e; } catch (IOException ex) { LOG.error("Key commit failed for volume:{} bucket:{} key:{}", volumeName, bucketName, keyName, ex); throw new OMException(ex.getMessage(), ResultCodes.KEY_ALLOCATION_ERROR); } finally { metadataManager.getLock().releaseBucketLock(volumeName, bucketName); } }

Target:
public void commitKey(OmKeyArgs args, long clientID) throws IOException { Preconditions.checkNotNull(args); String volumeName = args.getVolumeName(); String bucketName = args.getBucketName(); String keyName = args.getKeyName(); List<OmKeyLocationInfo> locationInfoList = args.getLocationInfoList(); String objectKey = metadataManager .getOzoneKey(volumeName, bucketName, keyName); String openKey = metadataManager .getOpenKey(volumeName, bucketName, keyName, clientID); Preconditions.checkNotNull(locationInfoList); try { metadataManager.getLock().acquireBucketLock(volumeName, bucketName); validateBucket(volumeName, bucketName); OmKeyInfo keyInfo = metadataManager.getOpenKeyTable().get(openKey); if (keyInfo == null) { throw new OMException("Failed to commit key, as " + openKey + "entry " + "is not found in the openKey table", KEY_NOT_FOUND); } keyInfo.setDataSize(args.getDataSize()); keyInfo.setModificationTime(Time.now()); keyInfo.updateLocationInfoList(locationInfoList); metadataManager.getStore().move( openKey, objectKey, keyInfo, metadataManager.getOpenKeyTable(), metadataManager.getKeyTable()); } catch (OMException e) { throw e; } catch (IOException ex) { LOG.error("Key commit failed for volume:{} bucket:{} key:{}", volumeName, bucketName, keyName, ex); throw new OMException(ex.getMessage(), ResultCodes.KEY_ALLOCATION_ERROR); } finally { metadataManager.getLock().releaseBucketLock(volumeName, bucketName); } }
Source:
public void incrementWarnings() { this.warning++; if (warning >= 2) { this.player.getWorld().strikeLightning(this.player.getLocation()); this.player.sendMessage(ChatColor.RED + "You have been warned at least twice now, make sure to read the rules at <LINK_0>"); } }

Target:
public void incrementWarnings() { this.warningCount++; if (this.warningCount % 2 == 0) { this.player.getWorld().strikeLightning(this.player.getLocation()); TFM_Util.playerMsg(this.player, ChatColor.RED + "You have been warned at least twice now, make sure to read the rules at " + TFM_ConfigEntry.SERVER_BAN_URL.getString()); } }
Source:
public int hashCode() { return Objects.hashCode( account, firstName, lastName, company, address1, address2, city, state, zip, country, phone, vatNumber, ipAddress, ipAddressCountry, cardType, year, month, firstSix, lastFour, updatedAt ); }

Target:
public int hashCode() { return Objects.hashCode( account, firstName, lastName, company, address1, address2, city, state, zip, country, phone, vatNumber, ipAddress, ipAddressCountry, cardType, year, month, firstSix, lastFour, updatedAt, geoCode ); }
Source:
public int getInt(String key) throws NumberFormatException { String setting = items.get(key); if (setting == null) { throw new NumberFormatException( "There is no setting associated with the key \"" + key + "\""); } return Integer.valueOf(setting).intValue(); }

Target:
public int getInt(String key) throws NumberFormatException { String setting = items.get(key); if (setting == null) { throw new NumberFormatException( "There is no setting associated with the key \"" + key + "\""); } return Integer.parseInt(setting); }
Source:
protected ITmfTreeColumnDataProvider getColumnDataProvider() { return () -> ImmutableList.of( createTmfTreeColumnData(Messages.SegmentStoreStatistics_LevelLabel, Comparator.comparing(TmfGenericTreeEntry::getName)), createTmfTreeColumnData(Messages.SegmentStoreStatistics_Statistics_MinLabel, Comparator.comparingLong(s -> s.getModel().getMin())), createTmfTreeColumnData(Messages.SegmentStoreStatistics_MaxLabel, Comparator.comparingLong(s -> s.getModel().getMax())), createTmfTreeColumnData(Messages.SegmentStoreStatistics_AverageLabel, Comparator.comparingDouble(s -> s.getModel().getMean())), createTmfTreeColumnData(Messages.SegmentStoreStatisticsViewer_StandardDeviation, Comparator.comparingDouble(s -> s.getModel().getStdDev())), createTmfTreeColumnData(Messages.SegmentStoreStatisticsViewer_Count, Comparator.comparingLong(s -> s.getModel().getNbElements())), createTmfTreeColumnData(Messages.SegmentStoreStatisticsViewer_Total, Comparator.comparingDouble(s -> s.getModel().getTotal())), new TmfTreeColumnData("")); }

Target:
protected ITmfTreeColumnDataProvider getColumnDataProvider() { return () -> ImmutableList.of( createTmfTreeColumnData(Messages.SegmentStoreStatistics_LevelLabel, Comparator.comparing(TmfTreeViewerEntry::getName)), createTmfTreeColumnData(Messages.SegmentStoreStatistics_Statistics_MinLabel, Comparator.comparing(keyExtractor(IStatistics<ISegment>::getMin, SegmentStoreStatisticsModel::getMin))), createTmfTreeColumnData(Messages.SegmentStoreStatistics_MaxLabel, Comparator.comparing(keyExtractor(IStatistics<ISegment>::getMax, SegmentStoreStatisticsModel::getMax))), createTmfTreeColumnData(Messages.SegmentStoreStatistics_AverageLabel, Comparator.comparing(keyExtractor(IStatistics<ISegment>::getMean, SegmentStoreStatisticsModel::getMean))), createTmfTreeColumnData(Messages.SegmentStoreStatisticsViewer_StandardDeviation, Comparator.comparing(keyExtractor(IStatistics<ISegment>::getStdDev, SegmentStoreStatisticsModel::getStdDev))), createTmfTreeColumnData(Messages.SegmentStoreStatisticsViewer_Count, Comparator.comparing(keyExtractor(IStatistics<ISegment>::getNbElements, SegmentStoreStatisticsModel::getNbElements))), createTmfTreeColumnData(Messages.SegmentStoreStatisticsViewer_Total, Comparator.comparing(keyExtractor(IStatistics<ISegment>::getTotal, SegmentStoreStatisticsModel::getTotal))), new TmfTreeColumnData("")); }
Source:
public Session load(String id) throws ClassNotFoundException, IOException { File file = file(id); if (file == null) { return null; } if (!file.exists()) { return null; } Context context = getManager().getContext(); Log contextLog = context.getLogger(); if (contextLog.isDebugEnabled()) { contextLog.debug(sm.getString(getStoreName()+".loading", id, file.getAbsolutePath())); } ClassLoader oldThreadContextCL = context.bind(Globals.IS_SECURITY_ENABLED, null); try (FileInputStream fis = new FileInputStream(file.getAbsolutePath()); ObjectInputStream ois = getObjectInputStream(fis)) { StandardSession session = (StandardSession) manager.createEmptySession(); session.readObjectData(ois); session.setManager(manager); return session; } catch (FileNotFoundException e) { if (contextLog.isDebugEnabled()) { contextLog.debug("No persisted data file found"); } return null; } finally { context.unbind(Globals.IS_SECURITY_ENABLED, oldThreadContextCL); } }

Target:
public Session load(String id) throws ClassNotFoundException, IOException { File file = file(id); if (file == null || !file.exists()) { return null; } Context context = getManager().getContext(); Log contextLog = context.getLogger(); if (contextLog.isDebugEnabled()) { contextLog.debug(sm.getString(getStoreName()+".loading", id, file.getAbsolutePath())); } ClassLoader oldThreadContextCL = context.bind(Globals.IS_SECURITY_ENABLED, null); try (FileInputStream fis = new FileInputStream(file.getAbsolutePath()); ObjectInputStream ois = getObjectInputStream(fis)) { StandardSession session = (StandardSession) manager.createEmptySession(); session.readObjectData(ois); session.setManager(manager); return session; } catch (FileNotFoundException e) { if (contextLog.isDebugEnabled()) { contextLog.debug("No persisted data file found"); } return null; } finally { context.unbind(Globals.IS_SECURITY_ENABLED, oldThreadContextCL); } }
Source:
protected MemoryDataView() { if (!(this instanceof DataContainer)) { throw new IllegalStateException( "Cannot construct a root MemoryDataView without a " + "container!"); } this.path = new DataQuery(); this.parent = this; this.container = (DataContainer) this; }

Target:
protected MemoryDataView() { checkState(this instanceof DataContainer,"Cannot construct a root MemoryDataView without a container!"); this.path = new DataQuery(); this.parent = this; this.container = (DataContainer) this; }
Source:
private void validateEmailBuilderConfig() { for (int i = 0; i < mProviders.size(); i++) { IdpConfig config = mProviders.get(i); if (config.getProviderId().equals(EMAIL_LINK_PROVIDER)) { if (!config.getParams().containsKey(ExtraConstants.FORCE_SAME_DEVICE)) { throw new IllegalStateException("You must force the same device flow " + "when using email link sign in with anonymous user upgrade"); } } } }

Target:
private void validateEmailBuilderConfig() { for (int i = 0; i < mProviders.size(); i++) { IdpConfig config = mProviders.get(i); if (config.getProviderId().equals(EMAIL_LINK_PROVIDER)) { boolean emailLinkForceSameDevice = config.getParams().getBoolean(ExtraConstants.FORCE_SAME_DEVICE, true); if (!emailLinkForceSameDevice) { throw new IllegalStateException("You must force the same device flow " + "when using email link sign in with anonymous user upgrade"); } } } }
Source:
private static void applyNonOverridableOptions(Configuration configuration) { configuration.setInt("mapred.map.max.attempts", 1); configuration.setBoolean("mapred.map.tasks.speculative.execution", false); configuration.setBoolean("mapreduce.map.speculative", false); configuration.setBoolean("mapreduce.task.classpath.user.precedence", true); configuration.setInt("mapreduce.task.timeout", 0); }

Target:
private static void applyNonOverridableOptions(Configuration configuration) { configuration.setInt("mapred.map.max.attempts", 1); configuration.setBoolean("mapred.map.tasks.speculative.execution", false); configuration.setBoolean("mapreduce.map.speculative", false); configuration.setBoolean("mapreduce.task.classpath.user.precedence", true); }
Source:
public void setUpdateMode(boolean enabled) { if (this.field.isShowLabel()) { TextView label = findViewById(R.id.liferay_ddm_label); if (label != null) { label.setEnabled(enabled); } } List<Option> availableOptions = field.getAvailableOptions(); if (availableOptions != null) { for (Option opt : availableOptions) { CompoundButton compoundButton = findViewWithTag(opt); compoundButton.setEnabled(enabled); } } setEnabled(enabled); }

Target:
public void setUpdateMode(boolean enabled) { if (this.field.isShowLabel()) { TextView label = findViewById(R.id.liferay_ddm_label); AndroidUtil.updateViewState(label, enabled); } List<Option> availableOptions = field.getAvailableOptions(); if (availableOptions != null) { for (Option opt : availableOptions) { CompoundButton compoundButton = findViewWithTag(opt); compoundButton.setEnabled(enabled); } } setEnabled(enabled); }
Source:
public void gracefulShutdown(ContextClosedEvent evt) { WebServer container = serverHolder().get(); LOG.debug("Received application context closed event {}. Shutting down...", evt); LOG.info("Early shutdown of Jetty connectors on {}", container); if (container != null) { if(shouldSleepBeforeShutdown) { LOG.info("Application config requesting sleep for "+sleepDurationMillisBeforeShutdown+" ms before jetty shutdown"); try { LOG.info("Sleeping for "+sleepDurationMillisBeforeShutdown+" ms before jetty shutdown"); Thread.sleep(sleepDurationMillisBeforeShutdown); } catch (InterruptedException e) { LOG.error("Failed to sleep before shutdown "+e.getMessage() ); } } container.stop(); LOG.info("Jetty is stopped."); } else { LOG.warn("Never got a Jetty?"); } }

Target:
public void gracefulShutdown(ContextClosedEvent evt) { WebServer container = serverHolder().get(); LOG.debug("Received application context closed event {}. Shutting down...", evt); LOG.info("Early shutdown of Jetty connectors on {}", container); if (container != null) { if(shouldSleepBeforeShutdown) { long sleepDurationMillisBeforeShutdown = sleepDurationBeforeShutdown.toMillis(); LOG.info("Application config requesting sleep for ms before Jetty shutdown", sleepDurationMillisBeforeShutdown); sleepBeforeJettyShutdown(sleepDurationMillisBeforeShutdown); } container.stop(); LOG.info("Jetty is stopped."); } else { LOG.warn("Never got a Jetty?"); } }
Source:
public Map<String, Collection<String>> toMap() { Map<String, Collection<String>> params = new HashMap<String, Collection<String>>(); if (null != location) { ArrayList<String> valueList = new ArrayList<String>(); valueList.add(location); params.put("location", valueList); } if (p2p) { ArrayList<String> valueList = new ArrayList<String>(); valueList.add("enabled"); params.put("p2p.preference", valueList); } return params; }

Target:
public Map<String, Collection<String>> toMap() { Map<String, Collection<String>> params = new HashMap<String, Collection<String>>(); if (null != location) { ArrayList<String> valueList = new ArrayList<String>(); valueList.add(location); params.put("location", valueList); } ArrayList<String> valueList = new ArrayList<String>(); valueList.add(mediaMode.toString()); params.put("p2p.preference", valueList); return params; }
Source:
private String getDefaultCidr(ClaudiaData claudiaData, String region) throws InvalidEntityException, AlreadyExistsEntityException, InfrastructureException { int cidrOpenstack = 1; if (!(claudiaData.getVdc() == null || claudiaData.getVdc().isEmpty())) { cidrOpenstack = getNumberDeployedNetwork(claudiaData, region) + 1; } return "10.1." + cidrOpenstack + ".0/24"; }

Target:
public String getDefaultCidr(ClaudiaData claudiaData, String region) throws InvalidEntityException, AlreadyExistsEntityException, InfrastructureException { int subNetElement = 1; int cidrOpenstack = 0; if (!(claudiaData.getVdc() == null || claudiaData.getVdc().isEmpty())) { cidrOpenstack = getNumberDeployedNetwork(claudiaData, region) + 1; } if (cidrOpenstack > MAX_NETWORK) { NET_ELEMENT += 1; subNetElement = cidrOpenstack / NET_ELEMENT; } else { subNetElement = cidrOpenstack; } return getValidCidr (claudiaData, region, subNetElement); }
Source:
protected void bindInternal(@NonNull final CompositeDisposable s) { s.add(viewModel.getRepositories() .observeOn(AndroidSchedulers.mainThread()) .subscribe(view::setRepositories)); s.add(viewModel.getNetworkRequestStatusText() .observeOn(AndroidSchedulers.mainThread()) .subscribe(view::setNetworkRequestStatus)); s.add(view.searchStringObservable .observeOn(AndroidSchedulers.mainThread()) .subscribe(viewModel::setSearchString)); s.add(Observable.create( emitter -> { view.repositoriesAdapter.setOnClickListener(this::repositoriesAdapterOnClick); }) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe()); }

Target:
protected void bindInternal(@NonNull final CompositeDisposable s) { s.add(viewModel.getRepositories() .observeOn(AndroidSchedulers.mainThread()) .subscribe(view::setRepositories)); s.add(viewModel.getNetworkRequestStatusText() .observeOn(AndroidSchedulers.mainThread()) .subscribe(view::setNetworkRequestStatus)); s.add(view.searchStringObservable .observeOn(AndroidSchedulers.mainThread()) .subscribe(viewModel::setSearchString)); s.add(Completable.fromAction(() -> view.repositoriesAdapter.setOnClickListener(this::repositoriesAdapterOnClick)) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe()); }
Source:
public void parse() { String line = ""; String setupLine = ""; List<String> vars = new ArrayList<String>(); List<String> list = new ArrayList<String>(); int offset = 0; try { RandomAccessFile raf = new RandomAccessFile(file.getRawLocation().makeAbsolute().toFile(), "r"); long bytesToSkip = findStartSetup(raf); if (bytesToSkip == -1) return; long stop = findEndSetup(raf, bytesToSkip); if (stop == -1) return; raf.seek(0); while ((line = raf.readLine()) != null) { if (!line.trim().startsWith("#")) { if (isLineSimpleDefinition(line)) { vars.add(line); } else if (!vars.isEmpty() && vars.get(vars.size()-1).trim().endsWith("\\") && isLineContinuation(line)){ offset = vars.get(vars.size()-1).lastIndexOf('\\'); vars.set(vars.size() -1, vars.get(vars.size() - 1).substring(0, offset)); vars.set(vars.size() - 1, vars.get(vars.size() - 1) .concat(line.trim())); } } } raf.seek(bytesToSkip); while ((line = raf.readLine()) != null && raf.getFilePointer() <= stop) { line = line.trim(); if (!line.startsWith("#")) { if (setupLine.equals("")) setupLine = line.trim(); else setupLine = setupLine.concat(line.trim()); } } list = prepareSetupOptions(setupLine); for (String str : vars) { variables.putAll(parseLine(str)); } for (String str : list) { setupOptions.putAll(parseLine(str)); } resolveVariables(variables, setupOptions); raf.close(); } catch (FileNotFoundException e) { StubbyLog.logError(e); } catch (IOException e) { StubbyLog.logError(e); } }

Target:
public void parse() { String line = ""; String setupLine = ""; List<String> vars = new ArrayList<String>(); List<String> list = new ArrayList<String>(); int offset = 0; try { RandomAccessFile raf = new RandomAccessFile(file.getRawLocation().makeAbsolute().toFile(), "r"); long bytesToSkip = findStartSetup(raf); if (bytesToSkip == -1) { return; } long stop = findEndSetup(raf, bytesToSkip); if (stop == -1) { return; } raf.seek(0); while ((line = raf.readLine()) != null) { if (!line.trim().startsWith("#")) { if (isLineSimpleDefinition(line)) { vars.add(line); } else if (!vars.isEmpty() && vars.get(vars.size()-1).trim().endsWith("\\") && isLineContinuation(line)){ offset = vars.get(vars.size()-1).lastIndexOf('\\'); vars.set(vars.size() -1, vars.get(vars.size() - 1).substring(0, offset)); vars.set(vars.size() - 1, vars.get(vars.size() - 1) .concat(line.trim())); } } } raf.seek(bytesToSkip); while ((line = raf.readLine()) != null && raf.getFilePointer() <= stop) { line = line.trim(); if (!line.startsWith("#")) { if (setupLine.equals("")) { setupLine = line.trim(); } else { setupLine = setupLine.concat(line.trim()); } } } list = prepareSetupOptions(setupLine); for (String str : vars) { variables.putAll(parseLine(str)); } for (String str : list) { setupOptions.putAll(parseLine(str)); } resolveVariables(variables, setupOptions); raf.close(); } catch (FileNotFoundException e) { StubbyLog.logError(e); } catch (IOException e) { StubbyLog.logError(e); } }
Source:
public Collection<Integer> selectNextChildren(long t) { return Collections.emptyList(); }

Target:
public Collection<Integer> selectNextChildren(long t) { return Collections.EMPTY_LIST; }
Source:
public static void bootstrap( CatalogFramework catalogFramework, EndpointUtil endpointUtil, List<Metacard> systemTemplates) { Subject systemSubject = SECURITY.runAsAdmin(SECURITY::getSystemSubject); if (systemSubject == null) { throw new SecurityException("Could not get systemSubject to initialize system templates"); } ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); Failsafe.with( new RetryPolicy() .retryOn(Collections.singletonList(RuntimeException.class)) .withMaxRetries(5) .withBackoff(2, 60, TimeUnit.SECONDS)) .with(executor) .onComplete( (connection, failure) -> { if (connection != null) { LOGGER.info("Successfully loaded System Search Forms", connection); } else if (failure != null) { LOGGER.error("Failed to load System Search Forms", failure); } executor.shutdown(); }) .run( () -> systemSubject.execute( () -> SearchFormsLoader.createSystemMetacards( endpointUtil, systemTemplates, catalogFramework))); }

Target:
public static void bootstrap( CatalogFramework catalogFramework, EndpointUtil endpointUtil, List<Metacard> systemTemplates) { Subject systemSubject = SECURITY.runAsAdmin(SECURITY::getSystemSubject); if (systemSubject == null) { throw new SecurityException("Could not get systemSubject to initialize system templates"); } ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); Failsafe.with( new RetryPolicy() .retryOn(Collections.singletonList(RuntimeException.class)) .withMaxRetries(5) .withBackoff(2, 60, TimeUnit.SECONDS)) .with(executor) .onComplete( (result, error) -> { if (result != null) { LOGGER.info("Successfully loaded System Search Forms {}", result); } else if (error != null) { LOGGER.error("Failed to load System Search Forms", error); } executor.shutdown(); }) .run( () -> systemSubject.execute( () -> SearchFormsLoader.createSystemMetacards( endpointUtil, systemTemplates, catalogFramework))); }
Source:
public Ds3Param toDs3Param() { Ds3Param ds3Param = new Ds3Param(name, type); return ds3Param; }

Target:
public Ds3Param toDs3Param() { final Ds3Param ds3Param = new Ds3Param(name, type); return ds3Param; }
Source:
protected Optional<PlanNode> visitTableScan(TableScanExpression tableScan, Context context) { List<Symbol> outputChannelNames = context.getOutput(); List<ColumnHandle> columnHandles = tableScan.getOutput().stream() .filter(ColumnReferenceExpression.class::isInstance) .map(ColumnReferenceExpression.class::cast) .map(ColumnReferenceExpression::getColumnHandle) .collect(toImmutableList()); checkArgument(columnHandles.size() == tableScan.getOutput().size(), "tableScan must contains all columnHandle"); ImmutableMap.Builder<Symbol, ColumnHandle> columnHandleMap = new ImmutableMap.Builder(); for (int i = 0; i < columnHandles.size(); i++) { columnHandleMap.put(outputChannelNames.get(i), columnHandles.get(i)); } Optional<TableLayoutHandle> tableLayoutHandle = Optional.empty(); if (tableScan.getConnectorTableLayoutHandle().isPresent()) { tableLayoutHandle = Optional.of( new TableLayoutHandle( connectorId, metadata.getTransactionHandle(session, connectorId), tableScan.getConnectorTableLayoutHandle().get())); } return Optional.of( new TableScanNode( idAllocator.getNextId(), new TableHandle(connectorId, tableScan.getTableHandle()), outputChannelNames, columnHandleMap.build(), tableLayoutHandle, TupleDomain.all(), TupleDomain.all())); }

Target:
private Optional<PlanNode> visitTableScan(TableScanExpression tableScan, Context context) { List<Symbol> outputChannelNames = context.getOutput(); List<ColumnHandle> columnHandles = tableScan.getOutput().stream() .filter(ColumnReferenceExpression.class::isInstance) .map(ColumnReferenceExpression.class::cast) .map(ColumnReferenceExpression::getColumnHandle) .collect(toImmutableList()); checkArgument(columnHandles.size() == tableScan.getOutput().size(), "tableScan must contains all columnHandle"); ImmutableMap.Builder<Symbol, ColumnHandle> columnHandleMap = new ImmutableMap.Builder(); for (int i = 0; i < columnHandles.size(); i++) { columnHandleMap.put(outputChannelNames.get(i), columnHandles.get(i)); } Optional<TableLayoutHandle> tableLayoutHandle = Optional.empty(); if (tableScan.getConnectorTableLayoutHandle().isPresent()) { tableLayoutHandle = Optional.of( new TableLayoutHandle( connectorId, metadata.getTransactionHandle(session, connectorId), tableScan.getConnectorTableLayoutHandle().get())); } return Optional.of( new TableScanNode( idAllocator.getNextId(), new TableHandle(connectorId, tableScan.getTableHandle()), outputChannelNames, columnHandleMap.build(), tableLayoutHandle, TupleDomain.all(), TupleDomain.all())); }
Source:
public void canObtainValidatorFactoryAndPerformValidation() { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); Set<ConstraintViolation<Customer>> constraintViolations = Validation.byDefaultProvider() .providerResolver( new MyValidationProviderResolver() ) .configure() .buildValidatorFactory() .getValidator() .validate( new Customer() ); assertEquals( 1, constraintViolations.size() ); assertEquals( "must be greater than or equal to 2", constraintViolations.iterator().next().getMessage() ); }

Target:
public void canObtainValidatorFactoryAndPerformValidation() { ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); Set<ConstraintViolation<Customer>> constraintViolations = Validation.byDefaultProvider() .providerResolver( new MyValidationProviderResolver() ) .configure() .buildValidatorFactory() .getValidator() .validate( new Customer() ); assertEquals( 1, constraintViolations.size() ); assertEquals( "must be greater than or equal to 2", constraintViolations.iterator().next().getMessage() ); } finally { Thread.currentThread().setContextClassLoader( originalClassLoader ); } }
Source:
private static List<Pair<String, String>> split(String flattenedPossibleRepresentations) { return ESCAPE_OUTER .getSplitPattern() .splitAsStream(flattenedPossibleRepresentations) .map(ESCAPE_OUTER::unescape) .map( joinedPossibleRepresentation -> { String[] values = ESCAPE_INNER.getSplitPattern().split(joinedPossibleRepresentation); if (values.length != 1 && values.length != 2) { throw new IllegalStateException( "Wrong number of split results - joined string: " + joinedPossibleRepresentation + ", split result: " + Arrays.toString(values)); } String name = values[0]; String path; if (values.length == 2) { path = values[1]; } else { path = ""; } return new ImmutablePair<>(ESCAPE_INNER.unescape(name), ESCAPE_INNER.unescape(path)); }) .collect(Collectors.toList()); }

Target:
private static List<Pair<String, String>> split(String flattenedPossibleRepresentations) { return ESCAPE_OUTER .splitAsStream(flattenedPossibleRepresentations) .map(ESCAPE_OUTER::unescape) .map(AbstractPossibleRepresentationProvider::splitInner) .filter(Objects::nonNull) .collect(Collectors.toList()); }
Source:
public void pushDirectoryURI(URI dir) { if (dir != null) { if (dir.isAbsolute()) fDirectoryStack.addElement(dir); else fDirectoryStack.addElement(URIUtil.makeAbsolute(dir, getWorkingDirectoryURI())); } }

Target:
public void pushDirectoryURI(URI dir) { if (dir != null) { if (dir.isAbsolute()) { fDirectoryStack.addElement(dir); } else { fDirectoryStack.addElement(URIUtil.makeAbsolute(dir, getWorkingDirectoryURI())); } } }
Source:
public final MessageInterpolator getDefaultMessageInterpolator() { return new ResourceBundleMessageInterpolator( defaultResourceBundleLocator ); }

Target:
public final MessageInterpolator getDefaultMessageInterpolator() { if ( defaultMessageInterpolator == null ) { defaultMessageInterpolator = new ResourceBundleMessageInterpolator( defaultResourceBundleLocator ); } return defaultMessageInterpolator; }
Source:
public void notifySurfaceDetached() { super.notifySurfaceDetached(); if (mImageReaderToReleaseList.size() > 0) { for (ImageReaderProxy imageReader : mImageReaderToReleaseList) { Surface surface = imageReader.getSurface(); if (surface != null) { surface.release(); } imageReader.close(); } mImageReaderToReleaseList.clear(); } }

Target:
public void notifySurfaceDetached() { super.notifySurfaceDetached(); if (!mImageReaderToReleaseList.isEmpty()) { for (ImageReaderProxy imageReader : mImageReaderToReleaseList) { Surface surface = imageReader.getSurface(); if (surface != null) { surface.release(); } imageReader.close(); } mImageReaderToReleaseList.clear(); } }
Source:
public String searchClassifier( String uriPath, String uriQuery ) { if(Utilities.stringContains(uriPath, apiPath)) { if(Utilities.stringContains(uriQuery, queryAction)) { if(Utilities.stringContains(uriQuery, prefixSearchList)) { return "prefix search"; } if(Utilities.stringContains(uriQuery, searchList)) { return "cirrus search"; } if(Utilities.stringContains(uriQuery, geoSearchList)) { return "geo search"; } return ""; } if(Utilities.stringContains(uriQuery, openSearchAction)) { return "open search"; } if(Utilities.stringContains(uriQuery, languageSearchAction)) { return "language search"; } } return ""; }

Target:
public String searchClassifier( String uriPath, String uriQuery ) { if(Utilities.stringContains(uriPath, apiPath)) { if(Utilities.stringContains(uriQuery, queryAction)) { if(Utilities.stringContains(uriQuery, prefixSearchList)) { return "prefix"; } if(Utilities.stringContains(uriQuery, searchList)) { return "cirrus"; } if(Utilities.stringContains(uriQuery, geoSearchList)) { return "geo"; } return ""; } if(Utilities.stringContains(uriQuery, openSearchAction)) { return "open"; } if(Utilities.stringContains(uriQuery, languageSearchAction)) { return "language"; } } return ""; }
Source:
public Builder addDictEncoding(Encoding encoding, int numPages) { Integer pages = dictStats.get(encoding); if (pages != null) { dictStats.put(encoding, numPages + pages); } else { dictStats.put(encoding, numPages); } return this; }

Target:
public Builder addDictEncoding(Encoding encoding, int numPages) { Integer pages = dictStats.get(encoding); dictStats.put(encoding, numPages + (pages != null ? pages : 0)); return this; }
Source:
public void nonExistentTablesWithMetadataDoNotAppearInGetMetadataForTables() { insertMetadataIntoNewCell(LOWER_UPPER); assertThat(kvs.getMetadataForTables()).isEmpty(); assertThat(kvs.getMetadataForTable(LOWER_UPPER)).contains(AtlasDbConstants.GENERIC_TABLE_METADATA); }

Target:
public void nonExistentTablesWithMetadataDoNotAppearInGetMetadataForTables() { insertMetadataIntoNewCell(LOWER_UPPER); assertThat(kvs.getMetadataForTables()).isEmpty(); }
Source:
public SSLContext get() { Credentials currentCreds = checkNotNull(creds.get(), "credential supplier returned null"); if (new File(currentCreds.identity).isFile() && new File(currentCreds.credential).isFile()) { try { SSLContext sslContext = SSLContext.getInstance("TLS"); X509Certificate certificate = getCertificate(loadFile(currentCreds.identity)); PrivateKey privateKey = getKey(loadFile(currentCreds.credential)); sslContext.init(new KeyManager[]{new InMemoryKeyManager(certificate, privateKey)}, trustManager, new SecureRandom()); return sslContext; } catch (GeneralSecurityException e) { throw new AssertionError(); } catch (IOException e) { throw propagate(e); } } return null; }

Target:
public SSLContext get() { Credentials currentCreds = checkNotNull(creds.get(), "credential supplier returned null"); try { SSLContext sslContext = SSLContext.getInstance("TLS"); X509Certificate certificate = getCertificate(loadFile(currentCreds.identity)); PrivateKey privateKey = getKey(loadFile(currentCreds.credential)); sslContext.init(new KeyManager[]{new InMemoryKeyManager(certificate, privateKey)}, trustManager, new SecureRandom()); return sslContext; } catch (GeneralSecurityException e) { throw propagate(e); } catch (IOException e) { throw propagate(e); } }
Source:
public void testConvertAdHocSubprocessNode_notautostart() throws Exception { final AdHocSubprocess definition = new AdHocSubprocess(); definition.getExecutionSet().setAdHocAutostart(new AdHocAutostart(false)); final View<BaseAdHocSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseAdHocSubprocess>, ?> node = new NodeImpl<>(UUID.randomUUID().toString()); node.setContent(view); SubProcessPropertyWriter writer = tested.convertAdHocSubprocessNode(node); assertTrue(AdHocSubProcessPropertyWriter.class.isInstance(writer)); assertFalse(CustomElement.autoStart.of(writer.getFlowElement()).get()); }

Target:
public void testConvertAdHocSubprocessNode_notautostart() { final AdHocSubprocess definition = new AdHocSubprocess(); definition.getExecutionSet().setAdHocAutostart(new AdHocAutostart(false)); final View<BaseAdHocSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseAdHocSubprocess>, ?> node = new NodeImpl<>(UUID.randomUUID().toString()); node.setContent(view); SubProcessPropertyWriter writer = tested.convertAdHocSubprocessNode(node); assertTrue(AdHocSubProcessPropertyWriter.class.isInstance(writer)); assertFalse(CustomElement.autoStart.of(writer.getFlowElement()).get()); }
Source:
public void testWritingToFile() throws IOException { for (int threads = 1; threads <= 4; threads++) { AsyncWriterPool pool = new AsyncWriterPool(threads); int fileNum = 8; ArrayList<File> files = new ArrayList<>(); ArrayList<Writer<String>> writers = new ArrayList<>(); ArrayList<Iterator<Integer>> streams = new ArrayList<>(); for (int i = 0; i < fileNum; i++) { File file = File.createTempFile(String.format("AsyncPoolWriter_%s_%s", threads, i), ".tmp"); TestWriter writer = new TestWriter(file.toPath()); files.add(file); Writer<String> pooledWriter = pool.pool(writer, new LinkedBlockingQueue<>(), 15); writers.add(pooledWriter); streams.add(Stream.iterate(0, val -> val + 1).iterator()); } for (int i = 0; i < fileNum * 10; i++) { for (int j = 0; j < 10; j++) { writers.get(i % fileNum).write(String.format("%s\n", streams.get(i % fileNum).next())); } } pool.close(); for (int i = 0; i < fileNum; i++) { File file = files.get(i); List<Integer> lines = IOUtil.slurpLines(file).stream().map(Integer::parseInt).collect(Collectors.toList()); assert AsyncWriterPoolTest.isSorted(lines); assert lines.size() == 100; } } }

Target:
public void testWritingToFile() throws IOException { for (int threads = 1; threads <= 4; threads++) { AsyncWriterPool pool = new AsyncWriterPool(threads); int fileNum = 8; ArrayList<File> files = new ArrayList<>(); ArrayList<Writer<String>> writers = new ArrayList<>(); ArrayList<Iterator<Integer>> streams = new ArrayList<>(); for (int i = 0; i < fileNum; i++) { File file = File.createTempFile(String.format("AsyncPoolWriter_%s_%s", threads, i), ".tmp"); file.deleteOnExit(); TestWriter writer = new TestWriter(file.toPath()); files.add(file); Writer<String> pooledWriter = pool.pool(writer, new LinkedBlockingQueue<>(), 15); writers.add(pooledWriter); streams.add(Stream.iterate(0, val -> val + 1).iterator()); } for (int i = 0; i < fileNum * 10; i++) { for (int j = 0; j < 10; j++) { writers.get(i % fileNum).write(String.format("%s\n", streams.get(i % fileNum).next())); } } pool.close(); for (int i = 0; i < fileNum; i++) { File file = files.get(i); List<Integer> lines = IOUtil.slurpLines(file).stream().map(Integer::parseInt).collect(Collectors.toList()); Assert.assertTrue(AsyncWriterPoolTest.isSorted(lines)); Assert.assertEquals(lines.size(), 100); } } }
Source:
private void initTable() { AbstractEntityModelTextColumn<StorageDomain> nameColumn = new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { return storage.getStorageName(); } }; storageDomainItems.setColumnWidth(nameColumn, "280px"); storageDomainItems.addColumn(nameColumn, constants.nameStorage()); AbstractEntityModelTextColumn<StorageDomain> freeSpaceColumn = new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { if (storage.getAvailableDiskSize() == null || storage.getAvailableDiskSize() < 1) { return messages.gigabytes("< 1"); } return messages.gigabytes(storage.getAvailableDiskSize().toString()); } }; storageDomainItems.setColumnWidth(freeSpaceColumn, "80px"); storageDomainItems.addColumn(freeSpaceColumn, constants.freeSpaceStorage()); }

Target:
private void initTable() { AbstractEntityModelTextColumn<StorageDomain> nameColumn = new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { return storage.getStorageName(); } }; storageDomainItems.setColumnWidth(nameColumn, "280px"); storageDomainItems.addColumn(nameColumn, constants.nameStorage()); AbstractEntityModelTextColumn<StorageDomain> freeSpaceColumn = new AbstractEntityModelTextColumn<StorageDomain>() { @Override public String getText(StorageDomain storage) { if (storage.getAvailableDiskSize() == null || storage.getAvailableDiskSize() < 1) { return messages.gigabytes("< 1"); } return messages.gigabytes(String.valueOf(storage.getAvailableDiskSize())); } }; storageDomainItems.setColumnWidth(freeSpaceColumn, "80px"); storageDomainItems.addColumn(freeSpaceColumn, constants.freeSpaceStorage()); }