auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Collection<TypeUrl> getTypesFromPackage(final String packageName) { final Collection<TypeUrl> knownTypeUrls = knownTypes.keySet(); final Collection<TypeUrl> result = Collections2.filter(knownTypeUrls, new Predicate<TypeUrl>() { @Override public boolean apply(@Nullable TypeUrl input) { if (input == null) { return false; } final boolean inPackage = input.getTypeName().startsWith(packageName); return inPackage; } }); return result; }

Target:
public static Set<TypeUrl> getTypesFromPackage(final String packageName) { final Collection<TypeUrl> knownTypeUrls = knownTypes.keySet(); final Collection<TypeUrl> resultCollection = Collections2.filter(knownTypeUrls, new Predicate<TypeUrl>() { @Override public boolean apply(@Nullable TypeUrl input) { if (input == null) { return false; } final String typeName = input.getTypeName(); final boolean inPackage = typeName.startsWith(packageName) && typeName.charAt(packageName.length()) == PACKAGE_SEPARATOR; return inPackage; } }); final Set<TypeUrl> resultSet = ImmutableSet.copyOf(resultCollection); return resultSet; }
Source:
public Element unparseServiceCreationConfiguration(ServiceCreationConfiguration<TransactionManagerProvider> serviceCreationConfiguration) { try { validateParameterForTranslationToServiceConfig(serviceCreationConfiguration); Document doc = createDocumentRoot(); LookupTransactionManagerProviderConfiguration lookupTransactionManagerProviderConfiguration = (LookupTransactionManagerProviderConfiguration) serviceCreationConfiguration; Element rootElement = createRootElement(doc, lookupTransactionManagerProviderConfiguration); return rootElement; } catch (SAXException | ParserConfigurationException | IOException e) { throw new XmlConfigurationException(e); } }

Target:
public Element unparseServiceCreationConfiguration(ServiceCreationConfiguration<TransactionManagerProvider> serviceCreationConfiguration) { return unparseConfig(serviceCreationConfiguration); }
Source:
public StashCredentials getCredentials() throws StashConfigurationException { String pwEnv = config.getStashPasswordEnvironmentVariable(); String pw = config.getStashPassword(); if (pwEnv != null) { pw = System.getenv(pwEnv); if (pw == null) { throw new StashConfigurationException( "Unable to retrieve password from configured environment variable " + StashPlugin.STASH_PASSWORD_ENVIRONMENT_VARIABLE); } } return new StashCredentials(config.getStashLogin(), pw); }

Target:
public StashCredentials getCredentials() throws StashConfigurationException { String passwordEnvVariable = config.getStashPasswordEnvironmentVariable(); String password = config.getStashPassword(); if (passwordEnvVariable != null) { password = System.getenv(passwordEnvVariable); if (password == null) { throw new StashConfigurationException( "Unable to retrieve password from configured environment variable " + StashPlugin.STASH_PASSWORD_ENVIRONMENT_VARIABLE); } } return new StashCredentials(config.getStashLogin(), password); }
Source:
public static int getKFromEpsilon(final double epsilon, final boolean pmf) { final double eps = max(epsilon, 4.7E-5); final double kdbl = pmf ? exp(log(1.854 / eps) / 0.9657) : exp(log(1.576 / eps) / 0.9726); final double krnd = round(kdbl); final double del = abs(krnd - kdbl); final int k = (int) ((del < 1E-6) ? krnd : ceil(kdbl)); return k; }

Target:
public static int getKFromEpsilon(final double epsilon, final boolean pmf) { final double eps = max(epsilon, 6.395E-5); final double kdbl = pmf ? exp(log(1.854 / eps) / 0.9657) : exp(log(1.576 / eps) / 0.9726); final double krnd = round(kdbl); final double del = abs(krnd - kdbl); final int k = (int) ((del < 1E-6) ? krnd : ceil(kdbl)); return max(MIN_K, min(MAX_K, k)); }
Source:
public static Win32VK fromValue(final int code) { if (code < 0 || code > 0xFF) { throw new IllegalArgumentException(String.format("No mapping for %02x", code)); } for (Win32VK vk : Win32VK.values()) { if (vk.code == code) { return vk; } } throw new IllegalArgumentException(String.format("No mapping for %02x", code)); }

Target:
public static Win32VK fromValue(final int code) { for (Win32VK vk : Win32VK.values()) { if (vk.code == code) { return vk; } } throw new IllegalArgumentException(String.format("No mapping for %02x", code)); }
Source:
public static DataSource cosmos( String name, String cosmosConnectionString, String collectionName, String query, Boolean useChangeDetection, String description, DataDeletionDetectionPolicy deletionDetectionPolicy) { if (CoreUtils.isNullOrEmpty(name)) { throw new IllegalArgumentException("name cannot be null or empty"); } if (CoreUtils.isNullOrEmpty(collectionName)) { throw new IllegalArgumentException("collectionName cannot be null or empty"); } if (CoreUtils.isNullOrEmpty(cosmosConnectionString)) { throw new IllegalArgumentException("cosmosConnectionString cannot be null or empty"); } return new DataSource() .setName(name) .setType(DataSourceType.COSMOS) .setCredentials(new DataSourceCredentials() .setConnectionString(cosmosConnectionString)) .setContainer(new DataContainer() .setName(collectionName) .setQuery(query)) .setDescription(description) .setDataDeletionDetectionPolicy(deletionDetectionPolicy) .setDataChangeDetectionPolicy( useChangeDetection ? new HighWaterMarkChangeDetectionPolicy().setHighWaterMarkColumnName("_ts") : null); }

