auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void initialize(Config config, TopologyAPI.Topology inputTopology) { this.topology = inputTopology; setPackingConfigs(config); LOG.info(String.format("Initalizing Packing: \n" + "Max number of instances per container: %d \n" + "Default instance CPU: %f, Default instance RAM: %s, Default instance DISK: %s \n" + "Paddng: %s \n" + "Container CPU: %f, Container RAM: %s, Container DISK: %s", this.maxNumInstancesPerContainer, this.defaultInstanceResources.getCpu(), this.defaultInstanceResources.getRam().toString(), this.defaultInstanceResources.getDisk().toString(), this.padding.toString(), this.maxContainerResources.getCpu(), this.maxContainerResources.getRam().toString(), this.maxContainerResources.getDisk().toString())); }

Target:
public void initialize(Config config, TopologyAPI.Topology inputTopology) { this.topology = inputTopology; setPackingConfigs(config); LOG.info(String.format("Initalizing Packing: \n" + "Max number of instances per container: %d \n" + "Default instance resource, CPU: %f, RAM: %s, DISK: %s \n" + "Paddng: %s \n" + "Container resource, CPU: %f, RAM: %s, DISK: %s", this.maxNumInstancesPerContainer, this.defaultInstanceResources.getCpu(), this.defaultInstanceResources.getRam().toString(), this.defaultInstanceResources.getDisk().toString(), this.padding.toString(), this.maxContainerResources.getCpu(), this.maxContainerResources.getRam().toString(), this.maxContainerResources.getDisk().toString())); }
Source:
private boolean checkListTypes() { for (VariableElement field : fields) { if (Utils.isRealmList(field)) { if (Utils.getGenericType(field) == null) { Utils.error("No generic type supplied for field", field); return false; } TypeMirror fieldType = field.asType(); List<? extends TypeMirror> typeArguments = ((DeclaredType) fieldType).getTypeArguments(); String genericCanonicalType = typeArguments.get(0).toString(); TypeElement typeElement = elements.getTypeElement(genericCanonicalType); if (typeElement.getSuperclass().getKind() == TypeKind.NONE) { Utils.error("Only concrete Realm classes are allowed in Lists. Neither " + "interfaces nor abstract classes can be used.", field); return false; } } } return true; }

Target:
private boolean checkListTypes() { for (VariableElement field : fields) { if (Utils.isRealmList(field)) { if (Utils.getGenericType(field) == null) { Utils.error("No generic type supplied for field", field); return false; } TypeMirror fieldType = field.asType(); List<? extends TypeMirror> typeArguments = ((DeclaredType) fieldType).getTypeArguments(); String genericCanonicalType = typeArguments.get(0).toString(); TypeElement typeElement = elements.getTypeElement(genericCanonicalType); if (typeElement.getSuperclass().getKind() == TypeKind.NONE) { Utils.error("Only concrete Realm classes are allowed in RealmLists. Neither " + "interfaces nor abstract classes can be used.", field); return false; } } } return true; }
Source:
public static <N extends Node> ParameterizedMetricKey<N> getInstance(MetricKey<N> key, MetricVersion version) { int code = code(key, version); if (!POOL.containsKey(code)) { POOL.put(code, new ParameterizedMetricKey<>(key, version)); } return (ParameterizedMetricKey<N>) POOL.get(code); }

Target:
public static <N extends Node> ParameterizedMetricKey<N> getInstance(MetricKey<N> key, MetricVersion version) { ParameterizedMetricKey<N> tmp = new ParameterizedMetricKey<>(key, version); if (!POOL.containsKey(tmp)) { POOL.put(tmp, tmp); } @SuppressWarnings("unchecked") ParameterizedMetricKey<N> result = (ParameterizedMetricKey<N>) POOL.get(tmp); return result; }
Source:
private void pollExecution() { if (this.executorId == -1) { if (AzkabanExecutorServer.getApp() != null) { try { final Executor executor = requireNonNull(FlowRunnerManager.this.executorLoader .fetchExecutor(AzkabanExecutorServer.getApp().getHost(), AzkabanExecutorServer.getApp().getPort()), "The executor can not be null"); this.executorId = executor.getId(); } catch (final Exception e) { FlowRunnerManager.logger.error("Failed to fetch executor ", e); } } } else if (FlowRunnerManager.this.active) { FlowRunnerManager.this.preparingFlowCount.getAndIncrement(); if (FlowRunnerManager.this.active) { try { final int execId = FlowRunnerManager.this.executorLoader .selectAndUpdateExecution(this.executorId); if (execId != -1) { FlowRunnerManager.logger.info("Submitting flow " + execId); Thread.sleep(1000 * 30); submitFlow(execId); } } catch (final Exception e) { FlowRunnerManager.logger.error("Failed to submit flow ", e); } finally { FlowRunnerManager.this.preparingFlowCount.getAndDecrement(); } } else { FlowRunnerManager.this.preparingFlowCount.getAndDecrement(); } } }

Target:
private void pollExecution() { if (this.executorId == -1) { if (AzkabanExecutorServer.getApp() != null) { try { final Executor executor = requireNonNull(FlowRunnerManager.this.executorLoader .fetchExecutor(AzkabanExecutorServer.getApp().getHost(), AzkabanExecutorServer.getApp().getPort()), "The executor can not be null"); this.executorId = executor.getId(); } catch (final Exception e) { FlowRunnerManager.logger.error("Failed to fetch executor ", e); } } } else { try { final int execId = FlowRunnerManager.this.executorLoader .selectAndUpdateExecution(this.executorId, FlowRunnerManager.this.active); if (execId != -1) { FlowRunnerManager.logger.info("Submitting flow " + execId); submitFlow(execId); commonMetrics.markDispatchSuccess(); } } catch (final Exception e) { FlowRunnerManager.logger.error("Failed to submit flow ", e); commonMetrics.markDispatchFail(); } } }
Source:
private boolean accepts(final Resource resource) throws RepositoryException { if (resource == null) { return false; } ValueMap props = resource.getValueMap(); if (!props.get("jcr:primaryType", "").equals("dam:AssetContent")) { return false; } if (!props.get("isRemoteAsset", false)) { return false; } if (remoteResourcesSyncing.contains(resource.getPath())) { return false; } Calendar lastFailure = props.get("remoteSyncFailed", (Calendar) null); if (lastFailure != null && System.currentTimeMillis() < (lastFailure.getTimeInMillis() + (this.config.getRetryDelay() * 60000))) { return false; } for (String syncPath : this.config.getDamSyncPaths()) { if (!resource.getPath().startsWith(syncPath)) { continue; } Session session = resource.getResourceResolver().adaptTo(Session.class); String userId = session.getUserID(); if (userId.equals("admin")) { LOG.debug("Avoiding binary sync for admin user"); continue; } if (this.config.getWhitelistedServiceUsers().contains(userId)) { return true; } User currentUser = (User) AccessControlUtil.getUserManager(session).getAuthorizable(userId); if (currentUser != null && !currentUser.isSystemUser()) { return true; } else { LOG.debug("Avoiding binary sync b/c this is a non-whitelisted service user: {}", session.getUserID()); } } return false; }

