auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean collectProjectFilesFromDirectory( Collection<File> files, File directory, Set<String> directoriesVisited, IProgressMonitor monitor) { if (monitor.isCanceled()) { return false; } monitor.subTask(NLS.bind( UIText.WizardProjectsImportPage_CheckingMessage, directory .getPath())); File[] contents = directory.listFiles(); if (contents == null) return false; if (directoriesVisited == null) { directoriesVisited = new HashSet<String>(); try { directoriesVisited.add(directory.getCanonicalPath()); } catch (IOException exception) { StatusManager.getManager() .handle( new Status(IStatus.ERROR, Activator .getPluginId(), exception .getLocalizedMessage(), exception)); } } final String dotProject = IProjectDescription.DESCRIPTION_FILE_NAME; for (int i = 0; i < contents.length; i++) { File file = contents[i]; if (file.isFile() && file.getName().equals(dotProject)) { files.add(file.getParentFile()); return true; } } for (int i = 0; i < contents.length; i++) { if (contents[i].isDirectory()) { if (!contents[i].getName().equals(".metadata")) { try { String canonicalPath = contents[i] .getCanonicalPath(); if (!directoriesVisited.add(canonicalPath)) { continue; } } catch (IOException exception) { StatusManager.getManager().handle( new Status(IStatus.ERROR, Activator .getPluginId(), exception .getLocalizedMessage(), exception)); } collectProjectFilesFromDirectory(files, contents[i], directoriesVisited, monitor); } } } return true; }