Target:
public static DataSource cosmos( String name, String cosmosConnectionString, String collectionName, String query, Boolean useChangeDetection, String description, DataDeletionDetectionPolicy deletionDetectionPolicy) { if (CoreUtils.isNullOrEmpty(name)) { throw new IllegalArgumentException("name cannot be null or empty"); } if (CoreUtils.isNullOrEmpty(collectionName)) { throw new IllegalArgumentException("collectionName cannot be null or empty"); } if (CoreUtils.isNullOrEmpty(cosmosConnectionString)) { throw new IllegalArgumentException("cosmosConnectionString cannot be null or empty"); } return new DataSource() .setName(name) .setType(DataSourceType.COSMOS) .setCredentials(new DataSourceCredentials() .setConnectionString(cosmosConnectionString)) .setContainer(new DataContainer() .setName(collectionName) .setQuery(query)) .setDataChangeDetectionPolicy( useChangeDetection ? new HighWaterMarkChangeDetectionPolicy().setHighWaterMarkColumnName("_ts") : null) .setDescription(description) .setDataDeletionDetectionPolicy(deletionDetectionPolicy); }
Source:
public String getCommitStatusFromPatch(Patch patch) throws NotFoundException { checkRepositoryServiceExists(); Objects.requireNonNull(patch, "patch cannot be null"); String status = null; for (RepositoryService repositoryService : repositories) { try { status = repositoryService.getCommitStatusFromPatch(patch); } catch (NotFoundException e) { if (LOG.isInfoEnabled()) LOG.info("No commit status found at RepositoryService: " + repositoryService.getClass().getName(), e); } } return status; }

Target:
public CommitStatus getCommitStatusFromPatch(Patch patch) throws NotFoundException { checkRepositoryServiceExists(); Objects.requireNonNull(patch, "patch cannot be null"); for (RepositoryService repositoryService : repositories) { try { return repositoryService.getCommitStatusFromPatch(patch); } catch (NotFoundException e) { if (LOG.isInfoEnabled()) LOG.info("No commit status found at RepositoryService: " + repositoryService.getClass().getName(), e); } } throw new NotFoundException("No commit status found for patch:" + patch.getURL()); }
Source:
public Map<ByteArray, Boolean> hasKeys(Iterable<ByteArray> keys, boolean exact) { StoreUtils.assertValidKeys(keys); Map<ByteArray, Boolean> results = new HashMap<ByteArray, Boolean>(); try { fileModificationLock.readLock().lock(); List<KeyValueLocation> keysAndValueLocations = Lists.newArrayList(); for(ByteArray key: keys) { int chunk = fileSet.getChunkForKey(key.get()); int valueLocation = searchStrategy.indexOf(fileSet.indexFileFor(chunk), fileSet.keyToStorageFormat(key.get()), fileSet.getIndexFileSize(chunk)); if(valueLocation >= 0) { if(exact) keysAndValueLocations.add(new KeyValueLocation(chunk, key, valueLocation)); else results.put(key, true); } } if(exact) { Collections.sort(keysAndValueLocations); for(KeyValueLocation keyVal: keysAndValueLocations) { byte[] value = fileSet.readValue(keyVal.getKey().get(), keyVal.getChunk(), keyVal.getValueLocation()); if(value.length > 0) results.put(keyVal.getKey(), true); } } return results; } finally { fileModificationLock.readLock().unlock(); } }