Target:
private boolean accepts(final Resource resource) throws RepositoryException { if (resource == null) { return false; } ValueMap props = resource.getValueMap(); if (!DamConstants.NT_DAM_ASSETCONTENT.equals(props.get(JcrConstants.JCR_PRIMARYTYPE))) { return false; } if (!props.get(RemoteAssets.IS_REMOTE_ASSET, false)) { return false; } Calendar lastFailure = props.get(RemoteAssets.REMOTE_SYNC_FAILED, (Calendar) null); if (lastFailure != null && System.currentTimeMillis() < (lastFailure.getTimeInMillis() + (this.config.getRetryDelay() * 60000))) { return false; } boolean matchesSyncPath = false; for (String syncPath : this.config.getDamSyncPaths()) { if (resource.getPath().startsWith(syncPath)) { matchesSyncPath = true; } } if (matchesSyncPath) { Session session = resource.getResourceResolver().adaptTo(Session.class); String userId = session.getUserID(); if (!userId.equals(UserConstants.DEFAULT_ADMIN_ID)) { if (this.config.getWhitelistedServiceUsers().contains(userId)) { return true; } User currentUser = (User) AccessControlUtil.getUserManager(session).getAuthorizable(userId); if (currentUser != null && !currentUser.isSystemUser()) { return true; } else { LOG.debug("Avoiding binary sync b/c this is a non-whitelisted service user: {}", session.getUserID()); } } else { LOG.debug("Avoiding binary sync for admin user"); } } return false; }
Source:
public NettyHttpClientPipelineFactory(TLSClientParameters clientParameters, int readTimeout) { this(clientParameters, readTimeout, 1048576); }

Target:
public NettyHttpClientPipelineFactory(TLSClientParameters clientParameters, int readTimeout) { this(clientParameters, readTimeout, NettyHttpConduit.DEFAULT_MAX_RESPONSE_CONTENT_LENGTH); }
Source:
private void createPluginVersionChangeTask(Project p, SarosEclipseExtension e) { String qualifier = e.getPluginVersionQualifier(); if (e.getPluginVersionQualifier() == null || qualifier.isEmpty()) return; p.getTasks() .register( PLUGIN_VERSION_CHANGE_TASK_NAME, (task) -> { task.getInputs().property("versionQualifier", qualifier); task.doLast( (t) -> { methodRequiresManifest("set version qualifier", e); new EclipseVersionConfigurator(e.getManifest()).addQualifier(qualifier); }); }); Task jarTask = p.getTasks().findByPath("jar"); if (jarTask == null) throw new GradleException("Unable to find jar task in project " + p.getName()); jarTask.dependsOn(PLUGIN_VERSION_CHANGE_TASK_NAME); }

Target:
private void createPluginVersionChangeTask(Project p, SarosEclipseExtension e) { String qualifier = e.getPluginVersionQualifier(); if (qualifier == null || qualifier.trim().isEmpty()) return; p.getTasks() .register( PLUGIN_VERSION_CHANGE_TASK_NAME, (task) -> { task.getInputs().property("versionQualifier", qualifier); task.doLast( (t) -> { methodRequiresManifest("set version qualifier", e); new OsgiBundleVersionConfigurator(e.getManifest()).addQualifier(qualifier); }); }); Task jarTask = p.getTasks().findByPath("jar"); if (jarTask == null) throw new GradleException("Unable to find jar task in project " + p.getName()); jarTask.dependsOn(PLUGIN_VERSION_CHANGE_TASK_NAME); }
Source:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { try { savedAnnouncements = savedInstanceState.getParcelableArrayList(Router.EXTRA_ANNOUNCEMENTS); } catch (Exception ex) { logger.error(ex); } } try { final Bundle bundle = getArguments(); courseData = (EnrolledCoursesResponse) bundle.getSerializable(Router.EXTRA_COURSE_DATA); FacebookProvider fbProvider = new FacebookProvider(); if (courseData != null) { if (savedAnnouncements == null) { loadAnnouncementData(courseData); } else { populateAnnouncements(savedAnnouncements); } } if (environment.getConfig().arePushNotificationEnabled() && courseData != null && courseData.getCourse() != null) { notificationSettingRow.setVisibility(View.VISIBLE); final String courseId = courseData.getCourse().getId(); final String subscriptionId = courseData.getCourse().getSubscription_id(); boolean isSubscribed = environment.getNotificationDelegate().isSubscribedByCourseId(courseId); notificationSwitch.setChecked(isSubscribed); notificationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { environment.getNotificationDelegate().changeNotificationSetting( courseId, subscriptionId, isChecked); } }); } else { notificationSwitch.setOnCheckedChangeListener(null); notificationSettingRow.setVisibility(View.GONE); } } catch (Exception ex) { logger.error(ex); } }

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { try { savedAnnouncements = savedInstanceState.getParcelableArrayList(Router.EXTRA_ANNOUNCEMENTS); } catch (Exception ex) { logger.error(ex); } } try { final Bundle bundle = getArguments(); courseData = (EnrolledCoursesResponse) bundle.getSerializable(Router.EXTRA_COURSE_DATA); FacebookProvider fbProvider = new FacebookProvider(); if (courseData != null) { if (savedAnnouncements == null) { loadAnnouncementData(courseData); } else { populateAnnouncements(savedAnnouncements); } } } catch (Exception ex) { logger.error(ex); } }
Source:
JsonNode readJsonNode(File file) { JsonNode node = null; try { node = mapper.readValue(file, JsonNode.class); } catch (IOException e) { log.warn("Cannot read/parse JSON file '{}'", file.getAbsolutePath()); log.warn("Exception", e); } return node; }

