auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void visitVariableExpression(final VariableExpression exp) { Variable ref = exp.getAccessedVariable(); if (ref instanceof VariableExpression || ref instanceof Parameter) { makeNode("localVariable", new Runnable() { @Override public void run() { loc(exp); literal(exp.getName()); } }); } else if (ref instanceof DynamicVariable || ref instanceof PropertyNode || ref instanceof FieldNode) { if (ref instanceof FieldNode && classNode.getGetterMethod("get" + Verifier.capitalize(exp.getName())) != null) { makeNode("attribute", new Runnable() { @Override public void run() { loc(exp); makeNode("javaThis_"); visit(new ConstantExpression(exp.getName())); literal(false); } }); } else { makeNode("property", new Runnable() { @Override public void run() { loc(exp); makeNode("javaThis_"); literal(exp.getName()); } }); } } else if ("this".equals(exp.getName())) { makeNode("this_"); } else if ("super".equals(exp.getName())) { makeNode("super_", new Runnable() { @Override public void run() { literal(classNode); } }); } else { System.err.println("V: " + exp); sourceUnit.addError(new SyntaxException("Unsupported expression for CPS transformation", exp.getLineNumber(), exp.getColumnNumber())); } }

Target:
public void visitVariableExpression(final VariableExpression exp) { Variable ref = exp.getAccessedVariable(); if (ref instanceof VariableExpression || ref instanceof Parameter) { makeNode("localVariable", new Runnable() { @Override public void run() { loc(exp); literal(exp.getName()); } }); } else if (ref instanceof DynamicVariable || ref instanceof PropertyNode || ref instanceof FieldNode) { if (ref instanceof FieldNode && classNode.getGetterMethod("get" + Verifier.capitalize(exp.getName())) != null) { makeNode("attribute", new Runnable() { @Override public void run() { loc(exp); makeNode("javaThis_"); visit(new ConstantExpression(exp.getName())); literal(false); } }); } else { makeNode("property", new Runnable() { @Override public void run() { loc(exp); makeNode("javaThis_"); literal(exp.getName()); } }); } } else if ("this".equals(exp.getName())) { makeNode("this_"); } else if ("super".equals(exp.getName())) { makeNode("super_", new Runnable() { @Override public void run() { literal(classNode); } }); } else { sourceUnit.addError(new SyntaxException("Unsupported expression for CPS transformation", exp.getLineNumber(), exp.getColumnNumber())); } }
Source:
public BufferCachingGrpcDataReader create() throws IOException { AlluxioConfiguration alluxioConf = mContext.getClusterConf(); int readerBufferSizeMessages = alluxioConf .getInt(PropertyKey.USER_STREAMING_READER_BUFFER_SIZE_MESSAGES); long dataTimeoutMs = alluxioConf.getMs(PropertyKey.USER_STREAMING_DATA_TIMEOUT); CloseableResource<BlockWorkerClient> client = mContext.acquireBlockWorkerClient(mAddress); GrpcBlockingStream<ReadRequest, ReadResponse> stream; try { String desc = "BufferCachingGrpcDataReader"; if (LOG.isDebugEnabled()) { desc = MoreObjects.toStringHelper(this) .add("request", mReadRequest) .add("address", mAddress) .toString(); } stream = new GrpcBlockingStream<>(client.get()::readBlock, readerBufferSizeMessages, desc); stream.send(mReadRequest, dataTimeoutMs); } catch (Exception e) { client.close(); throw e; } return new BufferCachingGrpcDataReader(mAddress, client, dataTimeoutMs, mReadRequest, stream); }

Target:
public BufferCachingGrpcDataReader create() throws IOException { AlluxioConfiguration alluxioConf = mContext.getClusterConf(); int readerBufferSizeMessages = alluxioConf .getInt(PropertyKey.USER_STREAMING_READER_BUFFER_SIZE_MESSAGES); long dataTimeoutMs = alluxioConf.getMs(PropertyKey.USER_STREAMING_DATA_TIMEOUT); CloseableResource<BlockWorkerClient> client = mContext.acquireBlockWorkerClient(mAddress); String desc = "BufferCachingGrpcDataReader"; if (LOG.isDebugEnabled()) { desc = MoreObjects.toStringHelper(this) .add("request", mReadRequest) .add("address", mAddress) .toString(); } GrpcBlockingStream<ReadRequest, ReadResponse> stream = null; try { stream = new GrpcBlockingStream<>(client.get()::readBlock, readerBufferSizeMessages, desc); stream.send(mReadRequest, dataTimeoutMs); } catch (Exception e) { if (stream != null) { stream.close(); } client.close(); throw e; } return new BufferCachingGrpcDataReader(mAddress, client, dataTimeoutMs, mReadRequest, stream); }
Source:
public boolean isSuccessful() { return true; }

Target:
public boolean isSuccessful() { return successful; }
Source:
private void initializeGitChangeWatcher() { requestTransmitter.newRequest() .endpointId("ws-agent") .methodName("track:git-change") .noParams() .sendAndSkipResult(); }

Target:
private void initializeGitChangeWatcher() { requestTransmitter.newRequest() .endpointId("ws-agent") .methodName("track/git-change") .noParams() .sendAndSkipResult(); }
Source:
private List<String> listTables(Server server) throws MojoExecutionException { String uri = server.getDbUri(); uri = uri.substring(0, uri.lastIndexOf("/")); DBConnector connector = null; final int tableNameColumnIndex = 3; try { connector = new DBConnector(uri, server.getDbUser(), server.getDbPassword(), server.getDbName()); DatabaseMetaData md = connector.getConnection().getMetaData(); ResultSet rs = md.getTables(server.getDbName(), null, null,new String[] {"TABLE"}); List<String> tableList = new ArrayList<>(); while (rs.next()) { tableList.add(rs.getString(tableNameColumnIndex)); } return tableList; } catch (SQLException e) { return null; } finally { if (connector != null){ try { connector.close(); } catch (SQLException e) { getLog().error(e.getMessage()); } } } }

