auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object deserialize(ByteBuf b, CorfuRuntime rt) { int classNameLength = b.readShort(); byte[] classNameBytes = new byte[classNameLength]; b.readBytes(classNameBytes, 0, classNameLength); String className = new String(classNameBytes); if (className.equals("null")) { return null; } int jsonStringLen = b.readInt(); String jsonString = b.readCharSequence(jsonStringLen, StandardCharsets.UTF_8).toString(); try { return JSON.parseObject(jsonString, Class.forName(className)); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } }

Target:
public Object deserialize(ByteBuf b, CorfuRuntime rt) { int classNameLength = b.readShort(); byte[] classNameBytes = new byte[classNameLength]; b.readBytes(classNameBytes, 0, classNameLength); String className = new String(classNameBytes); if (className.equals("null")) { return null; } int numJsonBytes = b.readInt(); String jsonString = b.readCharSequence(numJsonBytes, StandardCharsets.UTF_8).toString(); try { return JSON.parseObject(jsonString, Class.forName(className)); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } }
Source:
public GlowHorse(Location location) { super(location, EntityType.HORSE); Random rand = new Random(); this.variant = Variant.HORSE; this.horseStyle = Style.values()[rand.nextInt(4)]; this.horseColor = Color.values()[rand.nextInt(6)]; }

Target:
public GlowHorse(Location location) { this(location, null); }
Source:
public Category getCategory() { return Category.MODEL; }

Target:
public Category getCategory() { return this.category; }
Source:
public void shouldReturnNullForEmptyFilename() { S3FileMapper s3FileMapper = new S3FileMapper(mockFileBrowser, mockFileHelper); S3File file = s3FileMapper.transform(null); assertNull(file); }

Target:
public void shouldReturnNullForEmptyFilename() { S3FileMapper s3FileMapper = new S3FileMapper(mockFileBrowser, mockFileHelper); S3File file = s3FileMapper.transform(""); assertNull(file); }
Source:
protected void populate(final int row, final DashboardInfo k) { if (k.isDefault()) { table.setWidget(row, 1, new Image(Gerrit.RESOURCES.greenCheck())); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.getElement(row, 1).setTitle(Util.C.dashboardDefaultToolTip()); } table.setWidget(row, 2, new Anchor(k.name(), "#" + link(k))); table.setText(row, 3, k.description()); if (project.get().equals(k.projectName())) { table.setText(row, 4, k.projectName()); } setRowItem(row, k); }

Target:
protected void populate(final int row, final DashboardInfo k) { if (k.isDefault()) { table.setWidget(row, 1, new Image(Gerrit.RESOURCES.greenCheck())); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.getElement(row, 1).setTitle(Util.C.dashboardDefaultToolTip()); } table.setWidget(row, 2, new Anchor(k.name(), "#" + link(k))); table.setText(row, 3, k.description()); if (!project.get().equals(k.projectName())) { table.setText(row, 4, k.projectName()); } setRowItem(row, k); }
Source:
private void waitForAllTasks() { while ( writerTaskCounter.get() > 0 ) { LockSupport.parkNanos( TimeUnit.MILLISECONDS.toNanos( 10 ) ); } }

Target:
private void waitForAllTasks() { try { Predicates.await( () -> writerTaskCounter.get() == 0, 10, TimeUnit.MINUTES, 10, TimeUnit.MILLISECONDS ); } catch ( Throwable t ) { throw new RuntimeException( t ); } }
Source:
public Iterator<SegmentWithOvershadowedStatus> getPublishedSegments() { if (isCacheEnabled) { Preconditions.checkState( lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS) && cachePopulated.get(), "hold on, still syncing published segments" ); synchronized (lock) { return publishedSegments.iterator(); } } else { return getMetadataSegments( coordinatorDruidLeaderClient, jsonMapper, responseHandler, segmentWatcherConfig.getWatchedDataSources() ); } }

Target:
public Iterator<SegmentWithOvershadowedStatus> getPublishedSegments() { if (isCacheEnabled) { Uninterruptibles.awaitUninterruptibly(cachePopulated); return publishedSegments.iterator(); } else { return getMetadataSegments( coordinatorDruidLeaderClient, jsonMapper, responseHandler, segmentWatcherConfig.getWatchedDataSources() ); } }
Source:
public void processRightWatermark(final MistWatermarkEvent event) { if (event.getTimestamp() < recentRightWatermark.getTimestamp()) { throw new RuntimeException("The timestamp of watermark should be greater or equal " + "than the previous event timestamp."); } recentRightWatermark = event; final long leftWatermarkTimestamp = recentLeftWatermark.getTimestamp(); final long rightWatermarkTimestamp = recentRightWatermark.getTimestamp(); final long minimumWatermark = getMinimumWatermark(leftWatermarkTimestamp, rightWatermarkTimestamp); drainUntilTimestamp(minimumWatermark); emitWatermarkUntilTimestamp(leftWatermarkTimestamp, rightWatermarkTimestamp, minimumWatermark); }

Target:
public void processRightWatermark(final MistWatermarkEvent event) { if (event.getTimestamp() < recentRightWatermark.getTimestamp()) { throw new RuntimeException("The timestamp of watermark should be greater or equal " + "than the previous event timestamp."); } recentRightWatermark = event; drainUntilMinimumWatermark(); }
Source:
public void testJWTExpirationToken() throws Exception { String url = getContextBaseUrl() + "/users"; String expiredToken = securityTokenProvider.getToken("admin", Collections.emptyMap(), 1); Thread.sleep(1500); given().header(HttpHeaders.AUTHORIZATION, expiredToken) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(url) .then() .statusCode(HttpStatus.UNAUTHORIZED.value()) .body("error", equalTo(UNAUTHORIZED_MESSAGE)); }

Target:
public void testJWTExpirationToken() throws Exception { String url = getContextBaseUrl() + "/users"; String expiredToken = securityTokenProvider.getToken("admin", Collections.emptyMap(), 3); given().header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(expiredToken)) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(url) .then() .statusCode(HttpStatus.OK.value()) .body(notNullValue()); Thread.sleep(3000); given().header(HttpHeaders.AUTHORIZATION, getAuthorizationHeader(expiredToken)) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .when() .get(url) .then() .statusCode(HttpStatus.UNAUTHORIZED.value()) .body("error", equalTo("expired")); }
Source:
public void testAnalysisExecution() { LttngKernelAnalysisModule module = new LttngKernelAnalysisModule(); module.setId("test"); try { module.setTrace(fTrace); } catch (TmfAnalysisException e) { fail(e.getMessage()); } ITmfStateSystem ss = module.getStateSystem(); assertNull(ss); assertTrue(TmfTestHelper.executeAnalysis(module)); ss = module.getStateSystem(); assertNotNull(ss); }