Target:
public Map<ByteArray, Boolean> hasKeys(Iterable<ByteArray> keys, boolean exact) { StoreUtils.assertValidKeys(keys); Map<ByteArray, Boolean> results = new HashMap<ByteArray, Boolean>(); try { fileModificationLock.readLock().lock(); List<KeyValueLocation> keysAndValueLocations = Lists.newArrayList(); for(ByteArray key: keys) { int chunk = fileSet.getChunkForKey(key.get()); int valueLocation = searchStrategy.indexOf(fileSet.indexFileFor(chunk), fileSet.keyToStorageFormat(key.get()), fileSet.getIndexFileSize(chunk)); if(valueLocation >= 0) { if(exact) keysAndValueLocations.add(new KeyValueLocation(chunk, key, valueLocation)); else results.put(key, true); } } if(exact) { Collections.sort(keysAndValueLocations); for(KeyValueLocation keyVal: keysAndValueLocations) { results.put(keyVal.getKey(), fileSet.keyExists(keyVal.getKey().get(), keyVal.getChunk(), keyVal.getValueLocation())); } } return results; } finally { fileModificationLock.readLock().unlock(); } }
Source:
public Observable<Boolean> buildRx() { return Observable.defer(new Func0<Observable<Boolean>>() { @Override public Observable<Boolean> call() { return Observable.create(new Observable.OnSubscribe<Boolean>() { @Override public void call(Subscriber<? super Boolean> subscriber) { try { startBuild(); subscriber.onNext(true); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } } }); } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); }

Target:
public Observable<Boolean> buildRx() { Utils.checkRx(); return Observable.defer(new Func0<Observable<Boolean>>() { @Override public Observable<Boolean> call() { return Observable.create(new Observable.OnSubscribe<Boolean>() { @Override public void call(Subscriber<? super Boolean> subscriber) { try { startBuild(); subscriber.onNext(true); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } } }); } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); }
Source:
public static void report(Saveable obj, Collection<Throwable> errors) { StringBuilder buf = new StringBuilder(); int i = 0; for (Throwable e : errors) { if (e instanceof ReportException) { report(obj, ((ReportException)e).version); } else { if (++i > 1) buf.append(", "); buf.append(e.getClass().getSimpleName()).append(": ").append(e.getMessage()); } } if (buf.length() == 0) return; Jenkins j = Jenkins.getInstance(); if (j == null) { for (Throwable t : errors) { LOGGER.log(Level.WARNING, "could not read " + obj + " (and Jenkins did not start up)", t); } return; } OldDataMonitor odm = get(j); SaveableReference ref = referTo(obj); while (true) { VersionRange vr = odm.data.get(ref); if (vr != null) { vr.extra = buf.toString(); break; } else if (odm.data.put(ref, new VersionRange(null, buf.toString())) == null) { break; } } }

Target:
public static void report(Saveable obj, Collection<Throwable> errors) { StringBuilder buf = new StringBuilder(); int i = 0; for (Throwable e : errors) { if (e instanceof ReportException) { report(obj, ((ReportException)e).version); } else { if (++i > 1) buf.append(", "); buf.append(e.getClass().getSimpleName()).append(": ").append(e.getMessage()); } } if (buf.length() == 0) return; Jenkins j = Jenkins.getInstance(); if (j == null) { for (Throwable t : errors) { LOGGER.log(Level.WARNING, "could not read " + obj + " (and Jenkins did not start up)", t); } return; } OldDataMonitor odm = get(j); SaveableReference ref = referTo(obj); while (true) { VersionRange vr = odm.data.get(ref); if (vr != null && odm.data.replace(ref, vr, new VersionRange(vr, null, buf.toString()))) { break; } else if (odm.data.putIfAbsent(ref, new VersionRange(null, null, buf.toString())) == null) { break; } } }
Source:
protected final byte[] generatePremasterSecretFromPSK(byte[] psk, byte[] otherSecret) { int pskLength = psk.length; byte[] pskLengthField = new byte[2]; pskLengthField[0] = (byte) (pskLength >> 8); pskLengthField[1] = (byte) (pskLength); if(otherSecret == null) { byte[] zero = ByteArrayUtils.padArray(new byte[0], (byte) 0x00, pskLength); byte[] premasterSecret = ByteArrayUtils.concatenate(pskLengthField, ByteArrayUtils.concatenate(zero, ByteArrayUtils.concatenate(pskLengthField, psk))); return premasterSecret; } else { int otherSecretLength = otherSecret.length; byte[] otherSecretLengthField = new byte[2]; otherSecretLengthField[0] = (byte) (otherSecretLength >> 8); otherSecretLengthField[1] = (byte) (otherSecretLength); byte[] premasterSecret = ByteArrayUtils.concatenate(ByteArrayUtils.concatenate(otherSecretLengthField, otherSecret), ByteArrayUtils.concatenate(pskLengthField, psk)); return premasterSecret; } }

Target:
protected final byte[] generatePremasterSecretFromPSK(byte[] psk, byte[] otherSecret) { int pskLength = psk.length; byte[] other = otherSecret == null ? new byte[pskLength] : otherSecret; DatagramWriter writer = new DatagramWriter(); writer.write(other.length, 16); writer.writeBytes(other); writer.write(pskLength, 16); writer.writeBytes(psk); return writer.toByteArray(); }
Source:
public void start() { log.info("ShardOrganizationManager start, enabled: %s, started: %s", enabled, started); if (!enabled || started.getAndSet(true)) { log.info("ShardOrganizationManager return"); return; } startDiscovery(); }

Target:
public void start() { if (!enabled || started.getAndSet(true)) { return; } startDiscovery(); }
Source:
public Memoizer() { this.map = new HashMap<K, V>(); ReadWriteLock lock = new ReentrantReadWriteLock(); this.readLock = lock.readLock(); this.writeLock = lock.writeLock(); }

Target:
public Memoizer() { this.map = new LinkedHashMap<K, V>(); ReadWriteLock lock = new ReentrantReadWriteLock(); this.readLock = lock.readLock(); this.writeLock = lock.writeLock(); }
Source:
public CompletableFuture<TransactionId> startTransaction(PublicKeyHash owner) { return CompletableFuture.completedFuture(new TransactionId(Long.toString(System.currentTimeMillis()))); }

Target:
public CompletableFuture<TransactionId> startTransaction(PublicKeyHash owner) { return CompletableFuture.completedFuture(transactions.startTransaction(owner)); }
Source:
private int checkHeaderField(String headerName, String fieldName, BitInputStream input, int sizeInBits, Predicate<Integer> validator) throws IOException { int value = input.readInt(sizeInBits); if (validator.test(value)) { throw new UnknownContentTypeException(headerName + "Header " + fieldName + ": " + value); } return value; }

Target:
private int checkHeaderField(String headerName, String fieldName, BitInputStream input, int sizeInBits, Predicate<Integer> validator) throws IOException { int value = input.readInt(sizeInBits); if (!validator.test(value)) { throw new UnknownContentTypeException(headerName + "Header " + fieldName + ": " + value); } return value; }
Source:
public Transformer build(Site site) throws IOException { Templates templates = transformTemplateCache.get(site); if (templates == null) { TransformerFactory factory = newTransformerFactory(); Theme theme = site.getTheme(); try (ThemeUriResolver resolver = new ThemeUriResolver(theme); InputStream transformFile = theme.getStaticResource(rootPath + templateFilename)) { factory.setURIResolver(resolver); templates = factory.newTemplates(new StreamSource(transformFile)); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } transformTemplateCache.put(site, templates); } try { return templates.newTransformer(); } catch (TransformerConfigurationException e){ throw new RuntimeException(e); } }

Target:
public Transformer build(Site site) { Templates templates = transformTemplateCache.computeIfAbsent(site, this::createTemplate); try { return templates.newTransformer(); } catch (TransformerConfigurationException e){ throw new RuntimeException(e); } }
Source:
public void populateExpressionProperty(FactModelTree factModelTree) { factModelTree.addSimpleProperty(factModelTree.getFactName() + "Expression", "expression"); }

Target:
public void populateExpressionProperty(FactModelTree factModelTree) { factModelTree.addSimpleProperty(factModelTree.getFactName() + ConstantsHolder.EXPRESSION_SUFFIX, ConstantsHolder.EXPRESSION_CLASSNAME); }
Source:
private void verifySlotsUnblocked(AdsBaseObject ads, List<Map<String, Object>> slotsData) { for (Map<String, Object> slotData : slotsData) { String slotName = slotData.get("slotName").toString(); ads.wait.forElementPresent(By.cssSelector("#"+slotName)); ads.scrollToPosition("#"+slotName); Dimension slotSize = (Dimension) slotData.get("slotSize"); ads.verifyLineItemId(slotName, Integer.valueOf(slotData.get("lineItemId").toString())); ads.verifyIframeSize(slotName, slotData.get("src").toString(), slotSize.getWidth(), slotSize.getHeight()); } }

Target:
private void verifySlotsUnblocked(AdsBaseObject ads, List<Map<String, Object>> slotsData) { for (Map<String, Object> slotData : slotsData) { String slotName = slotData.get("slotName").toString(); String slotSelector = AdsContent.getSlotSelector(slotName); ads.wait.forElementPresent(By.cssSelector(slotSelector)); ads.scrollToPosition(slotSelector); Dimension slotSize = (Dimension) slotData.get("slotSize"); ads.verifyLineItemId(slotName, Integer.valueOf(slotData.get("lineItemId").toString())); ads.verifyIframeSize(slotName, slotData.get("src").toString(), slotSize.getWidth(), slotSize.getHeight()); } }
Source:
public WorldBorder getWorldBorder() { if (this.worldBorder == null) { this.worldBorder = cloneBorder((WorldBorder) this.world.worldBorder); } return this.worldBorder; }

Target:
public Optional<WorldBorder> getWorldBorder() { return Optional.ofNullable(this.worldBorder); }
Source:
public Network mapRow(ResultSet rs, int rowNum) throws SQLException { Network entity = super.mapRow(rs, rowNum); entity.setCluster(new NetworkCluster()); entity.getCluster().setDisplay((Boolean) rs.getObject("is_display")); entity.getCluster().setRequired(rs.getBoolean("required")); entity.getCluster().setStatus(NetworkStatus.forValue(rs.getInt("status"))); entity.getCluster().setMigration((Boolean) rs.getObject("migration")); return entity; }

Target:
public Network mapRow(ResultSet rs, int rowNum) throws SQLException { Network entity = super.mapRow(rs, rowNum); entity.setCluster(new NetworkCluster()); entity.getCluster().setDisplay((Boolean) rs.getObject("is_display")); entity.getCluster().setRequired(rs.getBoolean("required")); entity.getCluster().setStatus(NetworkStatus.forValue(rs.getInt("status"))); entity.getCluster().setMigration(rs.getBoolean("migration")); return entity; }
Source:
public Collection<String> getBoltNames() { getCachedPhysicalPlan(); return getBoltNames(cachedPhysicalPlan); }

Target:
public List<String> getBoltNames() { PhysicalPlan pp = getPhysicalPlan(); return getBoltNames(pp); }
Source:
public void seek(long position) throws IOException { if (Math.abs(position - mPos) > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } else { ((FSDataInputStream) in).seek(position); } mPos = position; }

Target:
public void seek(long position) throws IOException { if (position < mPos || position - mPos > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } mPos = position; }
Source:
public int getItemViewType(int position) { if (mItemList.get(position) instanceof ParentObject) { return TYPE_PARENT; } else if (mItemList.get(position) instanceof ChildObject) { return TYPE_CHILD; } else { return TYPE_PARENT; } }

Target:
public int getItemViewType(int position) { if (mItemList.get(position) instanceof ParentObject) { return TYPE_PARENT; } else if (mItemList.get(position) instanceof ChildObject) { return TYPE_CHILD; } else if (mItemList.get(position) == null) { throw new IllegalStateException("Null object added"); } else { return TYPE_PARENT; } }
Source:
public boolean sendToPlayers() { if (this.sentToPlayers) { return true; } if (this.cube == null || !this.playerCubeMap.getWorld().getGeneratorPipeline().isLastStage(cube.getGeneratorStage())) { return false; } this.dirtyBlocks.clear(); this.sentToPlayers = true; for (WatcherPlayerEntry entry : this.players.valueCollection()) { sendToPlayer(entry.player); } return true; }

Target:
public boolean sendToPlayers() { if (this.sentToPlayers) { return true; } if (this.cube == null || !this.cube.getGeneratorStage().isLastStage()) { return false; } this.dirtyBlocks.clear(); this.sentToPlayers = true; for (WatcherPlayerEntry entry : this.players.valueCollection()) { sendToPlayer(entry.player); } return true; }
Source:
public ByteBuf getCommandLineBytes() { final ImapArgumentFormatter argWriter = new ImapArgumentFormatter(); final String flagListString = argWriter.buildFlagString(flags); final String unchangedSinceStr = unchangedSince == null ? "" : unchangedSince.toString(); final int len = ImapClientConstants.PAD_LEN + msgNumbers.length() + unchangedSinceStr.length() + flagListString.length(); final ByteBuf sb = Unpooled.buffer(len); sb.writeBytes(isUid ? UID_STORE_SP_B : STORE_SP_B); sb.writeBytes(msgNumbers.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.SPACE); if (unchangedSince != null) { sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(UNCHANGEDSINCE_SP_B); sb.writeBytes(unchangedSinceStr.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.R_PAREN); sb.writeByte(ImapClientConstants.SPACE); } if (action == FlagsAction.ADD) { sb.writeByte(ImapClientConstants.PLUS); } else if (action == FlagsAction.REMOVE) { sb.writeByte(ImapClientConstants.MINUS); } sb.writeBytes(FLAGS_B); if (isSilent) { sb.writeBytes(SILENT_B); } sb.writeByte(ImapClientConstants.SPACE); sb.writeBytes(flagListString.getBytes(StandardCharsets.US_ASCII)); sb.writeBytes(CRLF_B); return sb; }

Target:
public ByteBuf getCommandLineBytes() { final ImapArgumentFormatter argWriter = new ImapArgumentFormatter(); final String flagListString = argWriter.buildFlagString(flags); final String unchangedSinceStr = unchangedSince == null ? "" : unchangedSince.toString(); final int len = ImapClientConstants.PAD_LEN + msgNumbers.length() + flagListString.length(); final ByteBuf sb = Unpooled.buffer(len); sb.writeBytes(isUid ? UID_STORE_SP_B : STORE_SP_B); sb.writeBytes(msgNumbers.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.SPACE); if (unchangedSince != null) { sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(UNCHANGEDSINCE_SP_B); sb.writeBytes(unchangedSinceStr.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.R_PAREN); sb.writeByte(ImapClientConstants.SPACE); } if (action == FlagsAction.ADD) { sb.writeByte(ImapClientConstants.PLUS); } else if (action == FlagsAction.REMOVE) { sb.writeByte(ImapClientConstants.MINUS); } sb.writeBytes(FLAGS_B); if (isSilent) { sb.writeBytes(SILENT_B); } sb.writeByte(ImapClientConstants.SPACE); sb.writeBytes(flagListString.getBytes(StandardCharsets.US_ASCII)); sb.writeBytes(CRLF_B); return sb; }
Source:
public static Properties loadProperties(InputStream resource) { try ( Reader is = new InputStreamReader(resource, "UTF-8"); ) { Properties prop = new Properties(); prop.load(is); return prop; } catch (IOException ioe) { throw new RuntimeException(ioe); } }

Target:
public static Properties loadProperties(InputStream resource) { try ( Reader is = new InputStreamReader(resource, Charset.forName("UTF-8")); ) { Properties prop = new Properties(); prop.load(is); return prop; } catch (IOException ioe) { throw new RuntimeException(ioe); } }
Source:
public int hashCode() { return (int) (getAddress() & 0xFFFFFFFF); }

Target:
public int hashCode() { return Long.hashCode(this.getAddress()); }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (intentListeners.indexOfKey(requestCode) >= 0) { IntentListener asker = intentListeners.get(requestCode); asker.onIntentResult(resultCode, data); intentListeners.remove(requestCode); } else if (requestCode == REQUEST_EXPORT_EMBROIDERY_FILE) { if (resultCode == RESULT_OK) { Log.d(TAG, "Exported embroidery file"); } } else { stageResourceHolder.onActivityResult(requestCode, resultCode, data); } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (intentListeners.indexOfKey(requestCode) >= 0) { IntentListener asker = intentListeners.get(requestCode); asker.onIntentResult(resultCode, data); intentListeners.remove(requestCode); } else { stageResourceHolder.onActivityResult(requestCode, resultCode, data); } }
Source:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !mayReturnNullOnNonNullInput(expression) && !isDynamicFilter(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }

Target:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !mayReturnNullOnNonNullInput(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }
Source:
public static byte[] encodeOSCoreRequest(OSCoreCtx ctx) { int firstByte = 0x00; ByteArrayOutputStream bRes = new ByteArrayOutputStream(); byte[] partialIV = OSSerializer.processPartialIV(ctx.getSenderSeq()); firstByte = firstByte | (partialIV.length & 0x07); firstByte = firstByte | 0x08; if(ctx.getIncludeContextId() == true) { firstByte = firstByte | 0x10; } bRes.write(firstByte); try { bRes.write(partialIV); if(ctx.getIncludeContextId() == true) { bRes.write(ctx.getIdContext().length); bRes.write(ctx.getIdContext()); } bRes.write(ctx.getSenderId()); } catch (IOException e) { e.printStackTrace(); } return bRes.toByteArray(); }

Target:
public static byte[] encodeOSCoreRequest(OSCoreCtx ctx) { int firstByte = 0x00; ByteArrayOutputStream bRes = new ByteArrayOutputStream(); byte[] partialIV = OSSerializer.processPartialIV(ctx.getSenderSeq()); firstByte = firstByte | (partialIV.length & 0x07); firstByte = firstByte | 0x08; if (ctx.getIncludeContextId()) { firstByte = firstByte | 0x10; } bRes.write(firstByte); try { bRes.write(partialIV); if (ctx.getIncludeContextId()) { bRes.write(ctx.getIdContext().length); bRes.write(ctx.getIdContext()); } bRes.write(ctx.getSenderId()); } catch (IOException e) { e.printStackTrace(); } return bRes.toByteArray(); }
Source:
public boolean performFinish() { try { IProject project = selectContextPage.getProject(); final ContextType type = selectContextPage.getContextType(); String name = selectContextPage.getContextName(); IPath containerPath = selectContextPage.getPathInProject(); IQ7Folder folder = RcpttCore.create(project).getFolder(containerPath); context = folder.createContext(name, ContextTypeManager .getInstance() .getTypeById("org.eclipse.rcptt.ctx.super"), true, new NullProgressMonitor()); IQ7NamedElement copy = context .getWorkingCopy(new NullProgressMonitor()); try { SuperContext superCtx = (SuperContext) copy.getNamedElement(); superCtx.setChildType(type.getId()); Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); WriteAccessChecker writeAccessChecker = new WriteAccessChecker(shell); if (!writeAccessChecker.makeResourceWritable(copy)) { return false; } copy.commitWorkingCopy(true, new NullProgressMonitor()); } finally { copy.discardWorkingCopy(); } IDE.openEditor( workbench.getActiveWorkbenchWindow().getActivePage(), (IFile) context.getResource()); } catch (Exception e) { Q7UIPlugin.log(e); return false; } return true; }