Target:
private List<String> listTables(Server server) throws MojoExecutionException { String uri = server.getDbUri(); uri = uri.substring(0, uri.lastIndexOf("/")); DBConnector connector = null; final int tableNameColumnIndex = 3; try { connector = new DBConnector(uri, server.getDbUser(), server.getDbPassword(), server.getDbName()); DatabaseMetaData md = connector.getConnection().getMetaData(); ResultSet rs = md.getTables(server.getDbName(), null, null,new String[] {"TABLE"}); List<String> tableList = new ArrayList<>(); while (rs.next()) { tableList.add(rs.getString(tableNameColumnIndex)); } return tableList; } catch (SQLException e) { throw new IllegalStateException("Failed to fetch table list from \"" + server.getDbName() + "\" database."); } finally { if (connector != null){ try { connector.close(); } catch (SQLException e) { getLog().error(e.getMessage()); } } } }
Source:
private boolean externalNetworkValid(AddNetworkValidator validator) { ProviderValidator providerValidator = new ProviderValidator(providerDao.get(getNetwork().getProvidedBy().getProviderId())); return validate(providerValidator.providerIsSet()) && validate(validator.externalNetworkNewInDataCenter()) && validate(validator.externalNetworkIsVmNetwork()) && validate(validator.externalNetworkVlanValid()) && (!getNetwork().isSetProviderPhysicalNetworkId() || validate(validator.providerPhysicalNetworkInDataCenter())); }

Target:
private boolean externalNetworkValid(AddNetworkValidator validator) { ProviderValidator providerValidator = new ProviderValidator(providerDao.get(getNetwork().getProvidedBy().getProviderId())); return validate(providerValidator.providerIsSet()) && validate(validator.externalNetworkNewInDataCenter()) && validate(validator.externalNetworkIsVmNetwork()) && validate(validator.externalNetworkVlanValid()) && (!getNetwork().getProvidedBy().isSetPhysicalNetworkId() || providerPhysicalNetworkValid(validator)); }
Source:
public void onRunFinish(boolean succeeded, BatchSourceContext context) { if (!succeeded && table != null && USE_TIMEFILTER.equals(config.fileRegex)) { String lastTimeRead = Bytes.toString(table.read(LAST_TIME_READ)); List<Date> existing = ImmutableList.of(); if (lastTimeRead != null) { existing = GSON.fromJson(lastTimeRead, ARRAYLIST_DATE_TYPE); } List<Date> failed = GSON.fromJson(datesToRead, ARRAYLIST_DATE_TYPE); failed.add(prevHour); failed.addAll(existing); table.write(LAST_TIME_READ, GSON.toJson(failed, ARRAYLIST_DATE_TYPE)); } try { if (fs.exists(path)) { fs.delete(path, true); } } catch (IOException e) { throw new IllegalArgumentException("Error deleting temporary file."); } }

Target:
public void onRunFinish(boolean succeeded, BatchSourceContext context) { if (!succeeded && table != null && USE_TIMEFILTER.equals(config.fileRegex)) { String lastTimeRead = Bytes.toString(table.read(LAST_TIME_READ)); List<Date> existing = ImmutableList.of(); if (lastTimeRead != null) { existing = GSON.fromJson(lastTimeRead, ARRAYLIST_DATE_TYPE); } List<Date> failed = GSON.fromJson(datesToRead, ARRAYLIST_DATE_TYPE); failed.add(prevHour); failed.addAll(existing); table.write(LAST_TIME_READ, GSON.toJson(failed, ARRAYLIST_DATE_TYPE)); } try { if (path != null && fs.exists(path.getParent())) { fs.delete(path.getParent(), true); } } catch (IOException e) { throw new IllegalArgumentException(String.format("Error deleting temporary file. %s.", e.getMessage()), e); } }
Source:
public Storable remove(StorableKey key) { final Future<Storable> future = executorService.submit(new DeleteCallable(key)); Storable result = null; try { result = future.get(); } catch (InterruptedException|ExecutionException e) { throw new StorageException(e); } return result; }

Target:
public Object remove(StorableKey key) { return executorService.submit(new DeleteCallable(key)); }
Source:
public List<XYSeriesConsumer> getSeries() { return checkNotNull(ImmutableList.copyOf(fSeries)); }

Target:
public List<XYSeriesConsumer> getSeries() { return fSeries; }
Source:
public static AnalyzeTextOptions map(com.azure.search.documents.indexes.implementation.models.AnalyzeRequest obj) { if (obj == null) { return null; } AnalyzeTextOptions analyzeTextOptions = null; if (obj.getTokenizer() != null) { LexicalTokenizerName tokenizer = LexicalTokenizerNameConverter.map(obj.getTokenizer()); analyzeTextOptions = new AnalyzeTextOptions(obj.getText(), tokenizer); } else { LexicalAnalyzerName analyzer = LexicalAnalyzerNameConverter.map(obj.getAnalyzer()); analyzeTextOptions = new AnalyzeTextOptions(obj.getText(), analyzer); } if (obj.getCharFilters() != null) { CharFilterName[] charFilters = obj.getCharFilters().stream() .map(CharFilterNameConverter::map) .toArray(CharFilterName[]::new); analyzeTextOptions.setCharFilters(charFilters); } if (obj.getTokenFilters() != null) { TokenFilterName[] tokenFilters = obj.getTokenFilters().stream() .map(TokenFilterNameConverter::map) .toArray(TokenFilterName[]::new); analyzeTextOptions.setTokenFilters(tokenFilters); } return analyzeTextOptions; }

Target:
public static AnalyzeTextOptions map(com.azure.search.documents.indexes.implementation.models.AnalyzeRequest obj) { if (obj == null) { return null; } AnalyzeTextOptions analyzeTextOptions = null; if (obj.getTokenizer() != null) { LexicalTokenizerName tokenizer = LexicalTokenizerNameConverter.map(obj.getTokenizer()); analyzeTextOptions = new AnalyzeTextOptions(obj.getText(), tokenizer); } else { LexicalAnalyzerName analyzer = LexicalAnalyzerNameConverter.map(obj.getAnalyzer()); analyzeTextOptions = new AnalyzeTextOptions(obj.getText(), analyzer); } if (obj.getCharFilters() != null) { analyzeTextOptions.setCharFilters(obj.getCharFilters().stream() .map(CharFilterNameConverter::map) .toArray(CharFilterName[]::new)); } if (obj.getTokenFilters() != null) { analyzeTextOptions.setTokenFilters(obj.getTokenFilters().stream() .map(TokenFilterNameConverter::map) .toArray(TokenFilterName[]::new)); } return analyzeTextOptions; }
Source:
private static AccountGroup.UUID findAdminGroup( ReviewDb db, ProjectConfig cfg) { AccountGroup.UUID adminGroup = null; List<PermissionRule> rules = cfg .getAccessSection(AccessSection.GLOBAL_CAPABILITIES) .getPermission(GlobalCapability.ADMINISTRATE_SERVER) .getRules(); for (PermissionRule rule : rules) { if (rule.getAction() == Action.ALLOW) { adminGroup = rule.getGroup().getUUID(); } } if (adminGroup == null) { throw new IllegalStateException("no administrator group found"); } return adminGroup; }