Target:
JsonNode readJsonNode(File file) { JsonNode node = null; try { node = mapper.readValue(file, JsonNode.class); } catch (IOException e) { log.warn("Cannot read/parse JSON file '{}': {}", file.getAbsolutePath(), e.getMessage()); log.debug("Exception", e); } return node; }
Source:
private void setResultSetMetadata() throws Exception { dbManager.ensureJDBCDriverIsAvailable(driverClass); Map<String, Integer> columnToType = new TreeMap<> ( new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } } ); Connection connection; if (dbSinkConfig.user == null) { connection = DriverManager.getConnection(dbSinkConfig.connectionString); } else { connection = DriverManager.getConnection(dbSinkConfig.connectionString, dbSinkConfig.user, dbSinkConfig.password); } try { try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(String.format("SELECT %s FROM %s WHERE 1 = 0", dbSinkConfig.columns, dbSinkConfig.tableName)) ) { ResultSetMetaData resultSetMetadata = rs.getMetaData(); FieldCase fieldCase = FieldCase.toFieldCase(dbSinkConfig.columnNameCase); for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { String name = resultSetMetadata.getColumnName(i + 1); int type = resultSetMetadata.getColumnType(i + 1); if (fieldCase == FieldCase.LOWER) { name = name.toLowerCase(); } else if (fieldCase == FieldCase.UPPER) { name = name.toUpperCase(); } columnToType.put(name, type); } } } finally { connection.close(); } columns = ImmutableList.copyOf(Splitter.on(",").omitEmptyStrings().trimResults().split(dbSinkConfig.columns)); columnTypes = new int[columns.size()]; for (int i = 0; i < columnTypes.length; i++) { String name = columns.get(i); Preconditions.checkArgument(columnToType.containsKey(name), "Missing column '%s' in SQL table", name); columnTypes[i] = columnToType.get(name); } }

Target:
private void setResultSetMetadata() throws Exception { Map<String, Integer> columnToType = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); dbManager.ensureJDBCDriverIsAvailable(driverClass); Connection connection; if (dbSinkConfig.user == null) { connection = DriverManager.getConnection(dbSinkConfig.connectionString); } else { connection = DriverManager.getConnection(dbSinkConfig.connectionString, dbSinkConfig.user, dbSinkConfig.password); } try { try (Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(String.format("SELECT %s FROM %s WHERE 1 = 0", dbSinkConfig.columns, dbSinkConfig.tableName)) ) { ResultSetMetaData resultSetMetadata = rs.getMetaData(); FieldCase fieldCase = FieldCase.toFieldCase(dbSinkConfig.columnNameCase); for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) { String name = resultSetMetadata.getColumnName(i + 1); int type = resultSetMetadata.getColumnType(i + 1); if (fieldCase == FieldCase.LOWER) { name = name.toLowerCase(); } else if (fieldCase == FieldCase.UPPER) { name = name.toUpperCase(); } columnToType.put(name, type); } } } finally { connection.close(); } columns = ImmutableList.copyOf(Splitter.on(",").omitEmptyStrings().trimResults().split(dbSinkConfig.columns)); columnTypes = new int[columns.size()]; for (int i = 0; i < columnTypes.length; i++) { String name = columns.get(i); Preconditions.checkArgument(columnToType.containsKey(name), "Missing column '%s' in SQL table", name); columnTypes[i] = columnToType.get(name); } }
Source:
public void loadGroupsInOffice(int office, Map<String, Object> params) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getGroupsByOffice(office, params) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Group>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); try { if (e instanceof HttpException) { String errorMessage = ((HttpException) e).response().errorBody() .string(); getMvpView().showError(MFErrorParser.parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } @Override public void onNext(List<Group> groups) { getMvpView().showProgressbar(false); getMvpView().showGroupsInOffice(groups); } })); }

Target:
public void loadGroupsInOffice(int office, Map<String, Object> params) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscription.add(mDataManager.getGroupsByOffice(office, params) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<List<Group>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showError(MFErrorParser.errorMessage(e)); } @Override public void onNext(List<Group> groups) { getMvpView().showProgressbar(false); getMvpView().showGroupsInOffice(groups); } })); }
Source:
private ContentResponse execute(Request req, boolean uriIsSecret) { String safeUri = safeUri(req, uriIsSecret); logger.info("Sending HTTP request: {}", req.getMethod(), safeUri); ContentResponse res; try { res = send(req); } catch (HttpResponseException e) { throw error(req, uriIsSecret, e.getResponse()); } catch (RuntimeException e) { logger.info("Exception without response: {}", req.getMethod(), safeUri); if(retry){ throw e; } else { throw new TaskExecutionException(e.toString()); } } logger.info("Received HTTP response: {}: {}", req.getMethod(), safeUri, res); if (HttpStatus.isSuccess(res.getStatus())) { return res; } else if (HttpStatus.isRedirection(res.getStatus())) { return res; } else { throw error(req, uriIsSecret, res); } }