Target:
public boolean performFinish() { try { IProject project = selectContextPage.getProject(); final ContextType type = selectContextPage.getContextType(); String name = selectContextPage.getContextName(); IPath containerPath = selectContextPage.getPathInProject(); IQ7Folder folder = RcpttCore.create(project).getFolder(containerPath); context = folder.createContext(name, ContextTypeManager .getInstance() .getTypeById("org.eclipse.rcptt.ctx.super"), true, new NullProgressMonitor()); IQ7NamedElement copy = context .getWorkingCopy(new NullProgressMonitor()); try { SuperContext superCtx = (SuperContext) copy.getNamedElement(); superCtx.setChildType(type.getId()); WriteAccessChecker writeAccessChecker = new WriteAccessChecker(getShell()); if (!writeAccessChecker.makeResourceWritable(copy)) { return false; } copy.commitWorkingCopy(true, new NullProgressMonitor()); } finally { copy.discardWorkingCopy(); } IDE.openEditor( workbench.getActiveWorkbenchWindow().getActivePage(), (IFile) context.getResource()); } catch (Exception e) { Q7UIPlugin.log(e); return false; } return true; }
Source:
public HttpConnectionFilterContext filterRequest(HttpConnectionFilterContext context) { HttpURLConnection connection = context.connection.getConnection(); if(cookie == null){ cookie = getCookie(connection.getURL()); } connection.setRequestProperty("Cookie",cookie); return context; }