Target:
private static AccountGroup.UUID findAdminGroup( ReviewDb db, ProjectConfig cfg) { List<PermissionRule> rules = cfg .getAccessSection(AccessSection.GLOBAL_CAPABILITIES) .getPermission(GlobalCapability.ADMINISTRATE_SERVER) .getRules(); for (PermissionRule rule : rules) { if (rule.getAction() == Action.ALLOW) { return rule.getGroup().getUUID(); } } throw new IllegalStateException("no administrator group found"); }
Source:
Scheduler getScheduler() { return this.scheduler; }

Target:
public Scheduler getScheduler() { return this.scheduler; }
Source:
public void decompress(ByteBuffer in, int numBytes, ByteBuffer out) { final int maxCopy = Math.min(numBytes, out.remaining()); final ByteBuffer copyBuffer = in.duplicate(); copyBuffer.limit(copyBuffer.position() + maxCopy); out.put(copyBuffer); out.flip(); in.position(in.position() + maxCopy); }

Target:
public void decompress(ByteBuffer in, int numBytes, ByteBuffer out) { final ByteBuffer copyBuffer = in.duplicate(); copyBuffer.limit(copyBuffer.position() + numBytes); out.put(copyBuffer).flip(); in.position(in.position() + numBytes); }
Source:
public void testArraysOfNulls() { Session session = getQueryRunner().getDefaultSession(); List<String> nullArrays = ImmutableList.of("bigints", "integers", "tinyints", "smallints", "booleans", "floats"); for (String col : nullArrays) { assertQuerySucceeds(session, String.format("SELECT count(*) FROM test_arrays_of_nulls WHERE %s[1] IS NOT NULL", col)); assertQuerySucceeds(session, String.format("SELECT count(*) FROM test_arrays_of_nulls WHERE %s[1] IS NULL", col)); } }

Target:
public void testArraysOfNulls() { getQueryRunner().execute("CREATE TABLE test_arrays_of_nulls AS " + "SELECT orderkey, linenumber, " + " CAST(ARRAY[null, null, null] AS ARRAY(BIGINT)) bigints, " + " CAST(ARRAY[null, null, null] AS ARRAY(INTEGER)) integers, " + " CAST(ARRAY[null, null, null] AS ARRAY(SMALLINT)) smallints, " + " CAST(ARRAY[null, null, null] AS ARRAY(TINYINT)) tinyints, " + " CAST(ARRAY[null, null, null] AS ARRAY(BOOLEAN)) booleans, " + " CAST(ARRAY[null, null, null] AS ARRAY(TIMESTAMP)) timestamps, " + " CAST(ARRAY[null, null, null] AS ARRAY(REAL)) floats " + "FROM lineitem"); List<String> columnNames = ImmutableList.of("bigints", "integers", "tinyints", "smallints", "booleans", "floats"); try { for (String columnName : columnNames) { assertQuerySucceeds(getSession(), format("SELECT count(*) FROM test_arrays_of_nulls WHERE %s[1] IS NOT NULL", columnName)); assertQuerySucceeds(getSession(), format("SELECT count(*) FROM test_arrays_of_nulls WHERE %s[1] IS NULL", columnName)); } } finally { getQueryRunner().execute("DROP TABLE test_arrays_of_nulls"); } }
Source:
public boolean processRow(ExportRow rd) throws ExportDecoderBase.RestartBlockException { try { if (haplist.isEmpty()) { connect(); } if (haplist.isEmpty()) { m_logger.rateLimitedLog(120, Level.ERROR, null, "Failed to connect to export socket endpoint %s, some servers may be down.", host); throw new RestartBlockException(true); } if (m_logger.isDebugEnabled()) { m_logger.debug(m_source.tableName + ":P" + m_source.partitionId + " sending seqNum: " + rd.values[2]); } String decoded = m_decoder.decode(rd.generation, rd.tableName, rd.types, rd.names,null, rd.values).concat("\n"); byte b[] = decoded.getBytes(); ByteBuffer buf = ByteBuffer.allocate(b.length); buf.put(b); buf.flip(); for (Pair<OutputStream, InputStream> streams : haplist.values()) { streams.getFirst().write(buf.array()); streams.getFirst().flush(); } } catch (Exception e) { m_logger.error(e.getLocalizedMessage()); haplist.clear(); throw new RestartBlockException(true); } return true; }

Target:
public boolean processRow(ExportRow rd) throws ExportDecoderBase.RestartBlockException { try { if (haplist.isEmpty()) { connect(); } if (haplist.isEmpty()) { m_logger.rateLimitedLog(120, Level.ERROR, null, "Failed to connect to export socket endpoint %s, some servers may be down.", host); throw new RestartBlockException(true); } if (m_logger.isDebugEnabled()) { m_logger.debug(m_source.tableName + ":P" + m_source.partitionId + " sending seqNum: " + rd.values[2]); } String decoded = m_decoder.decode(rd.generation, rd.tableName, rd.types, rd.names,null, rd.values).concat("\n"); byte b[] = decoded.getBytes(); ByteBuffer buf = ByteBuffer.allocate(b.length); buf.put(b); buf.flip(); for (Pair<OutputStream, InputStream> streams : haplist.values()) { streams.getFirst().write(buf.array()); streams.getFirst().flush(); } } catch (Exception e) { m_logger.warn("Unexpected error processing row: " + e.getLocalizedMessage() + ". Row will be retried."); haplist.clear(); throw new RestartBlockException(true); } return true; }
Source:
public Enumerable<Object[]> scan(DataContext root) { class TasksEnumerable extends DefaultEnumerable<Object[]> { private final JsonParserIterator<TaskStatusPlus> it; public TasksEnumerable(JsonParserIterator<TaskStatusPlus> tasks) { this.it = tasks; } @Override public Iterator<Object[]> iterator() { throw new UnsupportedOperationException("Do not use iterator(), it cannot be closed."); } @Override public Enumerator<Object[]> enumerator() { return new Enumerator<Object[]>() { @Override public Object[] current() { TaskStatusPlus task = it.next(); return new Object[]{task.getId(), task.getType(), task.getDataSource(), task.getCreatedTime(), task.getQueueInsertionTime(), task.getState(), task.getRunnerTaskState(), task.getDuration(), task.getLocation() != null ? task.getLocation().getHost() + ":" + (task.getLocation().getTlsPort() == -1 ? task.getLocation() .getPort() : task.getLocation().getTlsPort()) : null, task.getLocation().getHost(), task.getLocation().getPort(), task.getLocation().getTlsPort(), task.getErrorMsg()}; } @Override public boolean moveNext() { return it.hasNext(); } @Override public void reset() { } @Override public void close() { try { it.close(); } catch (IOException e) { throw new RuntimeException(e); } } }; } } return new TasksEnumerable(getTasks(druidLeaderClient, jsonMapper, responseHandler)); }