Target:
public void testAnalysisExecution() { LttngKernelAnalysisModule module = new LttngKernelAnalysisModule(); module.setId("test"); try { module.setTrace(fTrace); } catch (TmfAnalysisException e) { fail(e.getMessage()); } ITmfStateSystem ss = module.getStateSystem(); assertNull(ss); assertTrue(TmfTestHelper.executeAnalysis(module)); ss = module.getStateSystem(); assertNotNull(ss); List<Integer> quarks = ss.getQuarks("*"); assertFalse(quarks.isEmpty()); }
Source:
public List<String> getAllDatabases() { if (replay) { if (allDatabases.isPresent()) { return allDatabases.get(); } throw new PrestoException(NOT_FOUND, "Missing entry for all databases"); } List<String> result = delegate.getAllDatabases(); allDatabases = Optional.of(result); return result; }

Target:
public List<String> getAllDatabases() { if (replay) { return allDatabases.orElseThrow(() -> new PrestoException(NOT_FOUND, "Missing entry for all databases")); } List<String> result = delegate.getAllDatabases(); allDatabases = Optional.of(result); return result; }
Source:
private synchronized void onReceiverFinished(final String receiverId) { stateMachine.checkState(RECEIVERS_COMPLETED); receiverStateMachineMap.get(receiverId) .checkAndSetState(PushShuffleReceiverState.COMPLETED, PushShuffleReceiverState.FINISHED); numFinishedReceivers++; if (numFinishedSenders == totalNumSenders && numFinishedReceivers == totalNumReceivers) { LOG.log(Level.INFO, "The StaticPushShuffleManager is finished"); stateMachine.checkAndSetState(RECEIVERS_COMPLETED, FINISHED); } }

Target:
private synchronized void onReceiverFinished(final String receiverId) { stateMachine.checkState(RECEIVERS_COMPLETED); receiverStateMachineMap.get(receiverId) .checkAndSetState(PushShuffleReceiverState.COMPLETED, PushShuffleReceiverState.FINISHED); numFinishedReceivers++; if (isAllSendersAndReceiversFinished()) { finishManager(); } }
Source:
private SuiteRunner createSuiteRunner(XmlSuite xmlSuite) { SuiteRunner result = new SuiteRunner(getConfiguration(), xmlSuite, m_outputDir, m_testRunnerFactory, m_useDefaultListeners, m_methodInterceptors, Lists.newArrayList(m_invokedMethodListeners.values()), Lists.newArrayList(m_testListeners.values()), Lists.newArrayList(m_classListeners.values())); for (ISuiteListener isl : m_suiteListeners.values()) { result.addListener(isl); } for (IReporter r : result.getReporters()) { addListener(r); } for (IConfigurationListener cl : m_configuration.getConfigurationListeners()) { result.addConfigurationListener(cl); } return result; }

Target:
private SuiteRunner createSuiteRunner(XmlSuite xmlSuite) { SuiteRunner result = new SuiteRunner(getConfiguration(), xmlSuite, m_outputDir, m_testRunnerFactory, m_useDefaultListeners, m_methodInterceptors, m_invokedMethodListeners.values(), m_testListeners.values(), m_classListeners.values()); for (ISuiteListener isl : m_suiteListeners.values()) { result.addListener(isl); } for (IReporter r : result.getReporters()) { addListener(r); } for (IConfigurationListener cl : m_configuration.getConfigurationListeners()) { result.addConfigurationListener(cl); } return result; }
Source:
NetworkConfig getNetworkConfig() { String net = asString("network_mode"); if (net != null) { return new NetworkConfig(net); } Object networks = asObject("networks"); if (networks == null) { return null; } if (networks instanceof List) { List<String> toJoin = (List<String>) networks; if (toJoin.size() > 1) { throwIllegalArgumentException("'networks:' Only one custom network to join is supported currently"); } return new NetworkConfig(NetworkConfig.Mode.custom, toJoin.get(0)); } else if (networks instanceof Map) { Map<String,Object> toJoin = (Map<String, Object>) networks; if (toJoin.size() > 1) { throwIllegalArgumentException("'networks:' Only one custom network to join is supported currently"); } String custom = toJoin.keySet().iterator().next(); NetworkConfig ret = new NetworkConfig(NetworkConfig.Mode.custom, custom); Object aliases = toJoin.get(custom); if (aliases != null) { if (aliases instanceof List) { for (String alias : (List<String>) aliases) { ret.addAlias(alias); } } else if (aliases instanceof LinkedHashMap) { LinkedHashMap<String, ArrayList<String>> map = (LinkedHashMap<String, ArrayList<String>>) aliases; if (map.containsKey("aliases")) { for (String alias : map.get("aliases")) { ret.addAlias(alias); } } else { throwIllegalArgumentException( "'networks:' Aliases must be given as a linked has map of strings. 'aliases' key not founded"); } } else { throwIllegalArgumentException("'networks:' Aliases must be given as a list of string "); } } return ret; } else { throwIllegalArgumentException("'networks:' must beu either a list or a map"); return null; } }

Target:
NetworkConfig getNetworkConfig() { String net = asString("network_mode"); if (net != null) { return new NetworkConfig(net); } Object networks = asObject("networks"); if (networks == null) { return null; } if (networks instanceof List) { List<String> toJoin = (List<String>) networks; if (toJoin.size() > 1) { throwIllegalArgumentException("'networks:' Only one custom network to join is supported currently"); } return new NetworkConfig(NetworkConfig.Mode.custom, toJoin.get(0)); } else if (networks instanceof Map) { Map<String,Object> toJoin = (Map<String, Object>) networks; if (toJoin.size() > 1) { throwIllegalArgumentException("'networks:' Only one custom network to join is supported currently"); } String custom = toJoin.keySet().iterator().next(); NetworkConfig ret = new NetworkConfig(NetworkConfig.Mode.custom, custom); Object aliases = toJoin.get(custom); if (aliases != null) { if (aliases instanceof List) { for (String alias : (List<String>) aliases) { ret.addAlias(alias); } } else if (aliases instanceof Map) { Map<String, List<String>> map = (Map<String, List<String>>) aliases; if (map.containsKey("aliases")) { for (String alias : map.get("aliases")) { ret.addAlias(alias); } } else { throwIllegalArgumentException( "'networks:' Aliases must be given as a map of strings. 'aliases' key not founded"); } } else { throwIllegalArgumentException("'networks:' No aliases entry found in network config map"); } } return ret; } else { throwIllegalArgumentException("'networks:' must beu either a list or a map"); return null; } }
Source:
EagerQueryResult() { fields = originalResult.columns().toArray( new String[originalResult.columns().size()] ); }