Target:
public HttpConnectionFilterContext filterRequest(HttpConnectionFilterContext context) { HttpURLConnection connection = context.connection.getConnection(); if(shouldAttemptCookieRequest) { if (cookie == null) { cookie = getCookie(connection.getURL()); } connection.setRequestProperty("Cookie", cookie); } return context; }
Source:
private boolean hasPropsBefore( int[] propertyIds, SchemaDescriptor.PropertySchemaType propertySchemaType ) { boolean found = false; for ( int propertyId : propertyIds ) { PropertyValue propertyValue = knownProperties.get( propertyId ); if ( propertyValue == null || !propertyValue.hasBefore() ) { if ( propertySchemaType == COMPLETE_ALL_TOKENS ) { return false; } } else { found = true; } } return found; }

Target:
private boolean hasPropsBefore( int[] propertyIds, SchemaDescriptor.PropertySchemaType propertySchemaType ) { boolean found = false; for ( int propertyId : propertyIds ) { PropertyValue propertyValue = knownProperties.getIfAbsent( propertyId, () -> noValue ); if ( !propertyValue.hasBefore() ) { if ( propertySchemaType == COMPLETE_ALL_TOKENS ) { return false; } } else { found = true; } } return found; }
Source:
public void onSubmit(final String code) { dispatcher.execute(voteService.useCode(code), new RestCallbackImpl<Void>() { @Override public void onError(Response response) { super.onError(response); PlaceRequest placeRequest = new PlaceRequest.Builder() .nameToken(NameTokens.ALREADY_VOTED) .build(); placeManager.revealPlace(placeRequest); } @Override public void onSuccess(Void result) { Cookies.setCookie(CookieNames.VOTE_CODE, code); PlaceRequest placeRequest = new PlaceRequest.Builder() .nameToken(NameTokens.VOTE) .build(); placeManager.revealPlace(placeRequest); } }); }