Target:
public Enumerable<Object[]> scan(DataContext root) { class TasksEnumerable extends DefaultEnumerable<Object[]> { private final CloseableIterator<TaskStatusPlus> it; public TasksEnumerable(JsonParserIterator<TaskStatusPlus> tasks) { this.it = getAuthorizedTasks(tasks, root); } @Override public Iterator<Object[]> iterator() { throw new UnsupportedOperationException("Do not use iterator(), it cannot be closed."); } @Override public Enumerator<Object[]> enumerator() { return new Enumerator<Object[]>() { @Override public Object[] current() { TaskStatusPlus task = it.next(); return new Object[]{task.getId(), task.getType(), task.getDataSource(), task.getCreatedTime(), task.getQueueInsertionTime(), task.getStatusCode(), task.getRunnerStatusCode(), task.getDuration(), task.getLocation().getHost() + ":" + (task.getLocation().getTlsPort() == -1 ? task.getLocation() .getPort() : task.getLocation().getTlsPort()), task.getLocation().getHost(), task.getLocation().getPort(), task.getLocation().getTlsPort(), task.getErrorMsg()}; } @Override public boolean moveNext() { return it.hasNext(); } @Override public void reset() { } @Override public void close() { try { it.close(); } catch (IOException e) { throw new RuntimeException(e); } } }; } } return new TasksEnumerable(getTasks(druidLeaderClient, jsonMapper, responseHandler)); }
Source:
private Set<String> extractAttributes(String attributesParameter) { List<String> strings = Lists.newArrayList("schemas"); if (!Strings.isNullOrEmpty(attributesParameter)) { strings.addAll(Arrays.asList(attributesParameter.split("[,|\\.]"))); } strings.forEach(e -> strings.set(strings.indexOf(e), e.trim())); return new HashSet<>(strings); }

Target:
private Set<String> extractAttributes(String attributesParameter) { Set<String> result = new HashSet<>(); if (!Strings.isNullOrEmpty(attributesParameter)) { result = Sets.newHashSet( Splitter.on(CharMatcher.anyOf(".,")) .trimResults() .omitEmptyStrings() .split(attributesParameter) ); } result.add("schemas"); return result; }
Source:
private void onPrivateMessage(PrivateMessageEvent event) { User user = event.getUser(); if (user == null) { logger.warn("Private message without user: {}", event); return; } logger.debug("Received private message: {}", event); Player sourcePlayer = playerService.getPlayerForUsername(user.getNick()); if (sourcePlayer != null && sourcePlayer.getSocialStatus() == SocialStatus.FOE && preferencesService.getPreferences().getChat().getHideFoeMessages()) { log.info("Chat message was suppressed as sender was foe, sender was: {}", user.getNick()); return; } eventBus.post(new ChatMessageEvent(new ChatMessage(user.getNick(), Instant.ofEpochMilli(event.getTimestamp()), user.getNick(), event.getMessage()))); }

Target:
private void onPrivateMessage(PrivateMessageEvent event) { User user = event.getUser(); if (user == null) { logger.warn("Private message without user: {}", event); return; } logger.debug("Received private message: {}", event); Player sourcePlayer = playerService.getPlayerForUsername(user.getNick()); if (sourcePlayer != null && sourcePlayer.getSocialStatus() == SocialStatus.FOE && preferencesService.getPreferences().getChat().getHideFoeMessages()) { log.debug("Suppressing chat message from foe '{}'", user.getNick()); return; } eventBus.post(new ChatMessageEvent(new ChatMessage(user.getNick(), Instant.ofEpochMilli(event.getTimestamp()), user.getNick(), event.getMessage()))); }
Source:
public FileRawData execute( @DescribeParameter(name="layer", description="WFS layer to query") String layer, @DescribeParameter(name="subset", description="Subset, semi-colon separated") String subset, @DescribeParameter(name="callbackUrl", description="Callback URL", min=0) URL callbackUrl, @DescribeParameter(name="callbackParams", description="Parameters to append to the callback", min=0) String callbackParams, @DescribeParameter(name = "format", min = 0) final String format, ProgressListener progressListener ) throws ProcessException { try { if (goGoDuckConfig.getThreadCount() <= 0) { throw new ProcessException("threadCount set to 0 or below, job will not run"); } File outputFile = getResourceManager().getOutputResource( getResourceManager().getExecutionId(true), layer + ".nc").file(); String filePath = outputFile.toPath().toAbsolutePath().toString(); GoGoDuck ggd = new GoGoDuck(catalog, layer, subset, filePath, format, goGoDuckConfig); ggd.setTmpDir(getWorkingDir()); ggd.setThreadCount(goGoDuckConfig.getThreadCount()); ggd.setProgressListener(progressListener); Path outputPath = ggd.run(); notifySuccess(callbackUrl, callbackParams); return new FileRawData(outputPath.toFile(), ggd.getMimeType(), ggd.getExtension()); } catch (GoGoDuckException e) { logger.error(e.toString(), e); notifyFailure(callbackUrl, callbackParams); throw new ProcessException(e.getMessage()); } }