Target:
EagerQueryResult() { fields = originalResult.columns().toArray( new String[0] ); }
Source:
public int getItemViewType(int position) { if (isPlaying) { if (position >= getItemCount() - 2) { return EMPTY_VIEW_TYPE; } return TACT_VIEW_TYPE; } if (position == getItemCount() - 1) { return PLUS_VIEW_TYPE; } else { return TACT_VIEW_TYPE; } }

Target:
public int getItemViewType(int position) { if (isPlaying) { if (position >= getItemCount() - EMPTY_VIEW_COUNT_ON_END) { return EMPTY_VIEW_TYPE; } return TACT_VIEW_TYPE; } if (position == getItemCount() - 1) { return PLUS_VIEW_TYPE; } else { return TACT_VIEW_TYPE; } }
Source:
public String toString() { return "NonTerminalAroundInvokeInvocationContext [method=" + method + ", interceptor=" + chain.get(position) + "]"; }

Target:
public String toString() { return "NonTerminalAroundInvokeInvocationContext [method=" + method + ", interceptor=" + chain.get(position) + ']'; }
Source:
private static void showFilterDialog(Context context, Feed selectedFeed) { FilterDialog filterDialog = new FilterDialog(context, selectedFeed.getItemFilter()) { @Override protected void updateFilter(Set<String> filterValues) { selectedFeed.setItemFilter(filterValues.toArray(new String[0])); DBWriter.setFeedItemsFilter(selectedFeed.getId(), filterValues); } }; filterDialog.openCustomDialog(); }

Target:
private static void showFilterDialog(Context context, Feed selectedFeed) { FilterDialog filterDialog = new FilterDialog(context, selectedFeed.getItemFilter()) { @Override protected void updateFilter(Set<String> filterValues) { selectedFeed.setItemFilter(filterValues.toArray(new String[0])); DBWriter.setFeedItemsFilter(selectedFeed.getId(), filterValues); } }; filterDialog.openDialog(); }
Source:
private String createColumn(Type type, int position) { String column = format("s._%d", position + 1); if (type.equals(BIGINT)) { return formatPredicate(column, "INT"); } if (type.equals(INTEGER)) { return formatPredicate(column, "INT"); } if (type.equals(SMALLINT)) { return formatPredicate(column, "INT"); } if (type.equals(TINYINT)) { return formatPredicate(column, "INT"); } if (type.equals(DoubleType.DOUBLE)) { return formatPredicate(column, "FLOAT"); } if (type.equals(RealType.REAL)) { return formatPredicate(column, "FLOAT"); } if (type.equals(BOOLEAN)) { return formatPredicate(column, "BOOL"); } if (type.equals(DATE)) { return formatPredicate(column, "TIMESTAMP"); } if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; return formatPredicate(column, format("DECIMAL(%s,%s)", decimalType.getPrecision(), decimalType.getScale())); } return column; }

Target:
private String createColumn(Type type, int position) { String column = format("s._%d", position + 1); if (type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT)) { return formatPredicate(column, "INT"); } if (type.equals(BOOLEAN)) { return formatPredicate(column, "BOOL"); } if (type.equals(DATE)) { return formatPredicate(column, "TIMESTAMP"); } if (type instanceof DecimalType) { DecimalType decimalType = (DecimalType) type; return formatPredicate(column, format("DECIMAL(%s,%s)", decimalType.getPrecision(), decimalType.getScale())); } return column; }
Source:
public static List<Integer> getDefaultSupportedVersions() { return Arrays.asList(0, 2, 3, 4); }

Target:
public static List<StorageFormatType> getDefaultSupportedVersions() { return Arrays.asList(V1, V2, V3, V4); }
Source:
protected void entityPropertyChanged(Object sender, PropertyChangedEventArgs e) { super.entityPropertyChanged(sender, e); if (e.PropertyName.equals("status")) { getSearchCommand().execute(); } }

Target:
protected void entityPropertyChanged(Object sender, PropertyChangedEventArgs e) { super.entityPropertyChanged(sender, e); getSearchCommand().execute(); }
Source:
private static boolean hasSourceGenTasks(@NotNull Project project) { return hasTask(project, new Function<JpsAndroidModuleProperties, String>() { @Override public String fun(JpsAndroidModuleProperties androidFacetState) { return androidFacetState.SOURCE_GEN_TASK_NAME; } }); }

Target:
private static boolean hasSourceGenTasks(@NotNull Project project) { Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { AndroidFacet androidFacet = Facets.getFirstFacetOfType(module, AndroidFacet.ID); if (androidFacet != null) { JpsAndroidModuleProperties androidFacetState = androidFacet.getProperties(); String taskName = androidFacetState.SOURCE_GEN_TASK_NAME; if (taskName != null && !taskName.isEmpty() && !"TODO".equalsIgnoreCase(taskName)) { return true; } } } return false; }
Source:
public IMarkerResolution[] getResolutions(IMarker marker) { WorkbenchMarkerResolution workbenchMarkerResolution = new WorkbenchMarkerResolution() { @Override public void run(IMarker marker) { if (marker.getResource() instanceof IProject) { try { IProject project = (IProject) marker.getResource(); ModelingProjectManager.INSTANCE.removeModelingNature(project, new NullProgressMonitor()); ModelingProjectManager.INSTANCE.createLocalRepresentationsFile(project, new NullProgressMonitor()); ModelingProjectManager.INSTANCE.convertToModelingProject(project, new NullProgressMonitor()); } catch (CoreException e) { SiriusEditPlugin.getPlugin().getLog().log(e.getStatus()); } } } @Override public String getLabel() { return Messages.CreateMissingRepresentationFileResolution_label; } @Override public Image getImage() { return null; } @Override public String getDescription() { return Messages.CreateMissingRepresentationFileResolution_description; } @Override public IMarker[] findOtherMarkers(IMarker[] markers) { return new IMarker[0]; } }; return new IMarkerResolution[] { workbenchMarkerResolution }; }