Target:
private boolean collectProjectFilesFromDirectory( Collection<File> files, File directory, Set<String> directoriesVisited, IProgressMonitor monitor) { if (monitor.isCanceled()) { return false; } monitor.subTask(NLS.bind( RepositoryViewUITexts.RepositoriesView_Checking_Message, directory.getPath())); File[] contents = directory.listFiles(); if (contents == null) return false; final String dotProject = IProjectDescription.DESCRIPTION_FILE_NAME; for (int i = 0; i < contents.length; i++) { File file = contents[i]; if (file.isFile() && file.getName().equals(dotProject)) { files.add(file.getParentFile()); return true; } } for (int i = 0; i < contents.length; i++) { if (contents[i].isDirectory()) { if (!contents[i].getName().equals( GitProjectsImportPage.METADATA_FOLDER)) { try { String canonicalPath = contents[i] .getCanonicalPath(); if (!directoriesVisited.add(canonicalPath)) { continue; } } catch (IOException exception) { StatusManager.getManager().handle( new Status(IStatus.ERROR, Activator .getPluginId(), exception .getLocalizedMessage(), exception)); } collectProjectFilesFromDirectory(files, contents[i], directoriesVisited, monitor); } } } return true; }
Source:
public TableInstance<RelationalTableDefinition> createImmutable(RelationalTableDefinition tableDefinition, TableHandle tableHandle) { TableName tableName = createImmutableTableName(tableHandle); checkArgument(tableName.getSchema().isPresent(), "Cassandra requires table with schema"); if (!queryExecutor.tableExists(tableName.getSchema().get(), tableName.getSchemalessNameInDatabase())) { if (!skipCreateSchema) { queryExecutor.executeQuery(format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", tableName.getSchema().get())); } executeQueryIgnoreTypeError(tableDefinition.getCreateTableDDL(tableName.getNameInDatabase())); RelationalDataSource dataSource = tableDefinition.getDataSource(); insertData(tableName, dataSource); } return new CassandraTableInstance(tableName, tableDefinition); }

Target:
public TableInstance<RelationalTableDefinition> createImmutable(RelationalTableDefinition tableDefinition, TableHandle tableHandle) { TableName tableName = createImmutableTableName(tableHandle); if (!queryExecutor.tableExists(tableName.getSchema().get(), tableName.getSchemalessNameInDatabase())) { if (!skipCreateSchema) { queryExecutor.executeQuery(format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", tableName.getSchema().get())); } executeQueryIgnoreTypeError(tableDefinition.getCreateTableDDL(tableName.getNameInDatabase())); RelationalDataSource dataSource = tableDefinition.getDataSource(); insertData(tableName, dataSource); } return new CassandraTableInstance(tableName, tableDefinition); }
Source:
public static boolean isHealingRequired(GlusterVolumeEntity volume) { for (GlusterBrickEntity brick : volume.getBricks()) { if (brick.getUnSyncedEntries() != null && brick.getUnSyncedEntries() > 0) { return true; } } return false; }

Target:
public static boolean isHealingRequired(GlusterVolumeEntity volume) { for (GlusterBrickEntity brick : volume.getBricks()) { if (brick.getUnSyncedEntries() > 0) { return true; } } return false; }
Source:
public int hashCode() { return Objects.hash(id); }

Target:
public int hashCode() { return Objects.hash(id, title, description, start, end, registrationStart, registrationEnd, registrationLimit); }
Source:
public Attribute getAttributeById(PerunSession sess, Host host, int id) throws InternalErrorException, AttributeNotExistsException { Attribute attributesCache = null; if(!CacheManager.isCacheDisabled()) { Attribute attr = perun.getCacheManager().getAttributeById(id, new Holder(host.getId(), Holder.HolderType.HOST), null); attributesCache = setValueOfAttribute(sess, attr, host, null); } try { Attribute attributesDB = jdbc.queryForObject("select " + getAttributeMappingSelectQuery("host_attr_values") + " from attr_names left join host_attr_values on id=attr_id and host_id=? where id=?", new SingleBeanAttributeRowMapper<>(sess, this, host), host.getId(), id); String message = "The attributes do not match, attribute from cache is: " + attributesCache + " while attribute from db is: " + attributesDB + " the attribute belongs to " + host + " and its id is " + id; compareAttributeFromCacheAndDB(attributesCache, attributesDB, message); return attributesDB; } catch (EmptyResultDataAccessException ex) { throw new AttributeNotExistsException("Attribute id= \"" + id + "\"", ex); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }

Target:
public Attribute getAttributeById(PerunSession sess, Host host, int id) throws InternalErrorException, AttributeNotExistsException { Attribute attributesCache = null; if(!CacheManager.isCacheDisabled()) { Attribute attr = perun.getCacheManager().getAttributeById(id, new Holder(host.getId(), Holder.HolderType.HOST), null); attributesCache = setValueOfAttribute(sess, attr, host, null); } try { Attribute attributesDB = jdbc.queryForObject("select " + getAttributeMappingSelectQuery("host_attr_values") + " from attr_names left join host_attr_values on id=attr_id and host_id=? where id=?", new SingleBeanAttributeRowMapper<>(sess, this, host), host.getId(), id); compareAttributeFromCacheAndDB(attributesCache, attributesDB, host, null); return attributesDB; } catch (EmptyResultDataAccessException ex) { throw new AttributeNotExistsException("Attribute id= \"" + id + "\"", ex); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
protected void sendStreamOpen() throws NotConnectedException, InterruptedException { CharSequence to = getXMPPServiceDomain(); CharSequence from = null; CharSequence localpart = config.getUsername(); if (localpart != null) { from = XmppStringUtils.completeJidFrom(localpart, to); } String id = getStreamId(); sendNonza(new StreamOpen(to, from, id, config.getLanguage().toString().replace("_", "-"), StreamOpen.StreamContentNamespace.client)); }

Target:
protected void sendStreamOpen() throws NotConnectedException, InterruptedException { CharSequence to = getXMPPServiceDomain(); CharSequence from = null; CharSequence localpart = config.getUsername(); if (localpart != null) { from = XmppStringUtils.completeJidFrom(localpart, to); } String id = getStreamId(); sendNonza(new StreamOpen(to, from, id, config.getXmlLang(), StreamOpen.StreamContentNamespace.client)); }
Source:
private void commitFile(TopicPartition topicPart) throws IOException { long offset; if (offsets.containsKey(topicPart)) { offset = offsets.get(topicPart) + recordCounters.get(topicPart); } else { offset = recordCounters.get(topicPart) - 1; } offsets.put(topicPart, offset); String tempFileName = FileUtils.tempFileName(url, topicsDir, topicPart); String finalFileName = FileUtils.fileName(url, topicsDir, topicPart, offset); FileUtils.renameFile(fs, tempFileName, finalFileName); }

Target:
private void commitFile(TopicPartition topicPart) throws IOException { long offset; offset = offsets.get(topicPart) + recordCounters.get(topicPart); offsets.put(topicPart, offset); String tempFileName = FileUtils.tempFileName(url, topicsDir, topicPart); String finalFileName = FileUtils.committedFileName(url, topicsDir, topicPart, offset); FileUtils.renameFile(fs, tempFileName, finalFileName); }
Source:
public SqlNode getCastSpec(RelDataType type) { if (type instanceof BasicSqlType) { int maxPrecision = -1; switch (type.getSqlTypeName()) { case VARCHAR: case CHAR: maxPrecision = getTypeSystem().getMaxPrecision(type.getSqlTypeName()); } if (type.getPrecision() == RelDataType.PRECISION_NOT_SPECIFIED) { type = allowTypeWithUnspecifiedPrecision(type) ? type : new SqlTypeFactoryImpl(getTypeSystem()).createSqlType(type.getSqlTypeName()); } String charSet = type.getCharset() != null && supportsCharSet() ? type.getCharset().name() : null; return SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision); } return SqlTypeUtil.convertTypeToSpec(type); }

Target:
public SqlNode getCastSpec(RelDataType type) { if (type instanceof BasicSqlType) { int maxPrecision = -1; switch (type.getSqlTypeName()) { case VARCHAR: case CHAR: maxPrecision = getTypeSystem().getMaxPrecision(type.getSqlTypeName()); } String charSet = type.getCharset() != null && supportsCharSet() ? type.getCharset().name() : null; if (type.getPrecision() == RelDataType.PRECISION_NOT_SPECIFIED && !allowsTypeWithUnspecifiedPrecision(type)) { return SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision, getTypeSystem().getDefaultPrecision(type.getSqlTypeName())); } return SqlTypeUtil.convertTypeToSpec(type, charSet, maxPrecision); } return SqlTypeUtil.convertTypeToSpec(type); }
Source:
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { GlobalTransaction gtx = ctx.getGlobalTransaction(); if (!ctx.isOriginLocal()) { if (txTable.isTransactionCompleted(gtx)) { log.tracef("Transaction %s already completed, skipping commit", gtx); return null; } RemoteTransaction remoteTx = (RemoteTransaction) ctx.getCacheTransaction(); if (trace) { log.tracef("Remote tx topology id %d and command topology is %d", remoteTx.lookedUpEntriesTopology(), command.getTopologyId()); } if (remoteTx.lookedUpEntriesTopology() < command.getTopologyId()) { PrepareCommand prepareCommand; if (useVersioning) { prepareCommand = commandsFactory.buildVersionedPrepareCommand(ctx.getGlobalTransaction(), ctx.getModifications(), false); } else { prepareCommand = commandsFactory.buildPrepareCommand(ctx.getGlobalTransaction(), ctx.getModifications(), false); } commandsFactory.initializeReplicableCommand(prepareCommand, true); prepareCommand.setOrigin(ctx.getOrigin()); log.tracef("Replaying the transactions received as a result of state transfer %s", prepareCommand); visitPrepareCommand(ctx, prepareCommand); } txTable.markTransactionCompleted(gtx); } if (this.statisticsEnabled) commits.incrementAndGet(); Object result = invokeNextInterceptor(ctx, command); if (!ctx.isOriginLocal() || isTotalOrder) { txTable.remoteTransactionCommitted(gtx, false); } return result; }

Target:
public Object visitCommitCommand(TxInvocationContext ctx, CommitCommand command) throws Throwable { GlobalTransaction gtx = ctx.getGlobalTransaction(); if (!ctx.isOriginLocal()) { if (txTable.isTransactionCompleted(gtx)) { if (trace) log.tracef("Transaction %s already completed, skipping commit", gtx); return null; } RemoteTransaction remoteTx = (RemoteTransaction) ctx.getCacheTransaction(); if (trace) { log.tracef("Remote tx topology id %d and command topology is %d", remoteTx.lookedUpEntriesTopology(), command.getTopologyId()); } if (remoteTx.lookedUpEntriesTopology() < command.getTopologyId()) { PrepareCommand prepareCommand; if (useVersioning) { prepareCommand = commandsFactory.buildVersionedPrepareCommand(ctx.getGlobalTransaction(), ctx.getModifications(), false); } else { prepareCommand = commandsFactory.buildPrepareCommand(ctx.getGlobalTransaction(), ctx.getModifications(), false); } commandsFactory.initializeReplicableCommand(prepareCommand, true); prepareCommand.setOrigin(ctx.getOrigin()); if (trace) log.tracef("Replaying the transactions received as a result of state transfer %s", prepareCommand); visitPrepareCommand(ctx, prepareCommand); } txTable.markTransactionCompleted(gtx); } if (this.statisticsEnabled) commits.incrementAndGet(); Object result = invokeNextInterceptor(ctx, command); if (!ctx.isOriginLocal() || isTotalOrder) { txTable.remoteTransactionCommitted(gtx, false); } return result; }
Source:
private static void installScripts(IRemoteConnection remoteConnection) throws IOException { System.out.println("Install Scripts is being attempted"); System.out.println(Scripts.INSTALL_PTP_SCRIPTS); String[] installCommand = {"perl","-e",Scripts.INSTALL_PTP_SCRIPTS}; final IRemoteProcessBuilder install = remoteConnection.getProcessBuilder(installCommand); install.redirectErrorStream(); IRemoteProcess installProc = install.start(); InputStream in = installProc.getInputStream(); byte[] buf = new byte[512]; while(true) { int n = in.read(buf,0,buf.length); if(n <= 0) break; System.out.write(buf,0,n); } in.close(); }

Target:
private static void installScripts(IRemoteConnection remoteConnection) throws IOException { String[] installCommand = {"perl","-e",Scripts.INSTALL_PTP_SCRIPTS}; final IRemoteProcessBuilder install = remoteConnection.getProcessBuilder(installCommand); install.redirectErrorStream(); IRemoteProcess installProc = install.start(); InputStream in = installProc.getInputStream(); byte[] buf = new byte[512]; while(true) { int n = in.read(buf,0,buf.length); if(n <= 0) break; System.out.write(buf,0,n); } in.close(); }
Source:
public void testCostBalancerMultithreadStrategy() throws InterruptedException { DataSegment segment = getSegment(1000); BalancerStrategy strategy = new CostBalancerMultithreadStrategy(DateTime.now(DateTimeZone.UTC), 8); ServerHolder holder = strategy.findNewSegmentHomeReplicator(segment, serverHolderList); Assert.assertNotNull("Should be able to find a place for new segment!!", holder); Assert.assertEquals("Best Server should be BEST_SERVER", "BEST_SERVER", holder.getServer().getName()); }

Target:
public void testCostBalancerMultithreadStrategy() throws InterruptedException { setupDummyCluster(10, 20); DataSegment segment = getSegment(1000); BalancerStrategy strategy = new CostBalancerStrategy(DateTime.now(DateTimeZone.UTC), 1); ServerHolder holder = strategy.findNewSegmentHomeReplicator(segment, serverHolderList); Assert.assertNotNull("Should be able to find a place for new segment!!", holder); Assert.assertEquals("Best Server should be BEST_SERVER", "BEST_SERVER", holder.getServer().getName()); }
Source:
private void restore(final CaseManagementShapeView ghost) { if (state.getOriginalParent().isPresent() && state.getOriginalIndex().isPresent()) { final WiresContainer originalParent = state.getOriginalParent().get(); final int originalIndex = state.getOriginalIndex().get(); restore(ghost, originalParent, originalIndex); } }

Target:
private void restore(final CaseManagementShapeView ghost) { state.getOriginalParent().ifPresent(originalParent -> state.getOriginalIndex().ifPresent(originalIndex -> restore(ghost, originalParent, originalIndex) ) ); }
Source:
public static List<String> getPostgresCategoryString(String searchString, Map<String, String> mapPrefix, String prefixSplit ) { List<String> finalList = new ArrayList<String>(); if (searchString == null || !(searchString.trim().length() > 0)) { finalList.add( "{}" ); return finalList; } List<String> categories = parse(searchString.trim().toLowerCase()); List<String> catHolder = new ArrayList<String>(); for( String cat : categories ) { if (prefixSplit != null ) { int index = cat.indexOf( prefixSplit ); if ( index != -1 ) { String prefix = cat.substring( 0, index ); String value = cat.substring( index + 1 ); if ( mapPrefix.containsKey( prefix ) ) { addToFinalList( finalList, catHolder ); finalList.add( value ); } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } addToFinalList( finalList, catHolder ); return finalList; }

Target:
public static List<String> getPostgresCategoryString(String searchString, Map<String, String> mapPrefix, String prefixSplit ) { List<String> finalList = new ArrayList<String>(); if (searchString == null || !(searchString.trim().length() > 0)) { finalList.add( "{}" ); return finalList; } List<String> categories = parse(searchString.trim().toLowerCase()); List<String> catHolder = new ArrayList<String>(); for( String cat : categories ) { if (prefixSplit != null ) { int index = cat.indexOf( prefixSplit ); if ( index != -1 ) { String prefix = cat.substring( 0, index ); String value = cat.substring( index + prefixSplit.length() ); if ( mapPrefix.containsKey( prefix ) ) { addToFinalList( finalList, catHolder ); finalList.add( value ); } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } addToFinalList( finalList, catHolder ); return finalList; }
Source:
public String toStringForLogging() { StringBuilder sb = new StringBuilder(); if(correlationId != null){ sb.append("Corrolation ID: "); sb.append(correlationId); sb.append(", "); } if(jobId != null){ sb.append("Job ID: "); sb.append(jobId.toString()); sb.append(", "); } if(callStack != null){ sb.append("Call Stack: "); sb.append(callStack); sb.append(", "); } if(customEventId != -1){ sb.append("Custom Event ID: "); sb.append(customEventId); sb.append(", "); } if(message != null){ sb.append("Message: "); sb.append(message); } return sb.toString(); }

Target:
public String toStringForLogging() { StringBuilder sb = new StringBuilder(); sb.append("Correlation ID: "); sb.append(correlationId); sb.append(", "); if(jobId != null){ sb.append("Job ID: "); sb.append(jobId.toString()); sb.append(", "); } sb.append("Call Stack: "); sb.append(callStack); sb.append(", "); sb.append("Custom Event ID: "); sb.append(customEventId); sb.append(", "); sb.append("Message: "); sb.append(message); return sb.toString(); }
Source:
public Map<String,String> getFlattened(){ Map<String,String> returnVal = new TreeMap<String,String>(); for (Props curr = this; curr != null; curr = curr.getParent()) { for (String key : curr.localKeySet()) { if (!returnVal.containsKey(key)){ returnVal.put(key, curr.get(key)); } } } return returnVal; }

Target:
public Map<String,String> getFlattened(){ TreeMap<String,String> returnVal = new TreeMap<String,String>(); returnVal.putAll(getMapByPrefix("")); return returnVal; }
Source:
public void sendBinary(ByteBuffer buf) { if (channel == null) { logger.error("Channel is null. Cannot send text."); throw new NullPointerException("Cannot find the channel to write"); } channel.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(buf))); }

Target:
public void sendBinary(ByteBuffer buf) throws IOException { if (channel == null) { logger.error("Channel is null. Cannot send text."); throw new IllegalArgumentException("Cannot find the channel to write"); } channel.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(buf))); }
Source:
public String runScript(Script script, Map<String, Object> parameters) { String jsScript = script.getContent(); Object scriptResult; try { scriptResult = jsScriptExecutor.executeScript(jsScript, parameters); } catch (ScriptExecutionException see) { scriptResult = see.getLocalizedMessage(); } return scriptResult != null ? scriptResult.toString() : null; }

Target:
public String runScript(Script script, Map<String, Object> parameters) { String jsScript = script.getContent(); Object scriptResult = jsMagmaScriptExecutor.executeScript(jsScript, parameters); return scriptResult != null ? scriptResult.toString() : null; }
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartTimerEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartTimerEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, ""); }

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartTimerEvent emptyTop = getStartNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, StartTimerEvent.class); assertGeneralSet(emptyTop.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertTimerEventEmpty(emptyTop.getExecutionSet(), NON_INTERRUPTING, EMPTY_VALUE); }
Source:
public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { for (SystemTablesProvider delegate : delegates) { Optional<SystemTable> table = delegate.getSystemTable(session, tableName); if (table.isPresent()) { return table; } } return Optional.empty(); }

Target:
public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { return delegates.stream() .map(delegate -> delegate.getSystemTable(session, tableName)) .filter(Optional::isPresent) .map(Optional::get) .collect(toOptional()); }
Source:
private RexNode simplifyIsPredicate(SqlKind kind, RexNode a) { if (!RexUtil.isReferenceOrAccess(a, true)) { return null; } for (RexNode p : predicates.pulledUpPredicates) { IsPredicate pred = IsPredicate.of(p); if (pred == null || !a.toString().equals(pred.ref.toString())) { continue; } if (kind == pred.kind) { return rexBuilder.makeLiteral(true); } else if (kind.negate() == pred.kind) { return rexBuilder.makeLiteral(false); } } return null; }

Target:
private RexNode simplifyIsPredicate(SqlKind kind, RexNode a) { if (!RexUtil.isReferenceOrAccess(a, true)) { return null; } for (RexNode p : predicates.pulledUpPredicates) { IsPredicate pred = IsPredicate.of(p); if (pred == null || !a.toString().equals(pred.ref.toString())) { continue; } if (kind == pred.kind) { return rexBuilder.makeLiteral(true); } } return null; }
Source:
protected void onAfterSave(Object entity) { BlobHardRef ref = getRef(entity); if (ref.changed) { BlobStorageSpace storageSpace = ref.getBlob().getStorageSpace(); String uniqueName = ((BaseEntity<?>) entity).getUniqueName(); if (ref.isFilled()) { storageSpace.markAsUsed(uniqueName, getName(), ref.getKey()); } storageSpace.deleteReferencedBlobs(uniqueName, getName(), ref.getKey()); } ref.changed = false; }

Target:
protected void onAfterSave(Object entity) { BlobHardRef ref = getRef(entity); if (ref.changed) { BlobStorageSpace storageSpace = ref.getStorageSpace(); String uniqueName = ((BaseEntity<?>) entity).getUniqueName(); if (ref.isFilled()) { storageSpace.markAsUsed(uniqueName, getName(), ref.getKey()); } storageSpace.deleteReferencedBlobs(uniqueName, getName(), ref.getKey()); } ref.changed = false; }
Source:
public String getCommitMessage() { String text = getText(); text = Utils.normalizeLineEndings(text); if (shouldHardWrap()) { text = hardWrap(text); } return text; }

Target:
public String getCommitMessage() { String text = getText(); text = Utils.normalizeLineEndings(text); if (shouldHardWrap()) text = hardWrap(text); return text; }
Source:
public void installPluginFromStream(String originalName, InputStream in) throws IOException, PluginInstallException { String fileName = originalName; if (!(fileName.endsWith(".jar") || fileName.endsWith(".js"))) { throw new ParserInitializationException( "Can only install files with '.jar' and '.js' extension"); } File tmp = asTemp(in, ".next_" + fileName + "_", ".tmp", pluginsDir); String name = Objects.firstNonNull(getGerritPluginName(tmp), nameOf(fileName)); if (!originalName.equals(name)) { log.warn(String.format("Plugin provides its own name: <%s>," + " use it instead of the input name: <%s>", name, originalName)); } File dst = new File(pluginsDir, name); synchronized (this) { Plugin active = running.get(name); if (active != null) { name = active.getSrcFile().getName(); log.info(String.format("Replacing plugin %s", active.getName())); File old = new File(pluginsDir, ".last_" + name); old.delete(); active.getSrcFile().renameTo(old); } new File(pluginsDir, name + ".disabled").delete(); tmp.renameTo(dst); try { Plugin plugin = runPlugin(name, dst, active); if (active == null) { log.info(String.format("Installed plugin %s", plugin.getName())); } } catch (PluginInstallException e) { dst.delete(); throw e; } cleanInBackground(); } }

Target:
public void installPluginFromStream(String originalName, InputStream in) throws IOException, PluginInstallException { String fileName = originalName; if (!(fileName.endsWith(".jar") || fileName.endsWith(".js"))) { throw new ParserInitializationException( "Can only install files with '.jar' or '.js' extension"); } File tmp = asTemp(in, ".next_" + fileName + "_", ".tmp", pluginsDir); String name = Objects.firstNonNull(getGerritPluginName(tmp), nameOf(fileName)); if (!originalName.equals(name)) { log.warn(String.format("Plugin provides its own name: <%s>," + " use it instead of the input name: <%s>", name, originalName)); } File dst = new File(pluginsDir, name); synchronized (this) { Plugin active = running.get(name); if (active != null) { name = active.getSrcFile().getName(); log.info(String.format("Replacing plugin %s", active.getName())); File old = new File(pluginsDir, ".last_" + name); old.delete(); active.getSrcFile().renameTo(old); } new File(pluginsDir, name + ".disabled").delete(); tmp.renameTo(dst); try { Plugin plugin = runPlugin(name, dst, active); if (active == null) { log.info(String.format("Installed plugin %s", plugin.getName())); } } catch (PluginInstallException e) { dst.delete(); throw e; } cleanInBackground(); } }
Source:
private static void checkConfig(Config cfg) { Set<String> keys = new HashSet<>(); for (Table t : Table.values()) { keys.add(t.name().toLowerCase()); } for (String t : cfg.getSubsections(NOTEDB)) { checkArgument(keys.contains(t.toLowerCase()), "invalid notedb table: %s", t); for (String key : cfg.getNames(NOTEDB, t)) { String lk = key.toLowerCase(); checkArgument(lk.equals(WRITE) || lk.equals(READ), "invalid notedb key: %s.%s", t, key); } boolean write = cfg.getBoolean(NOTEDB, t, WRITE, false); boolean read = cfg.getBoolean(NOTEDB, t, READ, false); checkArgument(!(read && !write), "must have write enabled when read enabled: %s", t); } }

Target:
private static void checkConfig(Config cfg) { Set<String> keys = new HashSet<>(); for (Table t : Table.values()) { keys.add(t.key()); } for (String t : cfg.getSubsections(NOTEDB)) { checkArgument(keys.contains(t.toLowerCase()), "invalid notedb table: %s", t); for (String key : cfg.getNames(NOTEDB, t)) { String lk = key.toLowerCase(); checkArgument(lk.equals(WRITE) || lk.equals(READ), "invalid notedb key: %s.%s", t, key); } boolean write = cfg.getBoolean(NOTEDB, t, WRITE, false); boolean read = cfg.getBoolean(NOTEDB, t, READ, false); checkArgument(!(read && !write), "must have write enabled when read enabled: %s", t); } }
Source:
public KHyperLogLog(int maxSize, int hllBuckets, Long2ObjectSortedMap<HyperLogLog> minhash) { this.maxSize = maxSize; this.hllBuckets = hllBuckets; this.minhash = requireNonNull(minhash, "minhash is null"); hllsTotalEstimatedInMemorySize = 0; hllsTotalEstimatedSerializedSize = 0; for (HyperLogLog hll : minhash.values()) { increaseTotalHllSize(hll); } }

Target:
public KHyperLogLog(int maxSize, int hllBuckets, Long2ObjectSortedMap<HyperLogLog> minhash) { this.maxSize = maxSize; this.hllBuckets = hllBuckets; this.minhash = requireNonNull(minhash, "minhash is null"); minhash.values().forEach(this::increaseTotalHllSize); }
Source:
protected AutoFixableRuleViolation createRuleViolation(Rule rule, RuleContext ruleContext, Node node, String message, int beginLine, int endLine, Class<? extends RuleViolationFix> ruleViolationFixClass) { return null; }

Target:
protected AutoFixableRuleViolation createRuleViolation(Rule rule, RuleContext ruleContext, Node node, String message, int beginLine, int endLine, Class<? extends RuleViolationFix> ruleViolationFixClass) { AutoFixableParametricRuleViolation<EcmascriptNode> rViolation = new AutoFixableParametricRuleViolation<>(rule, ruleContext, (EcmascriptNode) node, message, ruleViolationFixClass); rViolation.setLines(beginLine, endLine); return rViolation; }
Source:
private Profile() { try (LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"))) { while (r.readLine() != null) { } maxIndex = r.getLineNumber(); count = new int[maxIndex]; time = new int[maxIndex]; lastTime = System.nanoTime(); Runtime.getRuntime().addShutdownHook(this); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }

Target:
private Profile() { try (LineNumberReader r = new LineNumberReader(new FileReader("profile.txt"))) { while (r.readLine() != null) { } maxIndex = r.getLineNumber(); count = new int[maxIndex]; time = new int[maxIndex]; lastTimeNs = System.nanoTime(); Runtime.getRuntime().addShutdownHook(this); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
Source:
public static boolean currentUserHasRole(String... roles) { if (roles == null || roles.length == 0) return false; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); if (authorities == null) throw new IllegalStateException("No current user logged in"); for (String role : roles) { for (GrantedAuthority grantedAuthority : authorities) { if (role.equals(grantedAuthority.getAuthority())) return true; } } } return false; }

Target:
public static boolean currentUserHasRole(String... roles) { if (roles == null || roles.length == 0) return false; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null) { Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); if (authorities == null) throw new IllegalStateException("No user currently logged in"); for (String role : roles) { for (GrantedAuthority grantedAuthority : authorities) { if (role.equals(grantedAuthority.getAuthority())) return true; } } } return false; }
Source:
B firstBatch() throws RetryableException; B nextBatch(B lastBatch) throws RetryableException; } public interface Batch { List<Change> changes(); boolean noChanges(); String advancedUnits(); long advanced(); String leftOffHuman(); Date leftOffDate(); boolean last(); abstract class AbstractDefaultImplementation implements Batch { private final ImmutableList<Change> changes; private final long advanced; private final Object leftOff; public AbstractDefaultImplementation(ImmutableList<Change> changes, long advanced, Object leftOff) { this.changes = checkNotNull(changes); this.advanced = advanced; this.leftOff = leftOff; } @Override public List<Change> changes() { return changes; } @Override public boolean noChanges() { return changes.isEmpty(); } @Override public long advanced() { return advanced; } @Override public String leftOffHuman() { return leftOff.toString(); } @Override public boolean last() { return false; } } }

Target:
B firstBatch() throws RetryableException; B nextBatch(B lastBatch) throws RetryableException; } public interface Batch { List<Change> changes(); boolean hasAnyChanges(); String advancedUnits(); long advanced(); String leftOffHuman(); Date leftOffDate(); boolean last(); abstract class AbstractDefaultImplementation implements Batch { private final ImmutableList<Change> changes; private final long advanced; private final Object leftOff; public AbstractDefaultImplementation(ImmutableList<Change> changes, long advanced, Object leftOff) { this.changes = checkNotNull(changes); this.advanced = advanced; this.leftOff = leftOff; } @Override public List<Change> changes() { return changes; } @Override public boolean hasAnyChanges() { return !changes.isEmpty(); } @Override public long advanced() { return advanced; } @Override public String leftOffHuman() { return leftOff.toString(); } @Override public boolean last() { return false; } } }
Source:
public void executeQueryCommand() { clusterId = getParameters().getClusterId(); Guid volumeId = getParameters().getVolumeId(); if (volumeId != null) { volume = getGlusterVolumeDao().getById(volumeId); if (volume == null) { throw new RuntimeException(VdcBllMessages.GLUSTER_VOLUME_ID_INVALID.toString()); } } if (clusterId == null) { clusterId = volume.getClusterId(); } getQueryReturnValue().setReturnValue(fetchTaskStatusDetails()); }

Target:
public void executeQueryCommand() { clusterId = getParameters().getClusterId(); volume = getGlusterVolumeDao().getById(getParameters().getVolumeId()); if (volume == null) { throw new RuntimeException(VdcBllMessages.GLUSTER_VOLUME_ID_INVALID.toString()); } if (clusterId == null) { clusterId = volume.getClusterId(); } getQueryReturnValue().setReturnValue(fetchTaskStatusDetails()); }
Source:
private URL getResource(IMetaclass metaclass, String resourcePath) { Object userControlsDisabled = this.options.get(IXWTLoader.DISABLE_USER_CONTROLS); if (!Boolean.TRUE.equals(userControlsDisabled)) { IResourceCache resourceCache = getResourceCache(); if (resourceCache == null) { return doGetResource(metaclass, resourcePath); } else { if (resourceCache.hasCached(metaclass, resourcePath)) { return resourceCache.getCachedResource(metaclass, resourcePath); } System.out.println("Do load resource "+resourcePath); URL url = doGetResource(metaclass, resourcePath); resourceCache.cacheResource(metaclass, resourcePath, url); return url; } } return null; }

Target:
private URL getResource(IMetaclass metaclass, String resourcePath) { Object userControlsDisabled = this.options.get(IXWTLoader.DISABLE_USER_CONTROLS); if (!Boolean.TRUE.equals(userControlsDisabled)) { IResourceCache resourceCache = getResourceCache(); if (resourceCache == null) { return doGetResource(metaclass, resourcePath); } else { if (resourceCache.hasCached(metaclass, resourcePath)) { return resourceCache.getCachedResource(metaclass, resourcePath); } URL url = doGetResource(metaclass, resourcePath); resourceCache.cacheResource(metaclass, resourcePath, url); return url; } } return null; }
Source:
public static int getLootingLevel(Entity target, Entity killer, DamageSource cause) { int looting = 0; if (killer instanceof EntityLivingBase) { looting = EnchantmentHelper.getLootingModifier((EntityLivingBase)killer); } if (target instanceof EntityLivingBase) { looting = net.minecraftforge.common.ForgeHooks.getLootingLevel((EntityLivingBase)target, cause, looting); } return looting; }

Target:
public static int getLootingLevel(Entity target, Entity killer, DamageSource cause) { int looting = 0; if (killer instanceof EntityLivingBase) { looting = EnchantmentHelper.getLootingModifier((EntityLivingBase)killer); } if (target instanceof EntityLivingBase) { looting = getLootingLevel((EntityLivingBase)target, cause, looting); } return looting; }
Source:
private static DetailAST findLeftCurly(DetailAST ast) { DetailAST leftCurly; if (ast.findFirstToken(TokenTypes.SLIST) == null) { leftCurly = ast.findFirstToken(TokenTypes.LCURLY); } else { leftCurly = ast.findFirstToken(TokenTypes.SLIST); } if (ast.getType() == TokenTypes.LITERAL_CASE && ast.getNextSibling() != null && "{".equals(ast.getNextSibling().getFirstChild().getText())) { leftCurly = ast.getNextSibling().getFirstChild(); } return leftCurly; }

Target:
private static DetailAST findLeftCurly(DetailAST ast) { final DetailAST leftCurly; final DetailAST slistAST = ast.findFirstToken(TokenTypes.SLIST); if (ast.getType() == TokenTypes.LITERAL_CASE && ast.getNextSibling() != null && ast.getNextSibling().getFirstChild().getType() == TokenTypes.SLIST) { leftCurly = ast.getNextSibling().getFirstChild(); } else if (slistAST == null) { leftCurly = ast.findFirstToken(TokenTypes.LCURLY); } else { leftCurly = slistAST; } return leftCurly; }
Source:
private static double chiSquareDistance(List<Long> values) { double mean = values.stream().mapToDouble(Long::doubleValue).reduce(0.0, Double::sum) / values.size(); double distances = values.stream().mapToDouble(Long::doubleValue) .reduce(0.0, (acc, nextVal) -> acc + Math.pow((nextVal - mean), 2)); return distances / mean; }

Target:
private static double chiSquareDistance(List<Long> values) { double mean = values.stream().mapToLong(x -> x).reduce(0L, Long::sum) / (double) values.size(); double distances = values.stream().mapToDouble(Long::doubleValue) .reduce(0.0, (acc, nextVal) -> acc + Math.pow(nextVal - mean, 2)); return distances / mean; }
Source:
private void configureLogCatcher() { logCatcher = new LogCatcher(); final Logger logger = Log.getLogger(); for (Handler handler : logger.getHandlers()) { logger.removeHandler(handler); } logger.addHandler(logCatcher); logger.setLevel(Level.ALL); }

Target:
public void configureLogCatcher() { logCatcher = new LogCatcher(); final Logger logger = Log.getLogger(); logger.addHandler(logCatcher); logger.setLevel(Level.ALL); }
Source:
public boolean isAPIProductAvailable(APIProductIdentifier identifier) throws APIManagementException { String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion(); try { return registry.resourceExists(path); } catch (RegistryException e) { String msg = "Failed to check availability of API Product :" + path; log.error(msg, e); throw new APIManagementException(msg, e); } }

Target:
public boolean isAPIProductAvailable(APIProductIdentifier identifier) throws APIManagementException { String path = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion(); try { return registry.resourceExists(path); } catch (RegistryException e) { String msg = "Failed to check availability of API Product :" + path; throw new APIManagementException(msg, e); } }
Source:
private static String[] mergePropertiesToCommandArray(String[] parameters, String[] cmdArray) { if (parameters != null) { cmdArray = ArrayUtils.addAll(cmdArray, parameters); } return cmdArray; }

Target:
private static String[] mergePropertiesToCommandArray(String[] parameters, String[] cmdArray) { if (parameters != null && cmdArray != null) { Object[] cmdObjectArray = ArrayUtils.addAll(cmdArray, parameters); cmdArray = Arrays.asList(cmdObjectArray).toArray(new String[cmdObjectArray.length]); } return cmdArray; }
Source:
public void processMetadata() throws TranslatorException { DescribeGlobalResult globalResult = connection.getObjects(); DescribeGlobalSObjectResult[] objects = globalResult.getSobjects(); for (DescribeGlobalSObjectResult object : objects) { addTable(object); } List<String> names = new ArrayList<String>(); for (String name : this.tableMap.keySet()) { names.add(name); if (names.size() < 100) { continue; } getColumnsAndRelationships(names); } if (!names.isEmpty()) { getColumnsAndRelationships(names); } addRelationships(); for (Table table:this.metadataFactory.getSchema().getTables().values()) { if (importStatistics) { try { String name = table.getNameInSource(); if (name == null) { name = table.getName(); } Long val = this.connection.getCardinality(name); if (val != null) { table.setCardinality(val); } } catch (Exception e) { LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Could not get cardinality for", table); } } if (table.getPrimaryKey() == null) { continue; } for (Column column:table.getPrimaryKey().getColumns()) { if (!column.isUpdatable()) { column.setAutoIncremented(true); } } } }

Target:
public void processMetadata() throws TranslatorException { DescribeGlobalResult globalResult = connection.getObjects(); DescribeGlobalSObjectResult[] objects = globalResult.getSobjects(); for (DescribeGlobalSObjectResult object : objects) { addTable(object); } List<String> names = new ArrayList<String>(); for (String name : this.tableMap.keySet()) { names.add(name); if (names.size() < 100) { continue; } getColumnsAndRelationships(names); } if (!names.isEmpty()) { getColumnsAndRelationships(names); } addRelationships(); for (Table table:this.metadataFactory.getSchema().getTables().values()) { if (importStatistics) { try { Long val = this.connection.getCardinality(table.getSourceName()); if (val != null) { table.setCardinality(val); } } catch (Exception e) { LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Could not get cardinality for", table); } } if (table.getPrimaryKey() == null) { continue; } for (Column column:table.getPrimaryKey().getColumns()) { if (!column.isUpdatable()) { column.setAutoIncremented(true); } } } }
Source:
public void parse(String delim, String itemToken) { final FromItem fromItem; final int parenthesisStart = itemToken.indexOf('('); if (parenthesisStart != -1) { if (parenthesisStart != 0) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected parenthesis to start at first character."); } final int parenthesisEnd = itemToken.indexOf(')', parenthesisStart); if (parenthesisEnd == -1) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected end parenthesis."); } final String subQueryString = itemToken.substring(parenthesisStart + 1, parenthesisEnd); logger.debug("Parsing sub-query: {}", subQueryString); final Query subQuery = new QueryParser(_dataContext, subQueryString).parse(); fromItem = new FromItem(subQuery); final String alias = itemToken.substring(parenthesisEnd + 1).trim(); if (!alias.isEmpty()) { fromItem.setAlias(alias); } } else if (itemToken.toUpperCase().indexOf(" JOIN ") != -1) { if(itemToken.split("(?i) JOIN ").length == 2) { fromItem = parseJoinItem(null,itemToken,new HashSet<FromItem>()); } else { fromItem = parseAllJoinItems(itemToken); } } else { fromItem = parseTableItem(itemToken); } _query.from(fromItem); }

Target:
public void parse(String delim, String itemToken) { final FromItem fromItem; final int parenthesisStart = itemToken.indexOf('('); if (parenthesisStart != -1) { if (parenthesisStart != 0) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected parenthesis to start at first character."); } final int parenthesisEnd = itemToken.indexOf(')', parenthesisStart); if (parenthesisEnd == -1) { throw new QueryParserException("Not capable of parsing FROM token: " + itemToken + ". Expected end parenthesis."); } final String subQueryString = itemToken.substring(parenthesisStart + 1, parenthesisEnd); logger.debug("Parsing sub-query: {}", subQueryString); final Query subQuery = new QueryParser(_dataContext, subQueryString).parse(); fromItem = new FromItem(subQuery); final String alias = itemToken.substring(parenthesisEnd + 1).trim(); if (!alias.isEmpty()) { fromItem.setAlias(alias); } } else if (itemToken.toUpperCase().indexOf(" JOIN ") != -1) { fromItem = parseAllJoinItems(itemToken); } else { fromItem = parseTableItem(itemToken); } _query.from(fromItem); }
Source:
private @NonNull ArrayList<SocketKeepalive> createConcurrentNattSocketKeepalives( @NonNull Network network, int requestCount, @NonNull TestSocketKeepaliveCallback callback) throws Exception { final Executor executor = mContext.getMainExecutor(); final IpSecManager mIpSec = (IpSecManager) mContext.getSystemService(Context.IPSEC_SERVICE); final UdpEncapsulationSocket nattSocket = mIpSec.openUdpEncapsulationSocket(); final InetAddress srcAddr = getFirstV4Address(network); final InetAddress dstAddr = getAddrByName(TEST_HOST, AF_INET); assertNotNull(srcAddr); assertNotNull(dstAddr); ArrayList<SocketKeepalive> result = null; try { result = createConcurrentKeepalivesOfType(requestCount, callback, () -> mCm.createSocketKeepalive(network, nattSocket, srcAddr, dstAddr, executor, callback)); } catch (Exception e) { Log.w(TAG, "Failed to create concurrent keepalives", e); } finally { nattSocket.close(); } return result; }

Target:
private @NonNull ArrayList<SocketKeepalive> createConcurrentNattSocketKeepalives( @NonNull Network network, int requestCount, @NonNull TestSocketKeepaliveCallback callback) throws Exception { final Executor executor = mContext.getMainExecutor(); final IpSecManager mIpSec = (IpSecManager) mContext.getSystemService(Context.IPSEC_SERVICE); final UdpEncapsulationSocket nattSocket = mIpSec.openUdpEncapsulationSocket(); final InetAddress srcAddr = getFirstV4Address(network); final InetAddress dstAddr = getAddrByName(TEST_HOST, AF_INET); assertNotNull(srcAddr); assertNotNull(dstAddr); try { return createConcurrentKeepalivesOfType(requestCount, callback, () -> mCm.createSocketKeepalive(network, nattSocket, srcAddr, dstAddr, executor, callback)); } finally { nattSocket.close(); } }
Source:
private static void checkGeneratorExpressionInArgument(List<PyArgumentTree> arguments) { List<PyArgumentTree> nonParenthesizedGeneratorExpressions = arguments.stream() .filter(arg -> arg.expression().is(Tree.Kind.GENERATOR_EXPR) && !arg.expression().firstToken().getValue().equals("(")) .collect(Collectors.toList()); if (!nonParenthesizedGeneratorExpressions.isEmpty() && arguments.size() > 1) { throw new RecognitionException(nonParenthesizedGeneratorExpressions.get(0).firstToken().getLine(), "Generator expression must be parenthesized."); } }

Target:
private static void checkGeneratorExpressionInArgument(List<PyArgumentTree> arguments) { List<PyArgumentTree> nonParenthesizedGeneratorExpressions = arguments.stream() .filter(arg -> arg.expression().is(Tree.Kind.GENERATOR_EXPR) && !arg.expression().firstToken().getValue().equals("(")) .collect(Collectors.toList()); if (!nonParenthesizedGeneratorExpressions.isEmpty() && arguments.size() > 1) { int line = nonParenthesizedGeneratorExpressions.get(0).firstToken().getLine(); throw new RecognitionException(line, "Parse error at line " + line + ": Generator expression must be parenthesized if not sole argument."); } }
Source:
public final Optional<BearerToken> getApiToken(String serviceName) { checkArgument(!Strings.isNullOrEmpty(serviceName)); Optional<ServiceConfiguration> maybeServiceConfig = getServiceConfiguration(serviceName); if (!maybeServiceConfig.isPresent()) { return defaultApiToken(); } return maybeServiceConfig.get().apiToken().or(defaultApiToken()); }

Target:
public final Optional<BearerToken> getApiToken(String serviceName) { ServiceConfiguration serviceConfig = Preconditions.checkNotNull( getServices().get(serviceName), "Unable to find the configuration for " + serviceName + "."); return serviceConfig.apiToken(); }
Source:
public ValidationResult validateCinderVolumeTypesExist() { return validate(new Callable<ValidationResult>() { @Override public ValidationResult call() { for (final CinderDisk disk : cinderDisks) { if (StringUtils.isEmpty(disk.getCinderVolumeType())) { continue; } OpenStackVolumeProviderProxy proxy = diskProxyMap.get(disk.getId()); List<CinderVolumeType> volumeTypes = proxy.getVolumeTypes(); boolean volumeTypeExists = CollectionUtils.exists(volumeTypes, new Predicate() { @Override public boolean evaluate(Object o) { return ((CinderVolumeType) o).getName().equals(disk.getCinderVolumeType()); } }); if (!volumeTypeExists) { return new ValidationResult(VdcBllMessages.CINDER_VOLUME_TYPE_NOT_EXISTS, String.format("$cinderVolumeType %s", disk.getCinderVolumeType())); } } return ValidationResult.VALID; } }); }

Target:
public ValidationResult validateCinderVolumeTypesExist() { return validate(new Callable<ValidationResult>() { @Override public ValidationResult call() { final CinderDisk disk = cinderDisks.iterator().next(); if (StringUtils.isEmpty(disk.getCinderVolumeType())) { return ValidationResult.VALID; } OpenStackVolumeProviderProxy proxy = diskProxyMap.get(disk.getId()); List<CinderVolumeType> volumeTypes = proxy.getVolumeTypes(); boolean volumeTypeExists = CollectionUtils.exists(volumeTypes, new Predicate() { @Override public boolean evaluate(Object o) { return ((CinderVolumeType) o).getName().equals(disk.getCinderVolumeType()); } }); if (!volumeTypeExists) { return new ValidationResult(VdcBllMessages.CINDER_VOLUME_TYPE_NOT_EXISTS, String.format("$cinderVolumeType %s", disk.getCinderVolumeType())); } return ValidationResult.VALID; } }); }