Target:
public FileRawData execute( @DescribeParameter(name="layer", description="WFS layer to query") String layer, @DescribeParameter(name="subset", description="Subset, semi-colon separated") String subset, @DescribeParameter(name="callbackUrl", description="Callback URL", min=0) URL callbackUrl, @DescribeParameter(name="callbackParams", description="Parameters to append to the callback", min=0) String callbackParams, @DescribeParameter(name = "format", min = 0) final String format, ProgressListener progressListener ) throws ProcessException { try { if (goGoDuckConfig.getThreadCount() <= 0) { throw new ProcessException("threadCount set to 0 or below, job will not run"); } File outputFile = getResourceManager().getOutputResource( getResourceManager().getExecutionId(true), layer + ".nc").file(); String filePath = outputFile.toPath().toAbsolutePath().toString(); GoGoDuck ggd = new GoGoDuck(catalog, layer, subset, filePath, format, goGoDuckConfig); ggd.setTmpDir(getWorkingDir()); ggd.setProgressListener(progressListener); Path outputPath = ggd.run(); notifySuccess(callbackUrl, callbackParams); return new FileRawData(outputPath.toFile(), ggd.getMimeType(), ggd.getExtension()); } catch (GoGoDuckException e) { logger.error(e.toString(), e); notifyFailure(callbackUrl, callbackParams); throw new ProcessException(e.getMessage(), e); } }
Source:
private void upsertAttributes(EntityType entityType, EntityType existingEntityType) { Map<String, Attribute> attrsMap = stream(entityType.getOwnAllAttributes()) .collect(toMap(Attribute::getIdentifier, Function.identity())); Map<String, Attribute> existingAttrsMap = stream(existingEntityType.getOwnAllAttributes()) .collect(toMap(Attribute::getIdentifier, Function.identity())); Set<String> addedAttrNames = Sets.difference(attrsMap.keySet(), existingAttrsMap.keySet()); Set<String> sharedAttrNames = Sets.intersection(attrsMap.keySet(), existingAttrsMap.keySet()); Set<String> deletedAttrNames = Sets.difference(existingAttrsMap.keySet(), attrsMap.keySet()); if (!addedAttrNames.isEmpty()) { dataService.add(ATTRIBUTE_META_DATA, addedAttrNames.stream().map(attrsMap::get)); } List<String> updatedAttrNames = sharedAttrNames.stream() .filter( attrName -> !EntityUtils.equals(attrsMap.get(attrName), existingAttrsMap.get(attrName))) .collect(toList()); if (!updatedAttrNames.isEmpty()) { dataService.update(ATTRIBUTE_META_DATA, updatedAttrNames.stream().map(attrsMap::get)); } if (!deletedAttrNames.isEmpty()) { dataService.delete(ATTRIBUTE_META_DATA, deletedAttrNames.stream().map(existingAttrsMap::get)); } }

Target:
private void upsertAttributes(EntityType entityType, EntityType existingEntityType) { Map<String, Attribute> attrsMap = stream(entityType.getOwnAllAttributes()) .collect(toMap(Attribute::getIdentifier, Function.identity())); Map<String, Attribute> existingAttrsMap = stream(existingEntityType.getOwnAllAttributes()) .collect(toMap(Attribute::getIdentifier, Function.identity())); Set<String> addedAttrIds = Sets.difference(attrsMap.keySet(), existingAttrsMap.keySet()); Set<String> sharedAttrIds = Sets.intersection(attrsMap.keySet(), existingAttrsMap.keySet()); Set<String> deletedAttrIds = Sets.difference(existingAttrsMap.keySet(), attrsMap.keySet()); if (!addedAttrIds.isEmpty()) { dataService.add(ATTRIBUTE_META_DATA, addedAttrIds.stream().map(attrsMap::get)); } List<String> updatedAttrIds = sharedAttrIds.stream() .filter( attrName -> !EntityUtils.equals(attrsMap.get(attrName), existingAttrsMap.get(attrName))) .collect(toList()); if (!updatedAttrIds.isEmpty()) { dataService.update(ATTRIBUTE_META_DATA, updatedAttrIds.stream().map(attrsMap::get)); } if (!deletedAttrIds.isEmpty()) { dataService.delete(ATTRIBUTE_META_DATA, deletedAttrIds.stream().map(existingAttrsMap::get)); } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof LookupConfig)) { return false; } LookupConfig that = (LookupConfig) o; return getSnapshotWorkingDir().equals(that.getSnapshotWorkingDir()); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof LookupConfig)) { return false; } LookupConfig that = (LookupConfig) o; return snapshotWorkingDir.equals(that.snapshotWorkingDir) && enableLookupSyncOnStartup == that.enableLookupSyncOnStartup && numLookupLoadingThreads == that.numLookupLoadingThreads; }
Source:
public PlanNode visitExchange(ExchangeNode exchange, RewriteContext<FragmentProperties> context) { if (!exchange.getScope().isRemote()) { return context.defaultRewrite(exchange, context.get()); } if (exchange.getScope() == REMOTE) { return createRemoteExchange(exchange, context); } if (exchange.getScope() == REMOTE_MATERIALIZED) { return createRemoteMaterializedExchange(exchange, context); } throw new IllegalArgumentException("Unexpected exchange scope: " + exchange.getScope()); }

Target:
public PlanNode visitExchange(ExchangeNode exchange, RewriteContext<FragmentProperties> context) { switch (exchange.getScope()) { case LOCAL: return context.defaultRewrite(exchange, context.get()); case REMOTE: return createRemoteExchange(exchange, context); case REMOTE_MATERIALIZED: return createRemoteMaterializedExchange(exchange, context); default: throw new IllegalArgumentException("Unexpected exchange scope: " + exchange.getScope()); } }
Source:
void validateShowStatsWhereExpression(Expression expression, ShowStats node) { check(ALLOWED_SHOW_STATS_WHERE_EXPRESSION_TYPES.stream().anyMatch(clazz -> clazz.isInstance(expression)), node, "Only literals, column references, comparators, is (not) null and logical operators are allowed in WHERE of SHOW STATS SELECT clause"); if (expression instanceof NotExpression) { validateShowStatsWhereExpression(((NotExpression) expression).getValue(), node); } else if (expression instanceof LogicalBinaryExpression) { validateShowStatsWhereExpression(((LogicalBinaryExpression) expression).getLeft(), node); validateShowStatsWhereExpression(((LogicalBinaryExpression) expression).getRight(), node); } else if (expression instanceof ComparisonExpression) { validateShowStatsWhereExpression(((ComparisonExpression) expression).getLeft(), node); validateShowStatsWhereExpression(((ComparisonExpression) expression).getRight(), node); } else if (expression instanceof IsNullPredicate) { validateShowStatsWhereExpression(((IsNullPredicate) expression).getValue(), node); } else if (expression instanceof IsNotNullPredicate) { validateShowStatsWhereExpression(((IsNotNullPredicate) expression).getValue(), node); } }