Target:
public IMarkerResolution[] getResolutions(IMarker marker) { WorkbenchMarkerResolution workbenchMarkerResolution = new WorkbenchMarkerResolution() { @Override public void run(IMarker marker) { if (marker.getResource() instanceof IProject) { try { IProject project = (IProject) marker.getResource(); ModelingProjectManager.INSTANCE.removeModelingNature(project, new NullProgressMonitor()); ModelingProjectManager.INSTANCE.convertToModelingProject(project, new NullProgressMonitor()); } catch (CoreException e) { SiriusEditPlugin.getPlugin().getLog().log(e.getStatus()); } } } @Override public String getLabel() { return Messages.CreateMissingRepresentationFileResolution_label; } @Override public Image getImage() { return null; } @Override public String getDescription() { return Messages.CreateMissingRepresentationFileResolution_description; } @Override public IMarker[] findOtherMarkers(IMarker[] markers) { return new IMarker[0]; } }; return new IMarkerResolution[] { workbenchMarkerResolution }; }
Source:
static <T> InstanceFactory<T> findFactoryFor(Class<T> type) { @SuppressWarnings("unchecked") final Constructor<T>[] constructors = (Constructor<T>[]) type.getDeclaredConstructors(); List<InstanceFactory<T>> annotatedFactories = Stream.concat( Stream.of(constructors) .filter(constructor -> constructor.isAnnotationPresent(JdbiConstructor.class)) .map(ConstructorInstanceFactory::new), Stream.of(type.getDeclaredMethods()) .filter(method -> method.isAnnotationPresent(JdbiConstructor.class)) .map(method -> new StaticMethodInstanceFactory<>(type, method))) .collect(Collectors.toList()); if (annotatedFactories.size() > 1) { throw new IllegalArgumentException(type + " must have at most one constructor or static factory method annotated @JdbiConstructor"); } if (annotatedFactories.size() == 1) { return annotatedFactories.get(0); } return new ConstructorInstanceFactory<>(findImplicitConstructorFor(type)); }

Target:
static <T> InstanceFactory<T> findFactoryFor(Class<T> type) { @SuppressWarnings("unchecked") final Constructor<T>[] constructors = (Constructor<T>[]) type.getDeclaredConstructors(); List<Constructor<T>> explicitConstructors = Stream.of(constructors) .filter(constructor -> constructor.isAnnotationPresent(JdbiConstructor.class)) .collect(Collectors.toList()); List<Method> explicitFactoryMethods = Stream.of(type.getDeclaredMethods()) .filter(method -> method.isAnnotationPresent(JdbiConstructor.class)) .collect(Collectors.toList()); if (explicitConstructors.size() + explicitFactoryMethods.size() > 1) { throw new IllegalArgumentException(type + " may have at most one constructor or static factory method annotated @JdbiConstructor"); } if (explicitConstructors.size() == 1) { return new ConstructorInstanceFactory<>(explicitConstructors.get(0)); } if (explicitFactoryMethods.size() == 1) { return new StaticMethodInstanceFactory<>(type, explicitFactoryMethods.get(0)); } return new ConstructorInstanceFactory<>(findImplicitConstructorFor(type)); }
Source:
public void add(Key k, Value v) { if (key == null) { key = k; timeStamps.add(k.getTimestamp()); values.add(v); size++; } else if (key.compareRow(k.getRow()) == 0 && key.compareColumnFamily(k.getColumnFamily()) == 0) { timeStamps.add(k.getTimestamp()); values.add(v); } else { } }

Target:
public void add(Key k, Value v) throws IllegalArgumentException { add(k, v.get()); }
Source:
protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); path.reset(); rect.set(0, 0, w, h); int maxModalWidthPx = getResources().getDimensionPixelSize(R.dimen.swrve__conversation_max_modal_width); float radiusToApply = getWidth() >= maxModalWidthPx ? radius : 0; path.addRoundRect(rect, radiusToApply, radiusToApply, Path.Direction.CW); path.close(); }

Target:
protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); path.reset(); rect.set(0, 0, w, h); float radiusToApply = getWidth() >= maxModalWidthPx ? radius : 0; path.addRoundRect(rect, radiusToApply, radiusToApply, Path.Direction.CW); path.close(); }
Source:
private void deleteIfExists(File file) { if (!file.exists()) { return; } if (file.isDirectory()) { for (File sub : file.listFiles()) { deleteIfExists(sub); } } file.delete(); }

Target:
private void deleteIfExists(File file) throws IOException { if (!file.exists()) { return; } if (file.isDirectory()) { for (File sub : file.listFiles()) { deleteIfExists(sub); } } if (!file.delete()) { throw new IOException("Failed to delete file: " + file); } }
Source:
public void testCleansUpItsLittleTurdlings() throws Exception { curator.start(); curator.blockUntilConnected(); NodeAnnouncer announcer = new NodeAnnouncer(curator); final byte[] billy = StringUtils.toUtf8("billy"); final String testPath = "/somewhere/test2"; final String parent = ZKPaths.getPathAndNode(testPath).getPath(); announcer.start(); try { Assert.assertNull(curator.checkExists().forPath(parent)); awaitAnnounce(announcer, testPath, billy, true); Assert.assertNotNull(curator.checkExists().forPath(parent)); } finally { announcer.stop(); } Assert.assertNull(curator.checkExists().forPath(parent)); }

Target:
public void testCleansUpItsLittleTurdlings() throws Exception { curator.start(); curator.blockUntilConnected(); NodeAnnouncer announcer = new NodeAnnouncer(curator); final byte[] billy = StringUtils.toUtf8("billy"); final String testPath = "/somewhere/test2"; final String parent = ZKPathsUtils.getParentPath(testPath); announcer.start(); try { Assert.assertNull(curator.checkExists().forPath(parent)); awaitAnnounce(announcer, testPath, billy, true); Assert.assertNotNull(curator.checkExists().forPath(parent)); } finally { announcer.stop(); } Assert.assertNull(curator.checkExists().forPath(parent)); }
Source:
public void loadConfigsIn(Context context) { ModuleEnvironment environment = context.get(ModuleManager.class).getEnvironment(); this.context = context; for (Class<? extends AutoConfig> configClass : environment.getSubtypesOf(AutoConfig.class)) { if (context.get(configClass) != null) { continue; } SimpleUri configId = ReflectionUtil.getSimpleUriFor(configClass, environment); loadConfig(configClass, configId); } this.context = null; }