Target:
public void onSubmit(final String code) { dispatcher.execute(voteService.useCode(code), new RestCallbackImpl<Void>() { @Override public void onError(Response response) { super.onError(response); if (response.getStatusCode() == SC_FORBIDDEN) { revealPlace(NameTokens.ALREADY_VOTED); } else { getView().showInvalidCodeError(); } } @Override public void onSuccess(Void result) { Cookies.setCookie(CookieNames.VOTE_CODE, code); revealPlace(NameTokens.VOTE); } }); }
Source:
public static TrackingLookupSourceSupplier createPartitionedLookupSourceSupplier(List<Supplier<LookupSource>> partitions, List<Type> hashChannelTypes, boolean outer) { if (outer) { OuterPositionTracker.Factory outerPositionTrackerFactory = new OuterPositionTracker.Factory(partitions); return new TrackingLookupSourceSupplier() { @Override public LookupSource getLookupSource() { return new PartitionedLookupSource( getPartitionsLookupSources(partitions), hashChannelTypes, Optional.of(outerPositionTrackerFactory.create())); } @Override public OuterPositionIterator getOuterPositionIterator() { return outerPositionTrackerFactory.getOuterPositionIterator(); } }; } else { return TrackingLookupSourceSupplier.from( () -> new PartitionedLookupSource( getPartitionsLookupSources(partitions), hashChannelTypes, Optional.empty())); } }

Target:
public static Supplier<LookupSource> createPartitionedLookupSourceSupplier(List<Supplier<LookupSource>> partitions, List<Type> hashChannelTypes, boolean outer) { Optional<OuterPositionTracker.Factory> outerPositionTrackerFactory = outer ? Optional.of(new OuterPositionTracker.Factory( partitions.stream() .map(partition -> partition.get().getJoinPositionCount()) .collect(toImmutableList()))) : Optional.empty(); return () -> new PartitionedLookupSource( partitions.stream() .map(Supplier::get) .collect(toImmutableList()), hashChannelTypes, outerPositionTrackerFactory.map(OuterPositionTracker.Factory::create)); }
Source:
public int getNext() { if (this == this.previous) { return this.id; } else if (this.previous == null) { System.out.printf("%s(unreached)", this.id); return (Integer)null; } else { Integer tmp = this.previous.getNext(); if (null != tmp) { pathNodeIds.add(tmp); } return this.id; } }

Target:
public Integer getNext() { if (this == this.previous) { return this.id; } else if (this.previous == null) { System.out.printf("%s(unreached)", this.id); return null; } else { Integer tmp = this.previous.getNext(); if (null != tmp) { pathNodeIds.add(tmp); } return this.id; } }
Source:
public void unregisterDeserializer(LRAParticipantDeserializer deserializer) { }

Target:
public void unregisterDeserializer(LRAParticipantDeserializer deserializer) { deserializers.remove(deserializer); }
Source:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { mUser = User.getUser(getArguments()); } else { mUser = User.getUser(savedInstanceState); } mHandler = ViewModelProviders.of(this).get(EmailProviderResponseHandler.class); mHandler.init(getFlowParams()); mHandler.getOperation().observe(this, new ResourceObserver<IdpResponse>( this, R.string.fui_progress_dialog_signing_up) { @Override protected void onSuccess(@NonNull IdpResponse response) { startSaveCredentials( mHandler.getCurrentUser(), response, mPasswordEditText.getText().toString()); } @Override protected void onFailure(@NonNull Exception e) { if (e instanceof FirebaseAuthWeakPasswordException) { mPasswordInput.setError(getResources().getQuantityString( R.plurals.fui_error_weak_password, R.integer.fui_min_password_length)); } else if (e instanceof FirebaseAuthInvalidCredentialsException) { mEmailInput.setError(getString(R.string.fui_invalid_email_address)); } else if (e instanceof FirebaseAuthAnonymousUpgradeException) { IdpResponse response = ((FirebaseAuthAnonymousUpgradeException) e).getResponse(); ((AnonymousUpgradeListener) getActivity()).onMergeFailure(response); } else { mEmailInput.setError(getString(R.string.fui_email_account_creation_error)); } } }); }