Target:
private ContentResponse execute(Request req, boolean uriIsSecret) { String safeUri = safeUri(req, uriIsSecret); logger.info("Sending HTTP request: {}", req.getMethod(), safeUri); ContentResponse res; try { res = send(req); } catch (HttpResponseException e) { throw error(req, uriIsSecret, e.getResponse()); } catch (RuntimeException e) { logger.warn("Exception without response: {}", req.getMethod(), safeUri); if (retry) { throw e; } else { throw new TaskExecutionException(e); } } logger.info("Received HTTP response: {}: {}", req.getMethod(), safeUri, res); if (HttpStatus.isSuccess(res.getStatus())) { return res; } else if (HttpStatus.isRedirection(res.getStatus())) { return res; } else { throw error(req, uriIsSecret, res); } }
Source:
public static Function<GHEventsSubscriber, Set<GHEvent>> extractEvents() { return new Function<GHEventsSubscriber, Set<GHEvent>>() { @Override public Set<GHEvent> apply(GHEventsSubscriber subscriber) { if (subscriber == null) { return Collections.emptySet(); } return defaultIfNull(subscriber.events(), Collections.<GHEvent>emptySet()); } }; }

Target:
public static Function<GHEventsSubscriber, Set<GHEvent>> extractEvents() { return new Function<GHEventsSubscriber, Set<GHEvent>>() { @Override public Set<GHEvent> apply(GHEventsSubscriber subscriber) { return defaultIfNull(notNull(subscriber).events(), Collections.<GHEvent>emptySet()); } }; }
Source:
private ArrayList<String> getTestCasesFileNamesWithPaths(String testFileFolder) { ArrayList<String> fileNamesWithPaths = new ArrayList<>(); if (testFileFolder.endsWith(Constants.XML_EXTENSION)) { fileNamesWithPaths.add(testFileFolder); } else if (testFileFolder.endsWith(Constants.TEST_FOLDER_EXTENSION)) { String testFolderPath = testFileFolder.split("\\$")[0]; File folder = new File(testFolderPath); File[] listOfFiles = folder.listFiles(); if (listOfFiles != null) { for (File file : listOfFiles) { String filename = file.getName(); if (filename.endsWith(Constants.XML_EXTENSION)) { fileNamesWithPaths.add(testFolderPath + filename); } } } } return fileNamesWithPaths; }

Target:
private ArrayList<String> getTestCasesFileNamesWithPaths(String testFileFolder) { ArrayList<String> fileNamesWithPaths = new ArrayList<>(); if (testFileFolder.endsWith(Constants.XML_EXTENSION)) { fileNamesWithPaths.add(testFileFolder); } else if (testFileFolder.endsWith(Constants.TEST_FOLDER_EXTENSION)) { String testFolderPath = testFileFolder.split("\\$")[0]; File folder = new File(testFolderPath); File[] listOfFiles = folder.listFiles(); for (File file : listOfFiles) { String filename = file.getName(); if (filename.endsWith(Constants.XML_EXTENSION)) { fileNamesWithPaths.add(testFolderPath + filename); } } } return fileNamesWithPaths; }
Source:
public void show(final String name) { nameField.innerHTML = name.replaceAll("\\n", "<br>").replaceAll("\\s", "&nbsp;"); setVisible(); nameField.focus(); }

Target:
public void show(final String name) { nameField.textContent = ""; nameField.innerHTML = ""; nameField.innerHTML = name; setVisible(); }
Source:
protected JPanel getWorkPanel() { if (mainPanel == null) { mainPanel = new JPanel(new BorderLayout()); tabbedPane = new JTabbedPane(); if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setName("ActiveScanMessagePane"); jScrollPane.setViewportView(getMessagesTable()); } if (filterPane == null) { filterPane = new JScrollPane(); filterPane.setName("FilterMessagePane"); filterPane.setViewportView(getFilterMessageTable()); } tabbedPane.add( Constant.messages.getString("ascan.panel.tab.scannedMessages"), jScrollPane); tabbedPane.add( Constant.messages.getString("ascan.panel.tab.filteredMessages"), filterPane); tabbedPane.setSelectedIndex(0); mainPanel.add(tabbedPane); } return mainPanel; }

Target:
protected JPanel getWorkPanel() { if (mainPanel == null) { mainPanel = new JPanel(new BorderLayout()); tabbedPane = new JTabbedPane(); JScrollPane jScrollPane = new JScrollPane(); jScrollPane.setName("ActiveScanMessagePane"); jScrollPane.setViewportView(getMessagesTable()); JScrollPane filterPane = new JScrollPane(); filterPane.setName("FilterMessagePane"); filterPane.setViewportView(getFilterMessageTable()); tabbedPane.add( Constant.messages.getString("ascan.panel.tab.scannedMessages"), jScrollPane); tabbedPane.add( Constant.messages.getString("ascan.panel.tab.filteredMessages"), filterPane); tabbedPane.setSelectedIndex(0); mainPanel.add(tabbedPane); } return mainPanel; }
Source:
public String toString() { return "ScanQuery{" + "dataSource='" + getDataSource() + '\'' + ", querySegmentSpec=" + getQuerySegmentSpec() + ", virtualColumns=" + getVirtualColumns() + ", resultFormat='" + resultFormat + '\'' + ", batchSize=" + batchSize + ", limit=" + scanRowsLimit + ", dimFilter=" + dimFilter + ", columns=" + columns + ", legacy=" + legacy + '}'; }

Target:
public String toString() { switch (this) { case RESULT_FORMAT_LIST: return "list"; case RESULT_FORMAT_COMPACTED_LIST: return "compactedList"; case RESULT_FORMAT_VALUE_VECTOR: return "valueVector"; default: return ""; } }
Source:
@Override public void consumeMessage(String sequenceName) throws InterruptedException { Subscription subscription; String queueGroup = natsProperties.getProperty(NatsConstants.QUEUE_GROUP); if (StringUtils.isNotEmpty(queueGroup)) { subscription = connection.subscribe(subject, queueGroup); } else { subscription = connection.subscribe(subject); } Message natsMessage = subscription.nextMessage(Duration.ZERO); String message = new String(natsMessage.getData(), StandardCharsets.UTF_8); log.info("Message Received to NATS Inbound EP: " + message); injectHandler.invoke(message.getBytes(), sequenceName, natsMessage.getReplyTo(), connection); }