Target:
private void validateShowStatsWhereExpression(Expression expression, ShowStats node) { check(ALLOWED_SHOW_STATS_WHERE_EXPRESSION_TYPES.stream().anyMatch(clazz -> clazz.isInstance(expression)), node, "Only literals, column references, comparators, is (not) null and logical operators are allowed in WHERE of SHOW STATS SELECT clause"); if (expression instanceof NotExpression) { validateShowStatsWhereExpression(((NotExpression) expression).getValue(), node); } else if (expression instanceof LogicalBinaryExpression) { validateShowStatsWhereExpression(((LogicalBinaryExpression) expression).getLeft(), node); validateShowStatsWhereExpression(((LogicalBinaryExpression) expression).getRight(), node); } else if (expression instanceof ComparisonExpression) { validateShowStatsWhereExpression(((ComparisonExpression) expression).getLeft(), node); validateShowStatsWhereExpression(((ComparisonExpression) expression).getRight(), node); } else if (expression instanceof IsNullPredicate) { validateShowStatsWhereExpression(((IsNullPredicate) expression).getValue(), node); } else if (expression instanceof IsNotNullPredicate) { validateShowStatsWhereExpression(((IsNotNullPredicate) expression).getValue(), node); } }
Source:
public T route(String command) throws CommandRouterException, RouteNotFoundException { T message = null; for (Route pa : routes) { Matcher matcher = pa.regex.matcher(command); boolean matches = matcher.matches(); if (matches) { List<String> parameters = new ArrayList<String>(); for (int index = 0; index <= matcher.groupCount(); index++) { parameters.add(matcher.group(index)); } String[] parametersArray = null; if (parameters.size() > 1) { parameters.remove(0); parametersArray = new String[parameters.size()]; parametersArray = parameters.toArray(parametersArray); } try { message = (T)pa.routerCommand.execute(parametersArray); } catch (Exception ex) { throw new CommandRouterException(ex.getMessage()); } break; } } if (message == null) throw new RouteNotFoundException("No route found for given command", command); return message; }

Target:
public T route(String command) throws CommandRouterException, RouteNotFoundException { T message = null; for (Route<T> pa : routes) { Matcher matcher = pa.regex.matcher(command); boolean matches = matcher.matches(); if (matches) { String[] parametersArray = null; if (matcher.groupCount() == 0) { parametersArray = new String[] { command }; } else { parametersArray = new String[matcher.groupCount()]; for (int i = 1; i <= matcher.groupCount(); i++) { parametersArray[i-1] = matcher.group(i); } } try { message = pa.routerCommand.execute(parametersArray); } catch (Exception ex) { throw new CommandRouterException(ex.getMessage()); } if (message == null) throw new RouteNotFoundException("No route found for given command", command); return message; } } return message; }
Source:
public Genomics fromClientSecretsFile(File clientSecretsJson) throws IOException { try (Reader in = new FileReader(clientSecretsJson)) { GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow .Builder( httpTransport, jsonFactory, GoogleClientSecrets.load(jsonFactory, in), scopes) .setDataStoreFactory(dataStoreFactory) .build(); return create( new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(userName), null); } }

Target:
public Genomics fromClientSecretsFile(File clientSecretsJson) throws IOException { Reader in = null; boolean returnNormally = true; try { GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow .Builder( httpTransport, jsonFactory, GoogleClientSecrets.load(jsonFactory, in = new FileReader(clientSecretsJson)), scopes) .setDataStoreFactory(dataStoreFactory) .build(); return create( refreshToken( new AuthorizationCodeInstalledApp(flow, verificationCodeReceiver.get()) .authorize(userName)), null); } catch (IOException e) { returnNormally = false; throw e; } finally { if (null != in) { try { in.close(); } catch (IOException e) { if (returnNormally) { throw e; } } } } }
Source:
protected String getTopologyConf(PackingPlan packing) { Config marathonConfig = Config.newBuilder() .putAll(config) .put(Keys.topologyBinaryFile(), FileUtils.getBaseName(Context.topologyBinaryFile(config))) .build(); ObjectMapper mapper = new ObjectMapper(); PackingPlan updatedPackingPlan = packing.cloneWithHomogeneousScheduledResource(); SchedulerUtils.persistUpdatedPackingPlan(Runtime.topologyName(runtime), updatedPackingPlan, Runtime.schedulerStateManagerAdaptor(runtime)); Resource containerResource = updatedPackingPlan.getContainers() .iterator().next().getRequiredResource(); ArrayNode instances = mapper.createArrayNode(); for (int i = 0; i < Runtime.numContainers(runtime); i++) { ObjectNode instance = mapper.createObjectNode(); instance.put(MarathonConstants.ID, Integer.toString(i)); instance.put(MarathonConstants.COMMAND, getExecutorCommand(marathonConfig, i)); instance.put(MarathonConstants.CPU, containerResource.getCpu()); instance.set(MarathonConstants.CONTAINER, getContainer(mapper)); instance.put(MarathonConstants.MEMORY, containerResource.getRam().asMegabytes()); instance.put(MarathonConstants.DISK, containerResource.getDisk().asMegabytes()); instance.put(MarathonConstants.INSTANCES, 1); instance.set(MarathonConstants.LABELS, getLabels(mapper)); instance.set(MarathonConstants.FETCH, getFetchList(mapper)); instances.add(instance); } ObjectNode appConf = mapper.createObjectNode(); appConf.put(MarathonConstants.ID, Runtime.topologyName(runtime)); appConf.set(MarathonConstants.APPS, instances); return appConf.toString(); }

Target:
protected String getTopologyConf(PackingPlan packing) { config = Config.newBuilder() .putAll(config) .put(Key.TOPOLOGY_BINARY_FILE, FileUtils.getBaseName(Context.topologyBinaryFile(config))) .build(); ObjectMapper mapper = new ObjectMapper(); PackingPlan updatedPackingPlan = packing.cloneWithHomogeneousScheduledResource(); SchedulerUtils.persistUpdatedPackingPlan(Runtime.topologyName(runtime), updatedPackingPlan, Runtime.schedulerStateManagerAdaptor(runtime)); Resource containerResource = updatedPackingPlan.getContainers() .iterator().next().getRequiredResource(); ArrayNode instances = mapper.createArrayNode(); for (int i = 0; i < Runtime.numContainers(runtime); i++) { ObjectNode instance = mapper.createObjectNode(); instance.put(MarathonConstants.ID, Integer.toString(i)); instance.put(MarathonConstants.COMMAND, getExecutorCommand(i)); instance.put(MarathonConstants.CPU, containerResource.getCpu()); instance.set(MarathonConstants.CONTAINER, getContainer(mapper)); instance.put(MarathonConstants.MEMORY, containerResource.getRam().asMegabytes()); instance.put(MarathonConstants.DISK, containerResource.getDisk().asMegabytes()); instance.put(MarathonConstants.INSTANCES, 1); instance.set(MarathonConstants.LABELS, getLabels(mapper)); instance.set(MarathonConstants.FETCH, getFetchList(mapper)); instances.add(instance); } ObjectNode appConf = mapper.createObjectNode(); appConf.put(MarathonConstants.ID, Runtime.topologyName(runtime)); appConf.set(MarathonConstants.APPS, instances); return appConf.toString(); }
Source:
public void close() { producer.close(Duration.ofSeconds(0)); }