Target:
public void loadConfigsIn(Context context) { ModuleEnvironment environment = context.get(ModuleManager.class).getEnvironment(); this.context = context; for (Class<? extends AutoConfig> configClass : environment.getSubtypesOf(AutoConfig.class)) { if (context.get(configClass) != null) { continue; } SimpleUri configId = ReflectionUtil.getFullyQualifiedSimpleUriFor(configClass, environment); loadConfig(configClass, configId); } this.context = null; }
Source:
private void doFlush(Map<String, FileState> toRemove) { Map<String, FileState> toRestore = new HashMap<>(); boolean interrupted = false; for (Entry<String, FileState> entry : toRemove.entrySet()) { if (!interrupted && entry.getValue().close()) { if (FileWritingMessageHandler.this.logger.isDebugEnabled()) { FileWritingMessageHandler.this.logger.debug("Flushed: " + entry.getKey()); } } else { interrupted = true; toRestore.put(entry.getKey(), entry.getValue()); } } if (interrupted) { if (FileWritingMessageHandler.this.logger.isDebugEnabled()) { FileWritingMessageHandler.this.logger.debug("Flushed: " + toRestore.keySet()); } synchronized (this) { for (Entry<String, FileState> entry : toRestore.entrySet()) { this.fileStates.putIfAbsent(entry.getKey(), entry.getValue()); } } } }

Target:
private void doFlush(Map<String, FileState> toRemove) { Map<String, FileState> toRestore = new HashMap<>(); boolean interrupted = false; for (Entry<String, FileState> entry : toRemove.entrySet()) { if (!interrupted && entry.getValue().close()) { if (FileWritingMessageHandler.this.logger.isDebugEnabled()) { FileWritingMessageHandler.this.logger.debug("Flushed: " + entry.getKey()); } } else { interrupted = true; toRestore.put(entry.getKey(), entry.getValue()); } } if (interrupted) { if (FileWritingMessageHandler.this.logger.isDebugEnabled()) { FileWritingMessageHandler.this.logger .debug("Interrupted during flush; not flushed: " + toRestore.keySet()); } synchronized (this) { for (Entry<String, FileState> entry : toRestore.entrySet()) { this.fileStates.putIfAbsent(entry.getKey(), entry.getValue()); } } } }
Source:
public void processRecord(ComputationContext context, String inputStreamName, Record record) { BulkBucket bucket = BulkCodecs.getBucketCodec().decode(record.getData()); LoginContext loginContext = null; try { loginContext = Framework.loginAsUser("Administrator"); command = getCommand(bucket.getCommandId()); if (command != null) { startBucket(record.getKey()); for (List<String> batch : Lists.partition(bucket.getIds(), command.getBatchSize())) { processBatchOfDocuments(batch); } endBucket(context, bucket.getIds().size()); context.askForCheckpoint(); } else { if (isAbortedCommand(bucket.getCommandId())) { log.debug("Skipping aborted command: {}", bucket.getCommandId()); context.askForCheckpoint(); } else { log.error("Stopping processing, unknown command: {}, offset: {}, record: {}.", bucket.getCommandId(), context.getLastOffset(), record); context.askForTermination(); } } loginContext.logout(); } catch (LoginException e) { e.printStackTrace(); } }

Target:
public void processRecord(ComputationContext context, String inputStreamName, Record record) { BulkBucket bucket = BulkCodecs.getBucketCodec().decode(record.getData()); command = getCommand(bucket.getCommandId()); if (command != null) { startBucket(record.getKey()); for (List<String> batch : Lists.partition(bucket.getIds(), command.getBatchSize())) { processBatchOfDocuments(batch); } endBucket(context, bucket.getIds().size()); context.askForCheckpoint(); } else { if (isAbortedCommand(bucket.getCommandId())) { log.debug("Skipping aborted command: {}", bucket.getCommandId()); context.askForCheckpoint(); } else { log.error("Stopping processing, unknown command: {}, offset: {}, record: {}.", bucket.getCommandId(), context.getLastOffset(), record); context.askForTermination(); } } }
Source:
public CompletableFuture<ClusterOverview> requestClusterOverview(Time timeout) { CompletableFuture<ResourceOverview> taskManagerOverviewFuture = runResourceManagerCommand(resourceManagerGateway -> resourceManagerGateway.requestResourceOverview(timeout)); final List<CompletableFuture<Optional<JobStatus>>> optionalJobInformation = queryJobMastersForInformation(dj -> dj.requestJobStatus(timeout)); CompletableFuture<Collection<Optional<JobStatus>>> allOptionalJobsFuture = FutureUtils.combineAll(optionalJobInformation); CompletableFuture<Collection<JobStatus>> allJobsFuture = allOptionalJobsFuture.thenApply(this::flattenOptionalCollection); final JobsOverview completedJobsOverview = archivedExecutionGraphStore.getStoredJobsOverview(); return allJobsFuture.thenCombine( taskManagerOverviewFuture, (Collection<JobStatus> runningJobsStatus, ResourceOverview resourceOverview) -> { final JobsOverview allJobsOverview = JobsOverview.create(runningJobsStatus).combine(completedJobsOverview); return new ClusterOverview(resourceOverview, allJobsOverview); }); }

Target:
public CompletableFuture<ClusterOverview> requestClusterOverview(Time timeout) { CompletableFuture<ResourceOverview> taskManagerOverviewFuture = runResourceManagerCommand(resourceManagerGateway -> resourceManagerGateway.requestResourceOverview(timeout)); final List<CompletableFuture<Optional<JobStatus>>> optionalJobInformation = queryJobMastersForInformation(dispatcherJob -> dispatcherJob.requestJobStatus(timeout)); CompletableFuture<Collection<Optional<JobStatus>>> allOptionalJobsFuture = FutureUtils.combineAll(optionalJobInformation); CompletableFuture<Collection<JobStatus>> allJobsFuture = allOptionalJobsFuture.thenApply(this::flattenOptionalCollection); final JobsOverview completedJobsOverview = archivedExecutionGraphStore.getStoredJobsOverview(); return allJobsFuture.thenCombine( taskManagerOverviewFuture, (Collection<JobStatus> runningJobsStatus, ResourceOverview resourceOverview) -> { final JobsOverview allJobsOverview = JobsOverview.create(runningJobsStatus).combine(completedJobsOverview); return new ClusterOverview(resourceOverview, allJobsOverview); }); }
Source:
public Double getBuckle(int bp) { if (bp < 0 || bp >= getPairingParameters().length) return null; return pairingParameters[bp][0]; }