Target:
@Override public void consumeMessage(String sequenceName) throws InterruptedException { Subscription subscription; String queueGroup = natsProperties.getProperty(NatsConstants.QUEUE_GROUP); if (StringUtils.isNotEmpty(queueGroup)) { subscription = connection.subscribe(subject, queueGroup); } else { subscription = connection.subscribe(subject); } Message natsMessage = subscription.nextMessage(Duration.ofMillis(100)); if (natsMessage != null) { String message = new String(natsMessage.getData(), StandardCharsets.UTF_8); printDebugLog("Message Received to NATS Inbound EP: " + message); injectHandler.invoke(message.getBytes(), sequenceName, natsMessage.getReplyTo(), connection); } else { printDebugLog("Message is null."); } }
Source:
public void beforeClass() throws Exception { super.beforeClass(); _gSetupTool.addCluster(CLUSTER_NAME, true); _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL); for (int i = 0; i < NODE_NR; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica); for (int i = 0; i < NODE_NR; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); _participants[i].syncStart(); } String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _manager = HelixManagerFactory.getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); _store = new MockAssignmentMetadataStore(_manager.getMetadataStoreConnectionString(), _manager.getClusterName()); }

Target:
public void beforeClass() throws Exception { super.beforeClass(); _gSetupTool.addCluster(CLUSTER_NAME, true); _gSetupTool.addResourceToCluster(CLUSTER_NAME, TEST_DB, _PARTITIONS, STATE_MODEL); for (int i = 0; i < NODE_NR; i++) { String storageNodeName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _gSetupTool.addInstanceToCluster(CLUSTER_NAME, storageNodeName); } _gSetupTool.rebalanceStorageCluster(CLUSTER_NAME, TEST_DB, _replica); for (int i = 0; i < NODE_NR; i++) { String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i); _participants[i] = new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, instanceName); _participants[i].syncStart(); } String controllerName = CONTROLLER_PREFIX + "_0"; _controller = new ClusterControllerManager(ZK_ADDR, CLUSTER_NAME, controllerName); _controller.syncStart(); _manager = HelixManagerFactory .getZKHelixManager(CLUSTER_NAME, "Admin", InstanceType.ADMINISTRATOR, ZK_ADDR); _manager.connect(); _store = new AssignmentMetadataStore(_manager.getMetadataStoreConnectionString(), _manager.getClusterName()); }
Source:
public void run(StreamApplication streamApp) { JmxServer jmxServer = null; try { jmxServer = new JmxServer(); ContainerModel containerModel = jobModel.getContainers().get(containerId); Object taskFactory = TaskFactoryUtil.createTaskFactory(config, streamApp, this); SamzaContainer container = SamzaContainer$.MODULE$.apply( containerModel, config, jobModel.maxChangeLogStreamPartitions, jmxServer, Util.<String, MetricsReporter>javaMapAsScalaMap(new HashMap<>()), taskFactory); container.setContainerListener( new SamzaContainerListener() { @Override public void onContainerStart() { log.info("Container Started"); } @Override public void onContainerStop(boolean invokedExternally) { log.info("Container Stopped"); } @Override public void onContainerFailed(Throwable t) { log.info("Container Failed"); } }); container.run(); } finally { if (jmxServer != null) { jmxServer.stop(); } } }

Target:
public void run(StreamApplication streamApp) { JmxServer jmxServer = null; try { jmxServer = new JmxServer(); ContainerModel containerModel = jobModel.getContainers().get(containerId); Object taskFactory = TaskFactoryUtil.createTaskFactory(config, streamApp, this); SamzaContainer container = SamzaContainer$.MODULE$.apply( containerModel, config, jobModel.maxChangeLogStreamPartitions, jmxServer, Util.<String, MetricsReporter>javaMapAsScalaMap(new HashMap<>()), taskFactory); container.setContainerListener( new SamzaContainerListener() { @Override public void onContainerStart() { log.info("Container Started"); } @Override public void onContainerStop(boolean invokedExternally) { log.info("Container Stopped"); } @Override public void onContainerFailed(Throwable t) { log.info("Container Failed"); containerException = t; } }); container.run(); } finally { if (jmxServer != null) { jmxServer.stop(); } } if (containerException != null) { log.error("Container stopped with Exception. Exiting process now.", containerException); System.exit(1); } }
Source:
public void testEncryptDecrypt() throws DecryptionException, BuilderException, EncryptionException { AESKeyVersion keyversion = new AESKeyVersion.Builder().build(); testEncryptDecryptKeyVersion(keyversion); for (KeySize keySize : KeySize.values()) { keyversion = new AESKeyVersion.Builder() .keySize(keySize) .padding(Padding.PKCS5).build(); testEncryptDecryptKeyVersion(keyversion); } for (KeySize keySize : KeySize.values()) { for (Mode mode : Mode.values()) { keyversion = new AESKeyVersion.Builder() .keySize(keySize) .padding(Padding.PKCS5).mode(mode).build(); testEncryptDecryptKeyVersion(keyversion); } } }