Target:
public void close() { producer.close(); }
Source:
public VfsFileChooserHelper( Shell shell, VfsFileChooserDialog fileChooserDialog, VariableSpace variableSpace, FileSystemOptions fileSystemOptions ) { this.fileChooserDialog = fileChooserDialog; this.shell = shell; this.variableSpace = variableSpace; this.fileSystemOptions = fileSystemOptions; this.schemeRestrictions = new String[1]; }

Target:
public VfsFileChooserHelper( Shell shell, VfsFileChooserDialog fileChooserDialog, VariableSpace variableSpace, FileSystemOptions fileSystemOptions ) { this.fileChooserDialog = fileChooserDialog; this.shell = shell; this.variableSpace = variableSpace; this.fileSystemOptions = fileSystemOptions; this.schemeRestrictions = new String[0]; }
Source:
public void run() { fLogger.info(() -> "[build thread start] trace=" + fBuildTrace.getName()); buildEntryList(fBuildTrace, fParentTrace, fMonitor); synchronized (fBuildThreadMap) { fBuildThreadMap.remove(fBuildTrace); } fLogger.info(() -> "[build thread end]"); }

Target:
public void run() { fLogger.info(() -> "[BuildThreadStart] trace=" + fBuildTrace.getName()); buildEntryList(fBuildTrace, fParentTrace, fMonitor); synchronized (fBuildThreadMap) { fBuildThreadMap.remove(fBuildTrace); } fLogger.info(() -> "[BuildThreadEnd]"); }
Source:
protected CreateVDSCommandParameters buildCreateVmParameters() { CreateVDSCommandParameters parameters = new CreateVDSCommandParameters(getVdsId(), getVm()); parameters.setRunInUnknownStatus(getParameters().isRunInUnknownStatus()); parameters.setVmPayload(vmPayload); if (shouldRestoreMemory()) { if (FeatureSupported.isMemoryDisksOnDifferentDomainsSupported(getVm().getCompatibilityVersion())) { parameters.setMemoryDumpImage((DiskImage) diskDao.get(getActiveSnapshot().getMemoryDiskId())); parameters.setMemoryConfImage((DiskImage) diskDao.get(getActiveSnapshot().getMetadataDiskId())); } else { parameters.setHibernationVolHandle(getActiveSnapshot().getMemoryVolume()); } parameters.setDownSince(getVm().getStatus() == VMStatus.Suspended ? getVm().getLastStopTime() : getActiveSnapshot().getCreationDate()); } parameters.setPassthroughVnicToVfMap(flushPassthroughVnicToVfMap()); if (initializationType == InitializationType.Sysprep && osRepository.isWindows(getVm().getVmOsId()) && (getVm().getFloppyPath() == null || "".equals(getVm().getFloppyPath()))) { parameters.setInitializationType(InitializationType.Sysprep); } if (initializationType == InitializationType.CloudInit && !osRepository.isWindows(getVm().getVmOsId())) { parameters.setInitializationType(InitializationType.CloudInit); } return parameters; }

Target:
protected CreateVDSCommandParameters buildCreateVmParameters() { CreateVDSCommandParameters parameters = new CreateVDSCommandParameters(getVdsId(), getVm()); parameters.setRunInUnknownStatus(getParameters().isRunInUnknownStatus()); parameters.setVmPayload(vmPayload); if (shouldRestoreMemory()) { if (FeatureSupported.isMemoryDisksOnDifferentDomainsSupported(getVm().getCompatibilityVersion()) && getActiveSnapshot().getMemoryDiskId() != null) { parameters.setMemoryDumpImage((DiskImage) diskDao.get(getActiveSnapshot().getMemoryDiskId())); parameters.setMemoryConfImage((DiskImage) diskDao.get(getActiveSnapshot().getMetadataDiskId())); } else { parameters.setHibernationVolHandle(getActiveSnapshot().getMemoryVolume()); } parameters.setDownSince(getVm().getStatus() == VMStatus.Suspended ? getVm().getLastStopTime() : getActiveSnapshot().getCreationDate()); } parameters.setPassthroughVnicToVfMap(flushPassthroughVnicToVfMap()); if (initializationType == InitializationType.Sysprep && osRepository.isWindows(getVm().getVmOsId()) && (getVm().getFloppyPath() == null || "".equals(getVm().getFloppyPath()))) { parameters.setInitializationType(InitializationType.Sysprep); } if (initializationType == InitializationType.CloudInit && !osRepository.isWindows(getVm().getVmOsId())) { parameters.setInitializationType(InitializationType.CloudInit); } return parameters; }
Source:
public void run() throws Exception { while (true) { if (m_sessionProvider.isClosing()) { return; } Message message = m_consumer.receive(); if (message == null) { return; } LOG.debug("Receiving JMS message [message={}]", message); try { onJmsMessage(message); } catch (Exception e) { BEANS.get(MomExceptionHandler.class).handle(e); } } }