Target:
public Double getBuckle(int bp) { checkArgument(bp); return pairingParameters[bp][0]; }
Source:
public void endWindow() { Map<KafkaPartition, Long> carryOn = new HashMap<>(offsetStats); offsetTrackHistory.add(Pair.of(currentWindowId, carryOn)); if (currentWindowId > idempotentStorageManager.getLargestRecoveryWindow()) { try { idempotentStorageManager.save(currentWindowRecoveryState, operatorId, currentWindowId); } catch (IOException e) { throw new RuntimeException("saving recovery", e); } } currentWindowRecoveryState.clear(); }

Target:
public void endWindow() { if (getConsumer() instanceof SimpleKafkaConsumer) { Map<KafkaPartition, Long> carryOn = new HashMap<>(offsetStats); offsetTrackHistory.add(Pair.of(currentWindowId, carryOn)); } if (currentWindowId > idempotentStorageManager.getLargestRecoveryWindow()) { try { idempotentStorageManager.save(currentWindowRecoveryState, operatorId, currentWindowId); } catch (IOException e) { throw new RuntimeException("saving recovery", e); } } currentWindowRecoveryState.clear(); }
Source:
public JobCoordinator getCurrentJobCoordinator() { return jobCoordinator; }

Target:
JobCoordinator getCurrentJobCoordinator() { return jobCoordinator; }
Source:
public CompilationUnit() { this(null, false, null, new NodeList<>(), new NodeList<>(), null); }

Target:
public CompilationUnit() { this(null, null, new NodeList<>(), new NodeList<>(), null); }
Source:
public void setUp() throws Exception { super.setUp(); _conn = con; Properties props = new Properties(); PGProperty.STRING_TYPE.set(props, "unspecified"); _stringTypeUnspecifiedConn = TestUtil.openDB(props); TestUtil.createTable(_conn, "arrtest", "intarr int[], decarr decimal(2,1)[], strarr text[]" + (TestUtil.haveMinimumServerVersion(_conn, ServerVersion.v8_3) ? ", uuidarr uuid[]" : "") + ", floatarr float8[]" + ", intarr2 int4[][]"); TestUtil.createTable(_conn, "arrcompprnttest", "id serial, name character(10)"); TestUtil.createTable(_conn, "arrcompchldttest", "id serial, name character(10), description character varying, parent integer"); TestUtil.createTable(_conn, "\"CorrectCasing\"", "id serial"); TestUtil.createTable(_conn, "\"Evil.Table\"", "id serial"); }

Target:
public void setUp() throws Exception { super.setUp(); _conn = con; TestUtil.createTable(_conn, "arrtest", "intarr int[], decarr decimal(2,1)[], strarr text[]" + (TestUtil.haveMinimumServerVersion(_conn, ServerVersion.v8_3) ? ", uuidarr uuid[]" : "") + ", floatarr float8[]" + ", intarr2 int4[][]"); TestUtil.createTable(_conn, "arrcompprnttest", "id serial, name character(10)"); TestUtil.createTable(_conn, "arrcompchldttest", "id serial, name character(10), description character varying, parent integer"); TestUtil.createTable(_conn, "\"CorrectCasing\"", "id serial"); TestUtil.createTable(_conn, "\"Evil.Table\"", "id serial"); }
Source:
public void initialize(SpecialTimestampsSupplier timestamps, KeyValueService kvs) { Schemas.createTablesAndIndexes(TargetedSweepSchema.INSTANCE.getLatestSchema(), kvs); queue = SweepQueue.create(kvs, shardsConfig); timestampsSupplier = timestamps; conservativeScheduler.scheduleBackgroundThreads(); thoroughScheduler.scheduleBackgroundThreads(); }

Target:
public void initialize(SpecialTimestampsSupplier timestamps, KeyValueService kvs) { if (isInitialized) { return; } Preconditions.checkState(kvs.isInitialized(), "Attempted to initialize targeted sweeper with an uninitialized backing KVS."); Schemas.createTablesAndIndexes(TargetedSweepSchema.INSTANCE.getLatestSchema(), kvs); queue = SweepQueue.create(kvs, shardsConfig); timestampsSupplier = timestamps; conservativeScheduler.scheduleBackgroundThreads(); thoroughScheduler.scheduleBackgroundThreads(); isInitialized = true; }
Source:
private void emitCreateExpectedObjectSchemaInfo(JavaWriter writer) throws IOException { writer.beginMethod( "OsObjectSchemaInfo", "createExpectedObjectSchemaInfo", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC)); writer.emitStatement( "OsObjectSchemaInfo info = new OsObjectSchemaInfo(\"%s\");", this.simpleClassName); for (VariableElement field : metadata.getFields()) { String fieldName = field.getSimpleName().toString(); Constants.RealmFieldType fieldType = getRealmType(field); switch (fieldType) { case NOTYPE: break; case OBJECT: String fieldTypeSimpleName = Utils.getFieldTypeSimpleName(field); writer.emitStatement("info.add(\"%s\", RealmFieldType.OBJECT, \"%s\")", fieldName, fieldTypeSimpleName); break; case LIST: String genericTypeSimpleName = Utils.getGenericTypeSimpleName(field); writer.emitStatement("info.add(\"%s\", RealmFieldType.LIST, \"%s\")", fieldName, genericTypeSimpleName); break; default: String nullableFlag = (metadata.isNullable(field) ? "!" : "") + "Property.REQUIRED"; String indexedFlag = (metadata.isIndexed(field) ? "" : "!") + "Property.INDEXED"; String primaryKeyFlag = (metadata.isPrimaryKey(field) ? "" : "!") + "Property.PRIMARY_KEY"; writer.emitStatement("info.add(\"%s\", %s, %s, %s, %s)", fieldName, fieldType.getRealmType(), primaryKeyFlag, indexedFlag, nullableFlag); } } writer.emitStatement("return info"); writer.endMethod() .emitEmptyLine(); }