Target:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { mUser = User.getUser(getArguments()); } else { mUser = User.getUser(savedInstanceState); } mHandler = ViewModelProviders.of(this).get(EmailProviderResponseHandler.class); mHandler.init(getFlowParams()); mHandler.getOperation().observe(this, new ResourceObserver<IdpResponse>( this, R.string.fui_progress_dialog_signing_up) { @Override protected void onSuccess(@NonNull IdpResponse response) { startSaveCredentials( mHandler.getCurrentUser(), response, mPasswordEditText.getText().toString()); } @Override protected void onFailure(@NonNull Exception e) { if (e instanceof FirebaseAuthWeakPasswordException) { mPasswordInput.setError(getResources().getQuantityString( R.plurals.fui_error_weak_password, R.integer.fui_min_password_length)); } else if (e instanceof FirebaseAuthInvalidCredentialsException) { mEmailInput.setError(getString(R.string.fui_invalid_email_address)); } else if (e instanceof FirebaseAuthAnonymousUpgradeException) { IdpResponse response = ((FirebaseAuthAnonymousUpgradeException) e).getResponse(); mListener.onMergeFailure(response); } else { mEmailInput.setError(getString(R.string.fui_email_account_creation_error)); } } }); }
Source:
public void handlesTwoRequestInOneConnection() throws Exception { final String text = "Hello world!"; final Socket socket = Mockito.mock(Socket.class); Mockito.when(socket.getInputStream()).thenReturn( new ByteArrayInputStream( Joiner.on("\r\n").join( "POST / HTTP/1.1", "Host: localhost", "Content-Length: 4", "", "hi", "POST / HTTP/1.1", "Host: localhost", "Content-Length: 4", "", "hi" ).getBytes() ) ); Mockito.when(socket.getLocalAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getLocalPort()).thenReturn(0); Mockito.when(socket.getInetAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getPort()).thenReturn(0); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(baos); new BkReuse(new BkBasic(new TkGreedy(new TkText(text)))).accept(socket); final Pattern pattern = Pattern.compile( text + ".*?" + text, Pattern.DOTALL ); Assert.assertTrue( String.format("Actual is %s", baos.toString()), pattern.matcher(baos.toString()).find() ); }

Target:
public void handlesTwoRequestInOneConnection() throws Exception { final String text = "Hello world!"; final Socket socket = Mockito.mock(Socket.class); Mockito.when(socket.getInputStream()).thenReturn( new ByteArrayInputStream( Joiner.on("\r\n").join( "POST / HTTP/1.1", "Host: localhost", "Content-Length: 4", "", "hi", "POST / HTTP/1.1", "Host: localhost", "Content-Length: 4", "", "hi" ).getBytes("UTF-8") ) ); Mockito.when(socket.getLocalAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getLocalPort()).thenReturn(0); Mockito.when(socket.getInetAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getPort()).thenReturn(0); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(baos); new BkReuse(new BkBasic(new TkGreedy(new TkText(text)))).accept(socket); MatcherAssert.assertThat( baos.toString(), RegexMatchers.containsPattern(text + ".*?" + text) ); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IntervalBase other = (IntervalBase) obj; if (end == null) { if (other.end != null) return false; } else if (!end.equals(other.end)) return false; if (intervalType != other.intervalType) return false; if (sessionSeed == null) { if (other.sessionSeed != null) return false; } else if (!sessionSeed.equals(other.sessionSeed)) return false; if (start == null) { if (other.start != null) return false; } else if (!start.equals(other.start)) return false; return true; }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } IntervalBase other = (IntervalBase) obj; if (end == null) { if (other.end != null) { return false; } } else if (!end.equals(other.end)) { return false; } if (intervalType != other.intervalType) { return false; } if (sessionSeed == null) { if (other.sessionSeed != null) { return false; } } else if (!sessionSeed.equals(other.sessionSeed)) { return false; } if (start == null) { if (other.start != null) { return false; } } else if (!start.equals(other.start)) { return false; } return true; }
Source:
protected void onBindViewHolder(ViewHolder holder, CodeSearchResult result) { Repository repo = result.getRepository(); holder.tvTitle.setText(result.getName()); holder.tvRepo.setText(repo.getOwner().getLogin() + "/" + repo.getName()); List<TextMatch> matches = result.getTextMatches(); if (matches != null && !matches.isEmpty()) { LayoutInflater inflater = LayoutInflater.from(mContext); holder.matchesContainer.removeAllViews(); for (int i = 0; i < matches.size(); i++) { TextMatch match = matches.get(i); SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(match.getFragment()); List<TextMatch.MatchItem> items = match.getMatches(); if (items != null) { for (TextMatch.MatchItem item : items) { int start = item.getStartPos(); int end = item.getEdndPos(); if (start >= 0 && end > start) { builder.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0); } } } View row = inflater.inflate(R.layout.row_search_match, holder.matchesContainer, false); TextView tvMatch = (TextView) row.findViewById(R.id.tv_match); tvMatch.setOnClickListener(this); tvMatch.setText(builder); tvMatch.setTag(result); tvMatch.setTag(R.id.search_match_index, i); holder.matchesContainer.addView(row); } holder.matchesContainer.setVisibility(View.VISIBLE); } else { holder.matchesContainer.setVisibility(View.GONE); } }