Target:
public void testEncryptDecrypt() throws DecryptionException, BuilderException, EncryptionException { AESKeyVersion keyversion = new AESKeyVersion.Builder().build(); testEncryptDecryptKeyVersion(keyversion); for (Integer keyVersionLength : new Integer[] {16, 24, 32}) { keyversion = new AESKeyVersion.Builder() .keyVersionLengthInBytes(keyVersionLength) .padding(Padding.PKCS5).build(); testEncryptDecryptKeyVersion(keyversion); } for (Integer keyVersionLength : new Integer[] {16, 24, 32}) { for (Mode mode : Mode.values()) { keyversion = new AESKeyVersion.Builder() .keyVersionLengthInBytes(keyVersionLength) .padding(Padding.PKCS5).mode(mode).build(); testEncryptDecryptKeyVersion(keyversion); } } }
Source:
private static void addAttachments(List<? extends Attachment> attachments, Map<String, Object> map, int revpos) { LinkedHashMap<String, Object> attsMap = new LinkedHashMap<String, Object>(); map.put("_attachments", attsMap); for (Attachment att : attachments) { SavedAttachment savedAtt = (SavedAttachment)att; HashMap<String, Object> theAtt = new HashMap<String, Object>(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Base64OutputStream bos = new Base64OutputStream(baos, true, 0, null); try { InputStream fis = savedAtt.getInputStream(); int bufSiz = 1024; byte[] buf = new byte[bufSiz]; int n = 0; do { n = fis.read(buf); if (n > 0) { bos.write(buf, 0, n); } } while (n > 0); if (savedAtt.revpos < revpos) { theAtt.put("stub", true); } else { theAtt.put("data", baos.toString()); } theAtt.put("content_type", savedAtt.type); theAtt.put("revpos", savedAtt.revpos); } catch (FileNotFoundException fnfe) { continue; } catch (IOException ioe) { continue; } attsMap.put(att.name, theAtt); } }

Target:
private static void addAttachments(List<? extends Attachment> attachments, Map<String, Object> map, int revpos) { LinkedHashMap<String, Object> attsMap = new LinkedHashMap<String, Object>(); map.put("_attachments", attsMap); for (Attachment att : attachments) { SavedAttachment savedAtt = (SavedAttachment)att; HashMap<String, Object> theAtt = new HashMap<String, Object>(); try { if (savedAtt.revpos < revpos) { theAtt.put("stub", true); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Base64OutputStream bos = new Base64OutputStream(baos, true, 0, null); InputStream fis = savedAtt.getInputStream(); int bufSiz = 1024; byte[] buf = new byte[bufSiz]; int n = 0; do { n = fis.read(buf); if (n > 0) { bos.write(buf, 0, n); } } while (n > 0); theAtt.put("data", baos.toString()); } theAtt.put("content_type", savedAtt.type); theAtt.put("revpos", savedAtt.revpos); } catch (IOException ioe) { Log.w(LOG_TAG, "Caught IOException in addAttachments whilst reading attachment " + att + ", skipping it: " + ioe); continue; } attsMap.put(att.name, theAtt); } }
Source:
public void testParseDisplayName() throws Exception { String directory = System.getenv("WinDir"); IntByReference pchEaten = new IntByReference(); PointerByReference ppidl = new PointerByReference(); IntByReference pdwAttributes = new IntByReference(); PointerByReference desktopFolder = new PointerByReference(); WinNT.HRESULT hResult = Shell32.INSTANCE.SHGetDesktopFolder(desktopFolder); assertEquals(COMUtils.S_OK, hResult.intValue()); IShellFolder shellFolder = IShellFolder.Converter.PointerToIShellFolder(desktopFolder); hResult = shellFolder.ParseDisplayName(new WinDef.HWND(Pointer.NULL), Pointer.NULL, directory, pchEaten, ppidl, pdwAttributes); assertEquals(COMUtils.S_OK, hResult.intValue()); }

Target:
public void testParseDisplayName() throws Exception { String directory = System.getenv("WinDir"); IntByReference pchEaten = new IntByReference(); PointerByReference ppidl = new PointerByReference(); IntByReference pdwAttributes = new IntByReference(); PointerByReference desktopFolder = new PointerByReference(); WinNT.HRESULT hResult = Shell32.INSTANCE.SHGetDesktopFolder(desktopFolder); assertEquals(COMUtils.S_OK, hResult.intValue()); IShellFolder shellFolder = IShellFolder.Converter.PointerToIShellFolder(desktopFolder); hResult = shellFolder.ParseDisplayName(null, null, directory, pchEaten, ppidl, pdwAttributes); assertEquals(COMUtils.S_OK, hResult.intValue()); }
Source:
public static synchronized String getRSAPublicString(String name, int length) { final SharedPreferences prefs = SalesforceSDKManager.getInstance().getAppContext().getSharedPreferences(ASYMM_SHARED_PREF_FILE, 0); final String id = prefs.getString(getSharedPrefKey(name), null); if (id != null) { RSA_IDS.put(name, id); return id; } else { String publicKeyBase64 = null; KeyPair keyPair = getKeyPair(name, length); if (keyPair != null) { PublicKey publicKey = keyPair.getPublic(); publicKeyBase64 = Base64.encodeToString(publicKey.getEncoded(), Base64.NO_WRAP); } prefs.edit().putString(getSharedPrefKey(name), publicKeyBase64).commit(); RSA_IDS.put(name, publicKeyBase64); return publicKeyBase64; } }

Target:
public static synchronized String getRSAPublicString(String name, int length) { String publicKeyBase64 = null; createRSAKeysIfNecessary(name, length); try { publicKeyBase64 = Base64.encodeToString(loadKeyStore().getCertificate(name).getPublicKey().getEncoded(), Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE); } catch (Exception e) { SalesforceSDKLogger.e(TAG, "Security exception thrown", e); } return publicKeyBase64; }
Source:
public static CredentialsProvider getCredentialsProvider() { return new CredentialsProvider() { @Override public String getHeaderName() { return javax.ws.rs.core.HttpHeaders.AUTHORIZATION; } @Override public String getAuthorization() { Principal principal = SecurityIntegrationFilter.getRequest().getUserPrincipal(); if (principal instanceof KeycloakPrincipal) { return new KeyCloakTokenCredentialsProvider().getAuthorization(); } else { return new SubjectCredentialsProvider().getAuthorization(); } } }; }

Target:
public static CredentialsProvider getCredentialsProvider() { return new CredentialsProvider() { KeyCloakTokenCredentialsProvider keyCloakProvider = new KeyCloakTokenCredentialsProvider(); SubjectCredentialsProvider subjectProvider = new SubjectCredentialsProvider(); @Override public String getHeaderName() { return javax.ws.rs.core.HttpHeaders.AUTHORIZATION; } @Override public String getAuthorization() { Principal principal = SecurityIntegrationFilter.getRequest().getUserPrincipal(); if (principal instanceof KeycloakPrincipal) { return keyCloakProvider.getAuthorization(); } else { return subjectProvider.getAuthorization(); } } }; }
Source:
public Page getNextPage() { if (finished) { return null; } long start = System.nanoTime(); try { List<Type> expectedTypes = columnHandles.stream().map(PinotColumnHandle::getDataType).collect(Collectors.toList()); PageBuilder pageBuilder = new PageBuilder(expectedTypes); ImmutableList.Builder<BlockBuilder> columnBlockBuilders = ImmutableList.builder(); ImmutableList.Builder<Type> columnTypes = ImmutableList.builder(); for (int idx : brokerPql.getColumnIndicesExpected()) { if (idx == -1) { continue; } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(idx); columnBlockBuilders.add(blockBuilder); columnTypes.add(expectedTypes.get(idx)); } int counter = issuePqlAndPopulate(brokerPql.getTable(), brokerPql.getPql(), brokerPql.getNumGroupByClauses(), columnBlockBuilders.build(), columnTypes.build()); pageBuilder.declarePositions(counter); Page page = pageBuilder.build(); finished = true; return page; } finally { readTimeNanos += System.nanoTime() - start; } }

Target:
public Page getNextPage() { if (finished) { return null; } long start = System.nanoTime(); try { List<Type> expectedTypes = columnHandles.stream() .map(PinotColumnHandle::getDataType) .collect(Collectors.toList()); PageBuilder pageBuilder = new PageBuilder(expectedTypes); ImmutableList.Builder<BlockBuilder> columnBlockBuilders = ImmutableList.builder(); ImmutableList.Builder<Type> columnTypes = ImmutableList.builder(); for (int i : brokerPql.getExpectedColumnIndices()) { if (i == -1) { continue; } BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(i); columnBlockBuilders.add(blockBuilder); columnTypes.add(expectedTypes.get(i)); } int counter = issuePqlAndPopulate( brokerPql.getTable(), brokerPql.getPql(), brokerPql.getGroupByClauses(), columnBlockBuilders.build(), columnTypes.build()); pageBuilder.declarePositions(counter); Page page = pageBuilder.build(); finished = true; return page; } finally { readTimeNanos += System.nanoTime() - start; } }
Source:
public void execute(Tuple tuple) { R obj = (R) tuple.getValue(0); LOG.info(String.valueOf(obj)); }

Target:
public void execute(Tuple tuple) { R obj = (R) tuple.getValue(0); LOG.info(String.valueOf(obj)); collector.ack(tuple); }
Source:
public Boolean getisLinearized() { if (baseObject == firstTrailer || linearizedDictionary == null) { return false; } return true; }

Target:
public Boolean getisLinearized() { return !(baseObject == firstTrailer || linearizedDictionary == null); }
Source:
private Set<RelColumnMapping> getColumnMappings(SqlOperator op) { SqlReturnTypeInference inference = op.getReturnTypeInference(); if (inference == null) { return null; } if (inference instanceof TableFunctionReturnTypeInference) { return ((TableFunctionReturnTypeInference) inference).getColumnMappings(); } else { return null; } }

Target:
private Set<RelColumnMapping> getColumnMappings(SqlOperator op) { SqlReturnTypeInference inference = op.getReturnTypeInference(); if (inference instanceof TableFunctionReturnTypeInference) { return ((TableFunctionReturnTypeInference) inference).getColumnMappings(); } else { return null; } }
Source:
private void runCommand(String command) throws KuraException { try { Process proc = Runtime.getRuntime().exec(command); proc.waitFor(); } catch (IOException e) { throw new KuraException(KuraErrorCode.OS_COMMAND_ERROR, e, "'" + command + "' failed"); } catch (InterruptedException e) { throw new KuraException(KuraErrorCode.OS_COMMAND_ERROR, e, "'" + command + "' failed"); } }

Target:
private void runCommand(String command) throws KuraException { try { Process proc = Runtime.getRuntime().exec(command); proc.waitFor(); } catch (IOException | InterruptedException e) { throw new KuraException(KuraErrorCode.OS_COMMAND_ERROR, e, "'" + command + "' failed"); } }
Source:
public Optional<UpdateDownloadLink> getLatestUpdateDownloadLinkForCurrentVersion() { if (listOfHTVersionsDownloadLink.isEmpty()) { return Optional.empty(); } Collections.sort(listOfHTVersionsDownloadLink, Collections.reverseOrder()); Version current = Version.getCurrentVersion(); Optional<UpdateDownloadLink> updateLink = listOfHTVersionsDownloadLink.stream() .filter(link -> link.getVersion().getMajor() == current.getMajor() || link.getVersion().getMajor() == current.getMajor() + 1) .findFirst(); if (updateLink.isPresent()) { return updateLink; } return Optional.empty(); }

Target:
public Optional<HtDownloadLink> getLatestUpdateDownloadLinkForCurrentVersion() { if (downloadLinks.isEmpty()) { return Optional.empty(); } Collections.sort(downloadLinks, Collections.reverseOrder()); return downloadLinks.stream() .filter(link -> Version.isVersionMajorSameOrJustOneGreaterFromCurrent(link.getVersion())).findFirst(); }
Source:
protected final void execute(final Channel channel) { channel.executingCalls.put(id,this); future = channel.executor.submit(new Runnable() { private int startIoId; private int calcLastIoId() { int endIoId = channel.lastIoId(); if (startIoId==endIoId) return 0; return endIoId; } public void run() { String oldThreadName = Thread.currentThread().getName(); Thread.currentThread().setName(oldThreadName+" for "+channel.getName()+" id="+id); try { Command rsp; CURRENT.set(Request.this); startIoId = channel.lastIoId(); try { channel.pipeWriter.get(lastIoId).get(); RSP r = Request.this.perform(channel); rsp = new Response<RSP,EXC>(id,calcLastIoId(),r); } catch (Throwable t) { rsp = new Response<RSP,Throwable>(id,calcLastIoId(),t); } finally { CURRENT.set(null); } if(chainCause) rsp.createdAt.initCause(createdAt); synchronized (channel) { if(!channel.isOutClosed()) { channel.send(rsp); } else { throw new ClosedChannelException(); } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to send back a reply to the request " + this, e); } finally { channel.executingCalls.remove(id); Thread.currentThread().setName(oldThreadName); } } }); }

Target:
protected final void execute(final Channel channel) { channel.executingCalls.put(id,this); future = channel.executor.submit(new Runnable() { private int startIoId; private int calcLastIoId() { int endIoId = channel.lastIoId(); if (startIoId==endIoId) return 0; return endIoId; } public void run() { String oldThreadName = Thread.currentThread().getName(); Thread.currentThread().setName(oldThreadName+" for "+channel.getName()+" id="+id); try { Command rsp; CURRENT.set(Request.this); startIoId = channel.lastIoId(); try { channel.pipeWriter.get(lastIoId).get(); RSP r = Request.this.perform(channel); rsp = new Response<RSP,EXC>(id,calcLastIoId(),r); } catch (Throwable t) { rsp = new Response<RSP,Throwable>(id,calcLastIoId(),t); } finally { CURRENT.set(null); } if(chainCause) rsp.createdAt.initCause(createdAt); channel.send(rsp); } catch (IOException e) { logger.log(Level.WARNING, "Failed to send back a reply to the request " + this, e); } finally { channel.executingCalls.remove(id); Thread.currentThread().setName(oldThreadName); } } }); }
Source:
public static Test suite() { if (CommonTestUtil.fixProxyConfiguration()) { CommonTestUtil.dumpSystemInfo(System.err); } TestSuite suite = new ManagedTestSuite(AllBugzillaTests.class.getName()); TestConfiguration testConfiguration = ManagedSuite.getTestConfiguration(); if (testConfiguration == null) { testConfiguration = TestConfiguration.getDefault(); } addTests(suite, testConfiguration); return suite; }

Target:
public static Test suite() { if (CommonTestUtil.fixProxyConfiguration()) { CommonTestUtil.dumpSystemInfo(System.err); } TestSuite suite = new ManagedTestSuite(AllBugzillaTests.class.getName()); TestConfiguration testConfiguration = ManagedSuite.getTestConfigurationOrCreateDefault(); addTests(suite, testConfiguration); return suite; }
Source:
public void setUp() throws InjectionException { final Injector injector = Tang.Factory.getTang().newInjector(); groupInfoMap = injector.getInstance(GroupInfoMap.class); injector.bindVolatileParameter(ThreadNumSoftLimit.class, THREAD_NUM_SOFT_LIMIT); handler = injector.getInstance(ProportionalGroupMetricHandler.class); }

Target:
public void setUp() throws InjectionException { final Injector injector = Tang.Factory.getTang().newInjector(); groupInfoMap = injector.getInstance(GroupInfoMap.class); injector.bindVolatileParameter(ThreadNumLimit.class, THREAD_NUM_SOFT_LIMIT); handler = injector.getInstance(ProportionalGroupMetricHandler.class); }
Source:
public Long getLogTail() { return logMetadata.getGlobalTail(); }

Target:
public long getLogTail() { return logMetadata.getGlobalTail(); }
Source:
public void testUseCatalog() throws Exception { TestingExecutor executor = new TestingExecutorBuilder() .setUseCatalogConsumer((ignored1, catalogName) -> { if (!catalogName.equals("cat")) { throw new SqlExecutionException("unexpected catalog name: " + catalogName); } }) .build(); InputStream inputStream = new ByteArrayInputStream("use catalog cat;\n".getBytes()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256); CliClient cliClient = null; SessionContext sessionContext = new SessionContext("test-session", new Environment()); String sessionId = executor.openSession(sessionContext); try (Terminal terminal = new DumbTerminal(inputStream, outputStream)) { cliClient = new CliClient(terminal, sessionId, executor, File.createTempFile("history", "tmp").toPath()); cliClient.open(); assertThat(executor.getNumUseCatalogCalls(), is(1)); String output = new String(outputStream.toByteArray()); assertFalse(output.contains("unexpected catalog name")); } finally { if (cliClient != null) { cliClient.close(); } } }

Target:
public void testUseCatalog() throws Exception { TestingExecutor executor = new TestingExecutorBuilder() .setUseCatalogConsumer((ignored1, catalogName) -> { if (!catalogName.equals("cat")) { throw new SqlExecutionException("unexpected catalog name: " + catalogName); } }) .build(); String output = testExecuteSql(executor, "use catalog cat;"); assertThat(executor.getNumUseCatalogCalls(), is(1)); assertFalse(output.contains("unexpected catalog name")); }
Source:
public List<String> getWordConfidence() { return wordConfidence; }

Target:
public List<SpeechWordConfidence> getWordConfidence() { return wordConfidence; }
Source:
private void scanDisks() { StorageDomain storageDomain = getSelectedItem(); Frontend.getInstance().runAction(VdcActionType.ScanStorageForUnregisteredDisks, new StorageDomainParametersBase(storageDomain.getStoragePoolId(), storageDomain.getId())); }

Target:
private void scanDisks() { StorageDomain storageDomain = getSelectedItem(); if (storageDomain != null) { Frontend.getInstance().runAction(VdcActionType.ScanStorageForUnregisteredDisks, new StorageDomainParametersBase(storageDomain.getStoragePoolId(), storageDomain.getId())); } }
Source:
private DiskImage mockDiskImage(Guid guid) { DiskImage disk = new DiskImage(); disk.setImageId(guid); ArrayList<Guid> storageIdList = new ArrayList<>(); storageIdList.add(storageDomainId); disk.setStorageIds(storageIdList); disk.setStoragePoolId(storagePoolId); disk.setActive(true); disk.setId(Guid.newGuid()); when(diskDao.get(guid)).thenReturn(disk); return disk; }

Target:
private DiskImage mockDiskImage(Guid guid) { DiskImage disk = new DiskImage(); disk.setImageId(guid); ArrayList<Guid> storageIds = new ArrayList<>(); storageIds.add(storageDomainId); disk.setStorageIds(storageIds); disk.setStoragePoolId(storagePoolId); disk.setActive(true); disk.setId(Guid.newGuid()); when(diskDao.get(guid)).thenReturn(disk); return disk; }
Source:
public InputStream[] call(CallContext callContext) { checkAllowedArgs(callContext.getEndpointState(), callContext.getSessionState(), callContext.getWorkUnit()); return getCaller().arrayCall(getClient(), callContext.getEndpointState(), callContext.getSessionState(), callContext.getWorkUnit()); }

Target:
public InputStream[] call(CallContext callContext) { try { return getResponseData(callContext, false); } catch(Exception ex) { throw new InternalError("Exception occurred while fetching data"); } }