Target:
private void emitCreateExpectedObjectSchemaInfo(JavaWriter writer) throws IOException { writer.beginMethod( "OsObjectSchemaInfo", "createExpectedObjectSchemaInfo", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC)); writer.emitStatement( "OsObjectSchemaInfo.Builder builder = new OsObjectSchemaInfo.Builder(\"%s\")", this.simpleClassName); for (VariableElement field : metadata.getFields()) { String fieldName = field.getSimpleName().toString(); Constants.RealmFieldType fieldType = getRealmType(field); switch (fieldType) { case NOTYPE: break; case OBJECT: String fieldTypeSimpleName = Utils.getFieldTypeSimpleName(field); writer.emitStatement("builder.addLinkedProperty(\"%s\", RealmFieldType.OBJECT, \"%s\")", fieldName, fieldTypeSimpleName); break; case LIST: String genericTypeSimpleName = Utils.getGenericTypeSimpleName(field); writer.emitStatement("builder.addLinkedProperty(\"%s\", RealmFieldType.LIST, \"%s\")", fieldName, genericTypeSimpleName); break; default: String nullableFlag = (metadata.isNullable(field) ? "!" : "") + "Property.REQUIRED"; String indexedFlag = (metadata.isIndexed(field) ? "" : "!") + "Property.INDEXED"; String primaryKeyFlag = (metadata.isPrimaryKey(field) ? "" : "!") + "Property.PRIMARY_KEY"; writer.emitStatement("builder.addProperty(\"%s\", %s, %s, %s, %s)", fieldName, fieldType.getRealmType(), primaryKeyFlag, indexedFlag, nullableFlag); } } writer.emitStatement("return builder.build()"); writer.endMethod() .emitEmptyLine(); }
Source:
public void checkPortVisibility() throws Exception { simpleImport("resources/rt/PortModel.emx"); openEditor(); rootPackage.getOwnedElements().stream() .filter(Port.class::isInstance) .filter(p -> !((Port) p).isService()) .forEach(port -> assertEquals(" Port visibility Error: port should be protected", VisibilityKind.PROTECTED_LITERAL, ((Port) port).getVisibility())); }

Target:
public void checkPortVisibility() throws Exception { simpleImport("resources/rt/PortModel.emx"); openEditor(); rootPackage.allOwnedElements().stream() .filter(Port.class::isInstance) .filter(p -> !((Port) p).isService()) .forEach(port -> assertEquals(" Port visibility Error: port should be protected", VisibilityKind.PROTECTED_LITERAL, ((Port) port).getVisibility())); }
Source:
public boolean isCorrectMutator(MethodSource<JavaClassSource> method, PropertySource<JavaClassSource> property) { String returnType = method.getReturnType().getName(); String className = property.getOrigin().getName(); return returnType.equals(className); }

Target:
public boolean isCorrectMutator(MethodSource<JavaClassSource> method, PropertySource<JavaClassSource> property) { String returnType = method.getReturnType().getName(); String className = property.getOrigin().getName(); return className.equals(returnType); }
Source:
public static String generateStructMemberArrayParserBlock(final String structResponseTypeName, final StructMember structMember) throws ParseException { final StringBuilder outputBuilder = new StringBuilder(); outputBuilder.append(indent(3)).append("GPtrArray* ").append(structMember.getName()).append("_array = _parse_").append(structResponseTypeName).append("(log, doc, child_node);\n"). append(indent(3)).append("response").append("->").append(structMember.getName()).append(" = (").append(structMember.getType()).append(")").append(structMember.getName()).append("_array->pdata;\n"). append(indent(3)).append("response").append("->num_").append(structMember.getName()).append(" = ").append(structMember.getName()).append("_array->len;\n"). append(indent(3)).append("g_ptr_array_free(").append(structMember.getName()).append("_array, FALSE);\n"); return outputBuilder.toString(); }

Target:
public static String generateStructMemberArrayParserBlock(final String structResponseTypeName, final StructMember structMember) throws ParseException { return indent(3) + "GPtrArray* " + structMember.getName() + "_array = _parse_" + structResponseTypeName + "(log, doc, child_node);\n" + indent(3) + "response->" + structMember.getName() + " = (" + structMember.getType() + ")" + structMember.getName() + "_array->pdata;\n" + indent(3) + "response->num_" + structMember.getName() + " = " + structMember.getName() + "_array->len;\n" + indent(3) + "g_ptr_array_free(" + structMember.getName() + "_array, FALSE);\n"; }
Source:
public void test2() throws IOException { Text colf = new Text("a"); Text colq = new Text("b"); Value dv = new Value(); TreeMap<Key,Value> tm = new TreeMap<>(); for (int i = 0; i < 1000; i++) { Key k = new Key(new Text(String.format("%03d", i)), colf, colq); k.setTimestamp(i); tm.put(k, dv); } assertTrue(tm.size() == 1000); SortedKeyValueIterator<Key,Value> a = new AgeOffFilter(); IteratorSetting is = new IteratorSetting(1, AgeOffFilter.class); AgeOffFilter.setTTL(is, 101l); AgeOffFilter.setCurrentTime(is, 1001l); AgeOffFilter.setNegate(is, true); assertTrue(((AgeOffFilter) a).validateOptions(is.getOptions())); try { ((AgeOffFilter) a).validateOptions(EMPTY_OPTS); assertTrue(false); } catch (IllegalArgumentException e) a.init(new SortedMapIterator(tm), is.getOptions(), null); a = a.deepCopy(null); SortedKeyValueIterator<Key,Value> copy = a.deepCopy(null); a.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(900, size(a)); copy.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(900, size(copy)); }

Target:
public void test2() throws IOException { Text colf = new Text("a"); Text colq = new Text("b"); Value dv = new Value(); TreeMap<Key,Value> tm = new TreeMap<>(); for (int i = 0; i < 1000; i++) { Key k = new Key(new Text(String.format("%03d", i)), colf, colq); k.setTimestamp(i); tm.put(k, dv); } assertTrue(tm.size() == 1000); SortedKeyValueIterator<Key,Value> a = new AgeOffFilter(); IteratorSetting is = new IteratorSetting(1, AgeOffFilter.class); AgeOffFilter.setTTL(is, 101l); AgeOffFilter.setCurrentTime(is, 1001l); AgeOffFilter.setNegate(is, true); assertTrue(((AgeOffFilter) a).validateOptions(is.getOptions())); try { ((AgeOffFilter) a).validateOptions(EMPTY_OPTS); assertTrue(false); } catch (IllegalArgumentException e) a.init(new SortedMapIterator(tm), is.getOptions(), null); a = a.deepCopy(null); SortedKeyValueIterator<Key,Value> copy = a.deepCopy(null); a.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(size(a), 900); copy.seek(new Range(), EMPTY_COL_FAMS, false); assertEquals(size(copy), 900); }
Source:
public static RegionInfo parseRegionInfoFromRegionName(byte[] regionName) throws IOException { byte[][] fields = RegionInfo.parseRegionName(regionName); long regionId = Long.parseLong(Bytes.toString(fields[2])); int replicaId = fields.length > 3 ? Integer.parseInt(Bytes.toString(fields[3]), 16) : 0; return RegionInfoBuilder.newBuilder(TableName.valueOf(fields[0])).setStartKey(fields[1]) .setSplit(false).setRegionId(regionId).setReplicaId(replicaId).build(); }