Target:
protected void onBindViewHolder(ViewHolder holder, CodeSearchResult result) { Repository repo = result.getRepository(); holder.tvTitle.setText(result.getName()); holder.tvRepo.setText(repo.getOwner().getLogin() + "/" + repo.getName()); List<TextMatch> matches = result.getTextMatches(); if (matches != null && !matches.isEmpty()) { LayoutInflater inflater = LayoutInflater.from(mContext); for (int i = 0; i < matches.size(); i++) { TextMatch match = matches.get(i); SpannableStringBuilder builder = new SpannableStringBuilder(match.getFragment()); List<TextMatch.MatchItem> items = match.getMatches(); if (items != null) { for (TextMatch.MatchItem item : items) { int start = item.getStartPos(); int end = item.getEndPos(); if (start >= 0 && end > start) { builder.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0); } } } View row = holder.matchesContainer.getChildAt(i); if (row == null) { row = inflater.inflate(R.layout.row_search_match, holder.matchesContainer, false); holder.matchesContainer.addView(row); } TextView tvMatch = (TextView) row.findViewById(R.id.tv_match); tvMatch.setOnClickListener(this); tvMatch.setText(builder); tvMatch.setTag(result); tvMatch.setTag(R.id.search_match_index, i); row.setVisibility(View.VISIBLE); } for (int i = matches.size(); i < holder.matchesContainer.getChildCount(); i++) { holder.matchesContainer.getChildAt(i).setVisibility(View.GONE); } holder.matchesContainer.setVisibility(View.VISIBLE); } else { holder.matchesContainer.setVisibility(View.GONE); } }
Source:
public String processSVG(KieServerConnectionInfo connectionInfo, String containerId, String processId) { Client client = ClientBuilder.newClient(); Optional<String> location = connectionInfo.getLocation(); if (location.isPresent()) { WebTarget target = client.target(location.get()) .path(PROCESS_SVG_URI) .resolveTemplate(CONTAINER_ID_PARAM, containerId) .resolveTemplate(PROCESS_ID_PARAM, processId); addAuth(connectionInfo, target); String svg = target.request().get(String.class); client.close(); return svg; } throw new RuntimeException("Location for Kie Server is required. Check configuration."); }

Target:
public String processSVG(KieServerConnectionInfo connectionInfo, String containerId, String processId) { Optional<String> location = connectionInfo.getLocation(); if (location.isPresent()) { Client client = ClientBuilder.newClient(); WebTarget target = client.target(location.get()) .path(PROCESS_SVG_URI) .resolveTemplate(CONTAINER_ID_PARAM, containerId) .resolveTemplate(PROCESS_ID_PARAM, processId); addAuth(connectionInfo, target); String svg = target.request().get(String.class); client.close(); return svg; } throw new RuntimeException("Location for Kie Server is required. Check configuration."); }
Source:
public void open(DeserializationSchema.InitializationContext context) throws Exception; public void deserialize(Envelope envelope, AMQP.BasicProperties properties, byte[] body, RMQCollector collector) throws IOException; boolean isEndOfStream(T nextElement); public TypeInformation<T> getProducedType(); public interface RMQCollector<T> extends Collector<T> { public void collect(List<T> records); public void setMessageIdentifiers(String correlationId, long deliveryTag); }

Target:
default void open(DeserializationSchema.InitializationContext context) throws Exception { }
Source:
public void setDistribution(T[] values, double[] scores) { if (values.length == 0) { throw new RuntimeException("No values supplied"); } if (values.length != scores.length) { throw new RuntimeException("Number of scores and values must be identical"); } double[] exponents = new double[scores.length]; double shift = -Double.MAX_VALUE; for (int i = 0; i < scores.length; ++i) { exponents[i] = 0.5d * epsilon * scores[i]; shift = Math.max(shift, exponents[i]); } BigDecimal divisor = new BigDecimal(0d, mc); BigDecimal[] enumerators = new BigDecimal[scores.length]; for (int i = 0; i < scores.length; ++i) { enumerators[i] = exp(exponents[i] - shift); divisor = divisor.add(enumerators[i], mc); } List<Pair<T, Double>> pmf = new ArrayList<>(); for (int i = 0; i < scores.length; ++i) { BigDecimal enumerator = enumerators[i]; BigDecimal probability = enumerator.divide(divisor, mc); pmf.add(new Pair<T, Double>(values[i], probability.doubleValue())); } this.distribution = new EnumeratedDistribution<T>(this.random, pmf); }

Target:
public void setDistribution(T[] values, double[] scores) { if (values.length == 0) { throw new RuntimeException("No values supplied"); } if (values.length != scores.length) { throw new RuntimeException("Number of scores and values must be identical"); } double[] exponents = new double[scores.length]; double shift = -Double.MAX_VALUE; for (int i = 0; i < scores.length; ++i) { exponents[i] = 0.5d * epsilon * scores[i]; shift = Math.max(shift, exponents[i]); } List<Pair<T, Double>> pmf = new ArrayList<>(); for (int i = 0; i < scores.length; ++i) { double prob = Math.exp(exponents[i] - shift); pmf.add(new Pair<T, Double>(values[i], prob)); } this.distribution = new EnumeratedDistribution<T>(this.random, pmf); }
Source:
private void remove() { if (getWindow() != null) { return; } ConfirmationModel model = new ConfirmationModel(); setConfirmWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().removeAffinityLabelsTitle()); model.setHelpTag(HelpTag.remove_affinity_groups); model.setHashName("remove_affinity_labels"); ArrayList<String> list = new ArrayList<>(); for (Label affinityLabel : getSelectedItems()) { list.add(affinityLabel.getName()); } model.setItems(list); UICommand command = UICommand.createDefaultOkUiCommand("OnRemove", this); model.getCommands().add(command); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); }

Target:
private void remove() { if (getWindow() != null) { return; } ConfirmationModel model = new ConfirmationModel(); setConfirmWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().removeAffinityLabelsTitle()); model.setHelpTag(HelpTag.remove_affinity_groups); model.setHashName("remove_affinity_labels"); ArrayList<String> list = new ArrayList<>(); for (Label affinityLabel : getSelectedItems()) { list.add(affinityLabel.getName()); } model.setItems(list); model.getCommands().add(UICommand.createDefaultOkUiCommand("OnRemove", this)); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); }