Target:
public void run() throws Exception { while (true) { if (m_sessionProvider.isClosing() || IFuture.CURRENT.get().isCancelled()) { LOG.debug("JMS MessageConsumer for was closed", m_destination); break; } Message message = m_consumer.receive(); if (message == null) { break; } LOG.debug("Receiving JMS message [message={}]", message); try { onJmsMessage(message); } catch (Exception e) { BEANS.get(MomExceptionHandler.class).handle(e); } } LOG.debug("JMS MessageConsumer for was closed", m_destination); }
Source:
public FEELFnResult<Boolean> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } if ( number.remainder( BigDecimal.ONE ).signum() != 0 ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot have non-zero fractional part" ) ); } return FEELFnResult.ofResult( !BigInteger.ZERO.equals( number.toBigInteger().remainder(TWO) ) ); }

Target:
public FEELFnResult<Boolean> invoke(@ParameterName( "number" ) BigDecimal number) { if ( number == null ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot be null" ) ); } if ( number.remainder( BigDecimal.ONE ).signum() != 0 ) { return FEELFnResult.ofError( new InvalidParametersEvent( FEELEvent.Severity.ERROR, "number", "cannot have non-zero fractional part" ) ); } return FEELFnResult.ofResult( BigDecimal.ZERO.compareTo( number.remainder(TWO) ) != 0); }
Source:
public boolean isInstanceOfScoped(EObject object, EClass clazz) { if (!isInstanceOfUnscoped(object, clazz)) { return false; } Object typeKey = toKey(clazz); final Set<EObject> instances = instanceStore.getInstanceSet(typeKey); return instances != null && instances.contains(object); }

Target:
public boolean isInstanceOfScoped(EObject object, EClass clazz) { Object typeKey = toKey(object.eClass()); if (!doCalculateInstanceOf(typeKey, clazz)) { return false; } final Set<EObject> instances = instanceStore.getInstanceSet(typeKey); return instances != null && instances.contains(object); }
Source:
public static String formatMessages(final List<DMNMessage> messages) { return messages.stream().map(Object::toString).collect( Collectors.joining( "\n" ) ); }

Target:
public static String formatMessages(final List<DMNMessage> messages) { return messages.stream().map(Object::toString).collect( Collectors.joining( System.lineSeparator() ) ); }
Source:
public String getDisplayName() { return "Upstream Committer"; }

Target:
public String getDisplayName() { return Messages.UpstreamComitterRecipientProvider_DisplayName(); }
Source:
public CompilationUnit parse(InputFile file) { try { if (file.getUnitName().endsWith(".java")) { String source = options.fileUtil().readFile(file); return parse(null, file.getUnitName(), source); } else { assert options.translateClassfiles(); JavacEnvironment parserEnv = createEnvironment(Collections.emptyList(), Collections.emptyList(), false, null); return ClassFileConverter.convertClassFile(options, parserEnv, file); } } catch (IOException e) { ErrorUtil.error(e.getMessage()); return null; } }

Target:
public CompilationUnit parse(InputFile file) { try { if (file.getUnitName().endsWith(".java")) { String source = options.fileUtil().readFile(file); return parse(null, file.getUnitName(), source); } else { assert options.translateClassfiles(); JavacEnvironment parserEnv = createEnvironment(Collections.emptyList(), Collections.emptyList(), false); return ClassFileConverter.convertClassFile(options, parserEnv, file); } } catch (IOException e) { ErrorUtil.error(e.getMessage()); return null; } }
Source:
public void executeQueryCommandWithWatchdog() { final Guid vmId = new Guid("ee655a4d-effc-4aab-be2b-2f80ff40cd1c"); VmDeviceDAO vmDeviceDaoMock = Mockito.mock(VmDeviceDAO.class); HashMap<String, Object> watchdogSpecParams = new HashMap<String, Object>(); watchdogSpecParams.put("model", "i3600esb"); watchdogSpecParams.put("action", "reset"); VmDevice vmDevice = new VmDevice(new VmDeviceId(new Guid("6f86b8a4-e721-4149-b2df-056eb621b16a"), vmId), VmDeviceType.WATCHDOG.getName(), "watchdog", "", 1, watchdogSpecParams, true, true, true, ""); Mockito.when(vmDeviceDaoMock.getVmDeviceByVmIdAndType(vmId, VmDeviceType.WATCHDOG.getName())) .thenReturn(Arrays.asList(vmDevice)); GetWatchdogQuery<IdQueryParameters> query = new GetWatchdogQuery<IdQueryParameters>(new IdQueryParameters(vmId)); query = Mockito.spy(query); Mockito.when(query.getVmDeviceDAO()).thenReturn(vmDeviceDaoMock); IdQueryParameters params = new IdQueryParameters(vmId); Mockito.when(query.getParameters()) .thenReturn(params); Mockito.doCallRealMethod().when(query).executeQueryCommand(); Mockito.doCallRealMethod().when(query).getReturnValue(); Mockito.doCallRealMethod().when(query).setReturnValue(Mockito.any(Object.class)); query.executeQueryCommand(); Assert.assertNotNull(query.getReturnValue()); Assert.assertEquals((((VmWatchdog)query.getReturnValue()).getAction()).name().toLowerCase(), "reset"); Assert.assertEquals((((VmWatchdog)query.getReturnValue()).getModel()).name().toLowerCase(), "i6300esb"); }

Target:
public void executeQueryCommandWithWatchdog() { final Guid vmId = new Guid("ee655a4d-effc-4aab-be2b-2f80ff40cd1c"); VmDeviceDAO vmDeviceDaoMock = Mockito.mock(VmDeviceDAO.class); HashMap<String, Object> watchdogSpecParams = new HashMap<String, Object>(); watchdogSpecParams.put("model", "i6300esb"); watchdogSpecParams.put("action", "reset"); VmDevice vmDevice = new VmDevice(new VmDeviceId(new Guid("6f86b8a4-e721-4149-b2df-056eb621b16a"), vmId), VmDeviceType.WATCHDOG.getName(), "watchdog", "", 1, watchdogSpecParams, true, true, true, ""); Mockito.when(vmDeviceDaoMock.getVmDeviceByVmIdAndType(vmId, VmDeviceType.WATCHDOG.getName())) .thenReturn(Arrays.asList(vmDevice)); GetWatchdogQuery<IdQueryParameters> query = new GetWatchdogQuery<IdQueryParameters>(new IdQueryParameters(vmId)); query = Mockito.spy(query); Mockito.when(query.getVmDeviceDAO()).thenReturn(vmDeviceDaoMock); IdQueryParameters params = new IdQueryParameters(vmId); Mockito.when(query.getParameters()) .thenReturn(params); Mockito.doCallRealMethod().when(query).executeQueryCommand(); Mockito.doCallRealMethod().when(query).getReturnValue(); Mockito.doCallRealMethod().when(query).setReturnValue(Mockito.any(Object.class)); query.executeQueryCommand(); Assert.assertNotNull(query.getReturnValue()); Assert.assertEquals((((VmWatchdog)query.getReturnValue()).getAction()).name().toLowerCase(), "reset"); Assert.assertEquals((((VmWatchdog)query.getReturnValue()).getModel()).name().toLowerCase(), "i6300esb"); }