Target:
public static RegionInfo parseRegionInfoFromRegionName(byte[] regionName) throws IOException { byte[][] fields = RegionInfo.parseRegionName(regionName); long regionId = Long.parseLong(Bytes.toString(fields[2])); int replicaId = fields.length > 3 ? Integer.parseInt(Bytes.toString(fields[3]), 16) : 0; return RegionInfoBuilder.newBuilder(TableName.valueOf(fields[0])).setStartKey(fields[1]) .setRegionId(regionId).setReplicaId(replicaId).build(); }
Source:
public void testCopy() { final DSLVariableValue original = new DSLVariableValue("value"); final DSLVariableValue copy = original.copy(); assertEquals(original, copy); assertNotSame(original, copy); }

Target:
public void testCopy() { final DSLVariableValue original = new DSLVariableValue("value"); final DSLVariableValue copy = original.copy(); assertEquals(original.getValue(), copy.getValue()); assertEquals(original, copy); assertNotSame(original, copy); }
Source:
public void testCountStar33() { List<AbstractPlanNode> pn = compileToFragments("SELECT COUNT(*) FROM T_ENG_11096 WHERE a = 1 AND b IS NOT DISTINCT FROM CAST(NULL AS INT) AND c > 1"); checkIndexCounter(pn, true); pn = compileToFragments("SELECT COUNT(1) FROM T_ENG_11096 WHERE a = 1 AND b IS NOT DISTINCT FROM CAST(NULL AS INT) AND c > 1"); checkIndexCounter(pn, true); pn = compileToFragments("SELECT COUNT(*) FROM T_ENG_11096 WHERE a = 1 AND b IS NOT DISTINCT FROM CAST(NULL AS INT)"); for ( AbstractPlanNode nd : pn) System.out.println("PlanNode Explain string:\n" + nd.toExplainPlanString()); AbstractPlanNode p = pn.get(0).getChild(0); assertTrue(p instanceof IndexScanPlanNode); assertNotNull(p.getInlinePlanNode(PlanNodeType.AGGREGATE)); }

Target:
public void testCountStar33() { List<AbstractPlanNode> pn = compileToFragments("SELECT COUNT(*) FROM T_ENG_11096 WHERE a = 1 AND b IS NOT DISTINCT FROM CAST(NULL AS INT) AND c > 1"); checkIndexCounter(pn, true); checkCompareNotDistinctFlags(pn.get(0).getChild(0), false, true, false); pn = compileToFragments("SELECT COUNT(1) FROM T_ENG_11096 WHERE a = 1 AND b IS NOT DISTINCT FROM CAST(NULL AS INT) AND c > 1"); checkIndexCounter(pn, true); checkCompareNotDistinctFlags(pn.get(0).getChild(0), false, true, false); pn = compileToFragments("SELECT COUNT(*) FROM T_ENG_11096 WHERE a = 1 AND b IS NOT DISTINCT FROM CAST(NULL AS INT)"); for ( AbstractPlanNode nd : pn) System.out.println("PlanNode Explain string:\n" + nd.toExplainPlanString()); AbstractPlanNode p = pn.get(0).getChild(0); checkCompareNotDistinctFlags(p, false, true); assertNotNull(p.getInlinePlanNode(PlanNodeType.AGGREGATE)); }
Source:
public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); ATMItem item = (ATMItem) getListView().getItemAtPosition(position); mOnItemSelectedListener.onItemSelected(item); }

Target:
public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); ATMItem item = (ATMItem) getListView().getItemAtPosition(position); if(!mSelectedItems.contains(item)) { mSelectedItems.add(item); }else{ mSelectedItems.remove(item); } }
Source:
public ValidationResult isBackupStorageDomainUpdatedWithRunningVmAndNoVmLease() { List<VM> vms = vmDao.getAllActiveForStorageDomain(storageDomain.getId()); List<String> invalidVmsForBackupStorageDomain = vms.stream() .filter(vm -> vm.getDiskMap() .values() .stream() .filter(DisksFilter.ONLY_IMAGES) .filter(DisksFilter.ONLY_PLUGGED) .map(DiskImage.class::cast) .anyMatch(vmDisk -> vmDisk.getStorageIds().get(0).equals(storageDomain.getId()))) .map(vm -> vm.getName()) .collect(Collectors.toList()); QueryReturnValue ret = getBackend().runInternalQuery( QueryType.GetEntitiesWithLeaseByStorageId, new IdQueryParameters(storageDomain.getId())); if (ret != null && ret.getReturnValue() != null && ret.getSucceeded()) { for (VmBase vmBase : ret.<List<VmBase>> getReturnValue()) { invalidVmsForBackupStorageDomain.add(vmBase.getName()); } } if (invalidVmsForBackupStorageDomain.isEmpty()) { return ValidationResult.VALID; } else { return new ValidationResult( EngineMessage.ACTION_TYPE_FAILED_RUNNING_VM_OR_VM_LEASES_PRESENT_ON_STORAGE_DOMAIN); } }

Target:
public ValidationResult isBackupStorageDomainUpdatedWithRunningVmAndNoVmLease() { List<VM> vms = vmDao.getAllActiveForStorageDomain(storageDomain.getId()); List<String> invalidVmsForBackupStorageDomain = vms.stream() .filter(vm -> vm.getDiskMap() .values() .stream() .filter(DisksFilter.ONLY_IMAGES) .filter(DisksFilter.ONLY_PLUGGED) .map(DiskImage.class::cast) .anyMatch(vmDisk -> vmDisk.getStorageIds().get(0).equals(storageDomain.getId()))) .map(vm -> vm.getName()) .collect(Collectors.toList()); QueryReturnValue ret = getBackend().runInternalQuery( QueryType.GetEntitiesWithLeaseByStorageId, new IdQueryParameters(storageDomain.getId())); if (ret.getSucceeded()) { for (VmBase vmBase : ret.<List<VmBase>> getReturnValue()) { invalidVmsForBackupStorageDomain.add(vmBase.getName()); } } if (invalidVmsForBackupStorageDomain.isEmpty()) { return ValidationResult.VALID; } log.info("All VMS in given domain is ", invalidVmsForBackupStorageDomain); return new ValidationResult( EngineMessage.ACTION_TYPE_FAILED_RUNNING_VM_OR_VM_LEASES_PRESENT_ON_STORAGE_DOMAIN); }