auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void uploadFiles() { try { List<Uri> contentUris = new ArrayList<>(); List<String> contentRemotePaths = new ArrayList<>(); int schemeFileCounter = 0; for (Parcelable sourceStream : mStreamsToUpload) { Uri sourceUri = (Uri) sourceStream; if (sourceUri != null) { String displayName = UriUtils.getDisplayNameForUri(sourceUri, this); if (displayName == null) { displayName = generateDiplayName(); } String remotePath = mUploadPath + displayName; if (ContentResolver.SCHEME_CONTENT.equals(sourceUri.getScheme())) { contentUris.add(sourceUri); contentRemotePaths.add(remotePath); } else if (ContentResolver.SCHEME_FILE.equals(sourceUri.getScheme())) { requestUpload(sourceUri.getPath(), remotePath); schemeFileCounter++; } } } if (!contentUris.isEmpty()) { copyThenUpload(contentUris.toArray(new Uri[contentUris.size()]), contentRemotePaths.toArray(new String[contentRemotePaths.size()])); } else if (schemeFileCounter == 0) { showErrorDialog( R.string.uploader_error_message_no_file_to_upload, R.string.uploader_error_title_no_file_to_upload ); } else { finish(); } } catch (SecurityException e) { Log_OC.e(TAG, "Permissions fail", e); showErrorDialog( R.string.uploader_error_message_read_permission_not_granted, R.string.uploader_error_title_file_cannot_be_uploaded ); } catch (Exception e) { Log_OC.e(TAG, "Unexpted error", e); showErrorDialog( R.string.common_error_unknown, R.string.uploader_error_title_file_cannot_be_uploaded ); } finally { SharedPreferences.Editor appPrefs = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()).edit(); appPrefs.putString("last_upload_path", mUploadPath); appPrefs.apply(); } }

Target:
public void uploadFiles() { try { List<Uri> contentUris = new ArrayList<>(); List<String> contentRemotePaths = new ArrayList<>(); int schemeFileCounter = 0; for (Parcelable sourceStream : mStreamsToUpload) { Uri sourceUri = (Uri) sourceStream; if (sourceUri != null) { String displayName = UriUtils.getDisplayNameForUri(sourceUri, this); if (displayName == null) { displayName = generateDiplayName(); } String remotePath = mUploadPath + displayName; if (ContentResolver.SCHEME_CONTENT.equals(sourceUri.getScheme())) { contentUris.add(sourceUri); contentRemotePaths.add(remotePath); } else if (ContentResolver.SCHEME_FILE.equals(sourceUri.getScheme())) { requestUpload(sourceUri.getPath(), remotePath); schemeFileCounter++; } } } if (!contentUris.isEmpty()) { copyThenUpload(contentUris.toArray(new Uri[contentUris.size()]), contentRemotePaths.toArray(new String[contentRemotePaths.size()])); } else if (schemeFileCounter == 0) { showErrorDialog( R.string.uploader_error_message_no_file_to_upload, R.string.uploader_error_title_no_file_to_upload ); } else { finish(); } } catch (SecurityException e) { Log_OC.e(TAG, "Permissions fail", e); showErrorDialog( R.string.uploader_error_message_read_permission_not_granted, R.string.uploader_error_title_file_cannot_be_uploaded ); } catch (Exception e) { Log_OC.e(TAG, "Unexpted error", e); showErrorDialog( R.string.common_error_unknown, R.string.uploader_error_title_file_cannot_be_uploaded ); } finally { PreferenceManager.setLastUploadPath(mUploadPath, this); } }
Source:
public ScenarioSimulationModel load(final Path path) { try { final String content = ioService.readAllString(Paths.convert(path)); final ScenarioSimulationModel scenarioSimulationModel = unmarshalInternal(content); final Simulation simulation = scenarioSimulationModel.getSimulation(); final Settings settings = scenarioSimulationModel.getSettings(); if (simulation != null && DMN.equals(settings.getType())) { try { dmnTypeService.initializeNameAndNamespace(settings, path, settings.getDmnFilePath()); } catch (ImpossibleToFindDMNException e) { logger.error(e.getMessage(), e); } } return scenarioSimulationModel; } catch (Exception e) { throw ExceptionUtilities.handleException(e); } }

Target:
public ScenarioSimulationModel load(final Path path) { try { final String content = ioService.readAllString(Paths.convert(path)); final ScenarioSimulationModel scenarioSimulationModel = unmarshalInternal(content); final Settings settings = scenarioSimulationModel.getSettings(); if (settings != null && DMN.equals(settings.getType())) { try { dmnTypeService.initializeNameAndNamespace(settings, path, settings.getDmnFilePath()); } catch (ImpossibleToFindDMNException e) { logger.error(e.getMessage(), e); } } return scenarioSimulationModel; } catch (Exception e) { throw ExceptionUtilities.handleException(e); } }
Source:
Point getScreenDPI () { int dpi = getDeviceZoom() * 96 / 100; return new Point (dpi, dpi); }

Target:
Point getScreenDPI () { long screen = GDK.gdk_screen_get_default(); int dpi = (int) GDK.gdk_screen_get_resolution (screen); if (dpi <= 0) dpi = 96; if (GTK.GTK_VERSION > OS.VERSION(3, 9, 0)) { int monitor_num = GDK.gdk_screen_get_monitor_at_point (screen, 0, 0); int scale = GDK.gdk_screen_get_monitor_scale_factor (screen, monitor_num); dpi = dpi * scale; } return new Point (dpi, dpi); }
Source:
private void silentDestroy() { LOGGER.debug("Found a broken ClusterTierManager - trying to clean it up"); try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { entityFactory.destroy(entityIdentifier); } catch (EntityBusyException e) { LOGGER.debug("ClusterTierManager marked busy when trying to clean it up", entityIdentifier); } catch (ConnectionClosedException | ConnectionShutdownException e) { throw e; } }

Target:
private void silentDestroy() { LOGGER.debug("Found a broken ClusterTierManager - trying to clean it up"); try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { entityFactory.destroy(entityIdentifier); } catch (EntityBusyException e) { LOGGER.debug("ClusterTierManager marked busy when trying to clean it up", entityIdentifier); } }
Source:
public Datacenter findDatacenter(String datacenterName) { for (Datacenter datacenter : datacenters) { if (datacenter.getName().equals(datacenterName)) { return datacenter; } } return null; }

Target:
public Datacenter findDatacenter(String datacenterName) { for (Datacenter datacenter : datacenters) { if (datacenter.getName().compareToIgnoreCase(datacenterName) == 0) { return datacenter; } } return null; }
Source:
private static URL makeURL(@Nonnull ZipFile file, @Nonnull ZipEntry entry, @Nonnull ZipURLStreamHandler handler) { try { assert entry.getName().indexOf(DASH) == -1; return new URL("ziploader", "", -1, file.getName() + DASH + entry.getName(), handler); } catch (MalformedURLException e) { throw new AssertionError(); } }

Target:
private static URL makeURL(@Nonnull ZipFile file, @Nonnull ZipEntry entry, @Nonnull ZipURLStreamHandler handler) { try { assert entry.getName().indexOf(BANG) == -1; return new URL("ziploader", "", -1, file.getName() + BANG + entry.getName(), handler); } catch (MalformedURLException e) { throw new AssertionError(); } }
Source:
boolean await(long delay, TimeUnit unit) throws InterruptedException; @Deprecated default void onShutdown() { throw new AssertionError("deprecated API, should not be invoked"); }

Target:
boolean await(long delay, TimeUnit unit) throws InterruptedException; @Deprecated default void onShutdown() { throw new UnsupportedOperationException("deprecated API, should not be invoked"); }
Source:
public static boolean isAccessibleFrom( @Nonnull JDefinedClassOrInterface type, @Nonnull JDefinedClassOrInterface accessor) { if (type.getEnclosingPackage() == accessor.getEnclosingPackage()) { return true; } JClassOrInterface enclosingType = type.getEnclosingType(); if (enclosingType == null) { return JModifier.isPublic(type.getModifier()); } if (!JModifier.isPublic(type.getModifier()) && !JModifier.isProtected(type.getModifier())) { return false; } assert enclosingType instanceof JDefinedClassOrInterface; return isAccessibleFrom((JDefinedClassOrInterface) enclosingType, accessor); }

Target:
public static boolean isAccessibleFrom( @Nonnull JDefinedClassOrInterface type, @Nonnull JDefinedClassOrInterface accessor) { if (type.isSameType(accessor) || type.getEnclosingPackage() == accessor.getEnclosingPackage()) { return true; } JClassOrInterface enclosingType = type.getEnclosingType(); if (enclosingType == null) { return JModifier.isPublic(type.getModifier()); } if (!JModifier.isPublic(type.getModifier()) && !JModifier.isProtected(type.getModifier())) { return false; } assert enclosingType instanceof JDefinedClassOrInterface; return isAccessibleFrom((JDefinedClassOrInterface) enclosingType, accessor); }
Source:
@Nullable public String getTokenURL() { for (FormGroup formGroup : form) { for (FormField formField : formGroup.getFields()) { String fieldId = formField.getId(); Object value = formField.getValue(); if (fieldId.equals("tokenURL") && value != null && value.toString().endsWith("/token")) { return value.toString().substring(0, value.toString().length() - "/token".length()); } } } return null; }

Target:
@Nullable public String getTokenURL() { for (FormGroup formGroup : form) { for (FormField formField : formGroup.getFields()) { String fieldId = formField.getId(); Object value = formField.getValue(); if (FormField.TOKEN_URL.equals(fieldId) && value != null && value.toString().endsWith("/token")) { return value.toString().substring(0, value.toString().length() - "/token".length()); } } } return null; }
Source:
public void mergeStatisticsMinMax(Statistics stats) { BinaryStatistics binaryStats = (BinaryStatistics)stats; if (!this.hasNonNullValue()) { initializeStats(binaryStats.genericGetMinSigned(), binaryStats.genericGetMaxSigned()); initializeStats(binaryStats.genericGetMinUnsigned(), binaryStats.genericGetMaxUnsigned()); } else { updateStats(binaryStats.genericGetMinSigned(), binaryStats.genericGetMaxSigned()); updateStats(binaryStats.genericGetMinUnsigned(), binaryStats.genericGetMaxUnsigned()); } }

Target:
public void mergeStatisticsMinMax(Statistics stats) { BinaryStatistics binaryStats = (BinaryStatistics)stats; if (!this.hasNonNullValue()) { initializeStatsSigned(binaryStats.genericGetMinSigned(), binaryStats.genericGetMaxSigned()); initializeStatsUnsigned(binaryStats.genericGetMinUnsigned(), binaryStats.genericGetMaxUnsigned()); } else { updateStatsSigned(binaryStats.genericGetMinSigned(), binaryStats.genericGetMaxSigned()); updateStatsUnsigned(binaryStats.genericGetMinUnsigned(), binaryStats.genericGetMaxUnsigned()); } }
Source:
public ClientPolicy(int retryTimeOut, int retryNumber, int incomingHeartbeat, int outgoingHeartbeat, List<Class<? extends Exception>> retryableExceptions) { this(retryTimeOut, retryNumber, incomingHeartbeat, outgoingHeartbeat, retryableExceptions, null); }

Target:
public ClientPolicy(int retryTimeOut, int retryNumber, int incomingHeartbeat, int outgoingHeartbeat, List<Class<? extends Exception>> retryableExceptions) { this.retryNumber = retryNumber; this.retryTimeOut = retryTimeOut; setIncomingHeartbeat(incomingHeartbeat); setOutgoingHeartbeat(outgoingHeartbeat); this.exceptions = Collections.unmodifiableList(retryableExceptions); }
Source:
public Void doInBackground(String... urls) { boolean sendMore = true; try { while (sendMore) { sendMore = sendData(); } } finally { wakeLock.release(); lockCounter--; Log.e(TAG,"MongosendTask wakelock released " + lockCounter); } return null; }

Target:
public Void doInBackground(String... urls) { try { sendData(); } finally { wakeLock.release(); lockCounter--; Log.e(TAG,"MongosendTask wakelock released " + lockCounter); } return null; }
Source:
public void postCollectionSubmittersGroupCreateSubmittersGroupForbidden() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/submittersGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isForbidden()); }

Target:
public void postCollectionSubmittersGroupCreateSubmittersGroupForbidden() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/submittersGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isForbidden()); token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/submittersGroup")) .andExpect(status().isNoContent()); }
Source:
public <T> T getService(Class<T> clazz) { if (services.containsKey(clazz)) { return (T) services.get(clazz); } try { return clazz.newInstance(); } catch (Exception e) return null; }

Target:
public <T> T getService(Class<T> clazz) { if (services.containsKey(clazz)) { return (T) services.get(clazz); } try { return clazz.newInstance(); } catch (Exception e) { log.warn("Didn't manage to create an instance of {}", clazz, e); } return null; }
Source:
CompletableFuture<ReadBatch> readRecords(TransferBatchRequest transferBatchRequest) { return CompletableFuture.supplyAsync(() -> { Optional<ReadBatchException> latestReadException = Optional.empty(); Optional<ReadBatch> latestReadBatch = Optional.empty(); for (int i = 0; i < maxReadRetries; i++) { try { Map<Long, ILogData> records = addressSpaceView.simpleProtocolRead( ImmutableList.copyOf(transferBatchRequest.getAddresses()), readOptions); ReadBatch batch = checkReadRecords( ImmutableList.copyOf(transferBatchRequest.getAddresses()), records, Optional.empty()); latestReadBatch = Optional.of(batch); if (batch.getStatus() == ReadBatch.ReadStatus.FAILED) { throw new IllegalStateException("Some addresses failed to transfer: " + batch.getFailedAddresses()); } else { latestReadException = Optional.empty(); break; } } catch (WrongEpochException e) { log.warn("readRecords: encountered a wrong epoch exception on try {}: ", i, e); latestReadException = Optional.of(new ReadBatchException(e)); break; } catch (RuntimeException e) { log.warn("readRecords: encountered an exception on try {}: ", i, e); latestReadException = Optional.of(new ReadBatchException(e)); Sleep.sleepUninterruptibly(readSleepDuration); } } if (latestReadException.isPresent()) { throw latestReadException.get(); } else { return latestReadBatch.get(); } }); }

Target:
CompletableFuture<ReadBatch> readRecords(TransferBatchRequest transferBatchRequest) { return CompletableFuture.supplyAsync(() -> { for (int i = 0; i < maxReadRetries; i++) { try { Map<Long, ILogData> records = addressSpaceView.simpleProtocolRead( transferBatchRequest.getAddresses(), readOptions); ReadBatch batch = checkReadRecords( transferBatchRequest.getAddresses(), records, Optional.empty()); if (batch.getStatus() == ReadBatch.ReadStatus.FAILED) { throw new IllegalStateException("Some addresses failed to transfer: " + batch.getFailedAddresses()); } return batch; } catch (WrongEpochException e) { log.warn("readRecords: encountered a wrong epoch exception on try {}: {}.", i, e); throw e; } catch (RuntimeException e) { log.warn("readRecords: encountered an exception on try {}: {}.", i, e); Sleep.sleepUninterruptibly(readSleepDuration); } } throw new ReadBatchException("readRecords: read retries were exhausted"); }); }
Source:
private static EtdSettlementType parseEtdSettlementType(String str) { String upper = str.toUpperCase(Locale.ENGLISH); Map<String, EtdSettlementType> valuesByCode = Stream.of(EtdSettlementType.values()).collect(toImmutableMap(EtdSettlementType::getCode)); EtdSettlementType fromCode = valuesByCode.get(upper); return fromCode != null ? fromCode : EtdSettlementType.of(str); }

Target:
private static EtdSettlementType parseEtdSettlementType(String str) { String upper = str.toUpperCase(Locale.ENGLISH); EtdSettlementType fromCode = SETTLEMENT_BY_CODE.get(upper); return fromCode != null ? fromCode : EtdSettlementType.of(str); }
Source:
public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes feedbackSession = logic.getFeedbackSession(feedbackSessionName, courseId); if (feedbackSession == null) { throw new EntityNotFoundException(new EntityDoesNotExistException("Feedback session not found")); } verifySessionOpenExceptForModeration(feedbackSession); verifyNotPreview(); Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case STUDENT_SUBMISSION: StudentAttributes studentAttributes = getStudentOfCourseFromRequest(feedbackSession.getCourseId()); checkAccessControlForStudentFeedbackSubmission(studentAttributes, feedbackSession); break; case INSTRUCTOR_SUBMISSION: InstructorAttributes instructorAttributes = getInstructorOfCourseFromRequest(feedbackSession.getCourseId()); checkAccessControlForInstructorFeedbackSubmission(instructorAttributes, feedbackSession); break; default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }

Target:
public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String feedbackSessionName = getNonNullRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); FeedbackSessionAttributes feedbackSession = getNonNullFeedbackSession(feedbackSessionName, courseId); verifySessionOpenExceptForModeration(feedbackSession); verifyNotPreview(); Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); switch (intent) { case STUDENT_SUBMISSION: StudentAttributes studentAttributes = getStudentOfCourseFromRequest(feedbackSession.getCourseId()); checkAccessControlForStudentFeedbackSubmission(studentAttributes, feedbackSession); break; case INSTRUCTOR_SUBMISSION: InstructorAttributes instructorAttributes = getInstructorOfCourseFromRequest(feedbackSession.getCourseId()); checkAccessControlForInstructorFeedbackSubmission(instructorAttributes, feedbackSession); break; default: throw new InvalidHttpParameterException("Unknown intent " + intent); } }
Source:
private boolean isSuspiciousClassInstantiation(ExpressionTree callee) { if (callee.is(Tree.Kind.NAMESPACE_NAME)) { NamespaceNameTree classNameTree = (NamespaceNameTree) callee; QualifiedName className = getFullyQualifiedName(classNameTree); return SUSPICIOUS_CLASS_INSTANTIATIONS.stream().anyMatch(className::equals); } return false; }

Target:
private boolean isSuspiciousClassInstantiation(ExpressionTree callee) { if (callee.is(Tree.Kind.NAMESPACE_NAME)) { QualifiedName className = getFullyQualifiedName((NamespaceNameTree) callee); return SUSPICIOUS_CLASS_INSTANTIATIONS.stream().anyMatch(className::equals); } return false; }
Source:
public synchronized BigtableClient getDataClient() throws IOException { if (this.client == null) { Channel generalChannel = createChannel(options.getDataHost(), options.getChannelCount()); Channel scanChannel = createChannel(options.getDataHost(), 1); this.client = new BigtableGrpcClient(generalChannel, scanChannel, batchPool, options.getRetryOptions()); } return client; }

Target:
public synchronized BigtableClient getDataClient() throws IOException { if (this.client == null) { Channel writeChannel = createChannel(options.getDataHost(), options.getChannelCount()); Channel readChannel = createChannel(options.getDataHost(), 1); RetryOptions retryOptions = options.getRetryOptions(); this.client = new BigtableGrpcClient(readChannel, writeChannel, batchPool, retryOptions); } return client; }
Source:
public int place(World world, BlockPos pos, @Nonnull FluidStack fluidStack, boolean doPlace) { if (fluidStack.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doPlace) { if (!world.isRemote) { IBlockState destBlockState = world.getBlockState(pos); Material destMaterial = destBlockState.getMaterial(); boolean isDestNonSolid = !destMaterial.isSolid(); boolean isDestReplaceable = destBlockState.getBlock().isReplaceable(world, pos); if ((isDestNonSolid || isDestReplaceable) && !destMaterial.isLiquid()) { world.destroyBlock(pos, true); } } world.setBlockState(pos, this.getDefaultState(), 11); } return Fluid.BUCKET_VOLUME; }

Target:
public int place(World world, BlockPos pos, @Nonnull FluidStack fluidStack, boolean doPlace) { if (fluidStack.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doPlace) { FluidUtil.destroyBlockOnFluidPlacement(world, pos); world.setBlockState(pos, this.getDefaultState(), 11); } return Fluid.BUCKET_VOLUME; }
Source:
public ItemFile getItemFile(final ZipEntry zipEntry, final ZipFile zipFile) throws IllegalArgumentException { if (null == zipEntry) { throw new IllegalArgumentException("A null ZIP entry was passed."); } if (null == zipFile) { throw new IllegalArgumentException("A null ZIP file was passed."); } return new ItemFile() { private ZipEntry itemEntry = zipEntry; private Image image = null; public Object getItem() throws Exception { if (null == image) { InputStream in = new BufferedInputStream(zipFile .getInputStream(itemEntry), (int) itemEntry .getSize()); byte[] buffer = new byte[(int) itemEntry.getSize()]; in.read(buffer); int index = (int) itemEntry.getSize() - 10; while (itemEntry.getSize() > index) { if (0 != buffer[index]) { break; } index++; } if (itemEntry.getSize() <= index) { throw new IOException( "Error reading " + itemEntry.getName() + "\nYou may want to unzip " + zipFile.getName()); } image = Toolkit.getDefaultToolkit().createImage(buffer); } return ImageUtil.getScaledImage(image, 84, 72); } }; }

Target:
public ItemFile getItemFile(final ZipEntry zipEntry, final ZipFile zipFile) throws IllegalArgumentException { if (null == zipEntry) { throw new IllegalArgumentException("A null ZIP entry was passed."); } if (null == zipFile) { throw new IllegalArgumentException("A null ZIP file was passed."); } return new ItemFile() { private ZipEntry itemEntry = zipEntry; private Image image = null; public Object getItem() throws Exception { if (null == image) { try (InputStream in = new BufferedInputStream( zipFile.getInputStream(itemEntry), (int) itemEntry.getSize())) { byte[] buffer = new byte[(int) itemEntry.getSize()]; in.read(buffer); int index = (int) itemEntry.getSize() - 10; while (itemEntry.getSize() > index) { if (0 != buffer[index]) { break; } index++; } if (itemEntry.getSize() <= index) { throw new IOException( "Error reading " + itemEntry.getName() + "\nYou may want to unzip " + zipFile.getName()); } image = Toolkit.getDefaultToolkit().createImage(buffer); } } return ImageUtil.getScaledImage(image, 84, 72); } }; }
Source:
private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); for (ProfileEntry profileEntry : source != null ? new ArrayList<ProfileEntry>((ArrayList<ProfileEntry>) source) : new ArrayList<ProfileEntry>()) { results.add(profileEntry.getProfile()); } return results; } }; }

Target:
private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); for (ProfileEntry profileEntry : source != null ? (Collection<ProfileEntry>) source : new ArrayList<ProfileEntry>()) { results.add(profileEntry.getProfile()); } return results; } }; }
Source:
public boolean isEnabled() { return getRepositories().length == 1; }

Target:
public boolean isEnabled() { IProject[] projects = getProjectsForSelectedResources(); return getRepositoriesFor(projects).length == 1; }
Source:
public APIResult submitAndScheduleExtensionJob(String extensionName, String jobName, String configPath, String doAsUser) { InputStream configStream = FalconClient.getServletInputStream(configPath); String packagePath = ExtensionStore.get().getMetaStore().getDetail(extensionName).getLocation(); try { List<Entity> entities = ExtensionHandler.loadAndPrepare(extensionName, jobName, configStream, packagePath); return localExtensionManager.submitAndSchedulableExtensionJob(extensionName, jobName, configStream, entities); } catch (FalconException | IOException e) { throw new FalconCLIException("Failed in submitting extension job " + jobName); } }

Target:
public APIResult submitAndScheduleExtensionJob(String extensionName, String jobName, String configPath, String doAsUser) { InputStream configStream = getServletInputStream(configPath); try { List<Entity> entities = getEntities(extensionName, jobName, configStream); return localExtensionManager.submitAndSchedulableExtensionJob(extensionName, jobName, configStream, entities); } catch (FalconException | IOException e) { throw new FalconCLIException("Failed in submitting extension job " + jobName); } }
Source:
public static void setup() { cache = mock(AttributeTypeCache.class); type = mock(AttributeType.class); types.add(CoreAttributeTypes.Active); types.add(CoreAttributeTypes.FavoriteBranch); }

Target:
public void setup() { MockitoAnnotations.initMocks(this); types.add(CoreAttributeTypes.Active); types.add(CoreAttributeTypes.FavoriteBranch); }
Source:
public static List<Property> getNestedPath(org.eclipse.uml2.uml.Class clazz, View view) { List<Property> propertyPath = new ArrayList<>(); View currentView = ViewUtil.getContainerView(view); while (currentView != null && !clazz.equals(currentView.getElement())) { EObject property = currentView.getElement(); if (property instanceof Property) { propertyPath.add((Property) property); } currentView = ViewUtil.getContainerView(currentView); } Collections.reverse(propertyPath); return propertyPath; }

Target:
public static List<Property> getNestedPath(org.eclipse.uml2.uml.Class clazz, View view) { List<Property> propertyPath = new ArrayList<>(); View currentView = ViewUtil.getContainerView(view); boolean stop = false; while (!stop && currentView != null) { EObject property = currentView.getElement(); if (property instanceof Property) { if (((Property) property).getType() == clazz) { stop = true; } else { propertyPath.add((Property) property); } } else { if (clazz.equals(currentView.getElement())) { stop = true; } } currentView = ViewUtil.getContainerView(currentView); } Collections.reverse(propertyPath); return propertyPath; }
Source:
@Override protected void setUp() throws Exception { super.setUp(); File file = File.createTempFile("integrity", "dat"); file.deleteOnExit(); expBuf = new ByteBufferExpander(1024, ByteOrder.BIG_ENDIAN); FileIOFactory factory = new RandomAccessFileIOFactory(); fileInput = new FileInput( factory.create(file), expBuf ); ByteBuffer buf = ByteBuffer.allocate(1024); ThreadLocalRandom curr = ThreadLocalRandom.current(); for (int i = 0; i < 1024; i+=16) { buf.putInt(curr.nextInt()); buf.putInt(curr.nextInt()); buf.putInt(curr.nextInt()); buf.position(i); if (oldCrcAlgo) buf.putInt(PureJavaCrc32.calcCrc32(buf, 12)); else buf.putInt(U.calcCrc(buf, 12)); } buf.rewind(); fileInput.io().writeFully(buf); fileInput.io().force(); }

Target:
@Override protected void setUp() throws Exception { super.setUp(); File file = File.createTempFile("integrity", "dat"); file.deleteOnExit(); expBuf = new ByteBufferExpander(1024, ByteOrder.BIG_ENDIAN); FileIOFactory factory = new RandomAccessFileIOFactory(); fileInput = new SimpleFileInput( factory.create(file), expBuf ); ByteBuffer buf = ByteBuffer.allocate(1024); ThreadLocalRandom curr = ThreadLocalRandom.current(); for (int i = 0; i < 1024; i+=16) { buf.putInt(curr.nextInt()); buf.putInt(curr.nextInt()); buf.putInt(curr.nextInt()); buf.position(i); buf.putInt(FastCrc.calcCrc(buf, 12)); } buf.rewind(); fileInput.io().writeFully(buf); fileInput.io().force(); }
Source:
void increment(int imp) { imp = imp < 0 ? 0 : imp > NUM_IMPORTANCES -1 ? NUM_IMPORTANCES - 1 : imp; mCount[imp] ++; }

Target:
void increment(int imp) { imp = Math.max(0, Math.min(imp, mCount.length - 1)); mCount[imp]++; }
Source:
public void runFlakyTest() { SystemTestEnvironment testEnvironment = systemTestEnvironmentManager.createTestEnvironment("flaky-test"); RandoopOptions options = createRandoopOptions(testEnvironment); options.addTestClass("flaky.FlakyClass"); options.setOption("generated_limit", "1000"); options.setOption("output_limit", "1000"); options.setOption("flaky-test-behavior", "OUTPUT"); CoverageChecker coverageChecker = new CoverageChecker( options, "flaky.FlakyClass.getTwo() include", "flaky.FlakyClass.getThree() include", "flaky.FlakyClass.flakyDefaultHashCode() ignore", "flaky.FlakyClass.multiply(int, int) include"); List<String> expectedFlakyMethodsInOrder = new ArrayList<>(); expectedFlakyMethodsInOrder.add("flaky.FlakyClass.flakyDefaultHashCode(flaky.FlakyClass)"); generateAndTest( testEnvironment, options, ExpectedTests.DONT_CARE, ExpectedTests.DONT_CARE, coverageChecker, expectedFlakyMethodsInOrder); }

Target:
public void runFlakyTest() { SystemTestEnvironment testEnvironment = systemTestEnvironmentManager.createTestEnvironment("flaky-test"); RandoopOptions options = createRandoopOptions(testEnvironment); options.addTestClass("flaky.FlakyClass"); options.setOption("generated_limit", "1000"); options.setOption("output_limit", "1000"); options.setOption("flaky-test-behavior", "OUTPUT"); CoverageChecker coverageChecker = new CoverageChecker( options, "flaky.FlakyClass.getTwo() include", "flaky.FlakyClass.getThree() include", "flaky.FlakyClass.flakyDefaultHashCode() ignore", "flaky.FlakyClass.multiply(int, int) include"); List<String> expectedFlakyMethodsInOrder = new ArrayList<>(); expectedFlakyMethodsInOrder.add("flaky.FlakyClass.flakyDefaultHashCode()"); generateAndTest( testEnvironment, options, ExpectedTests.DONT_CARE, ExpectedTests.DONT_CARE, coverageChecker, expectedFlakyMethodsInOrder); }
Source:
private void setupGridView() { final RecyclerView grid = (RecyclerView)findViewById(R.id.wifi_direct_gridview_buttons); grid.setHasFixedSize(true); StaggeredGridLayoutManager gridView = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); grid.setLayoutManager(gridView); grid.setItemAnimator(null); grid.setAdapter(adapter); grid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { grid.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { grid.getViewTreeObserver().removeOnGlobalLayoutListener(this); } grid.requestLayout(); adapter.notifyDataSetChanged(); configUI(); } }); }

Target:
private void setupGridView() { final RecyclerView grid = (RecyclerView)findViewById(R.id.wifi_direct_gridview_buttons); grid.setHasFixedSize(true); StaggeredGridLayoutManager gridView = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); grid.setLayoutManager(gridView); grid.setItemAnimator(null); grid.setAdapter(adapter); grid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { grid.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { grid.getViewTreeObserver().removeOnGlobalLayoutListener(this); } grid.requestLayout(); adapter.notifyDataSetChanged(); } }); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((backendHintSettings == null) ? 0 : backendHintSettings.hashCode()); result = prime * result + ((queryBackendFactory == null) ? 0 : queryBackendFactory.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Objects.hashCode(backendHintSettings); result = prime * result + Objects.hashCode(queryBackendFactory); return result; }
Source:
Optional<ItemDefinition> findItemDefinitionParent(final DataType dataType) { final Optional<ItemDefinition> itemDefinitionParent = Optional.ofNullable(itemDefinitionStore.get(dataType.getParentUUID())); if (itemDefinitionParent.isPresent()) { final ItemDefinition parent = itemDefinitionParent.get(); if (parent.getTypeRef() == null) { return Optional.of(parent); } else { for (final ItemDefinition itemDefinition : itemDefinitions()) { if (itemDefinition.getName().getValue().equals(parent.getTypeRef().getLocalPart())) { return Optional.of(itemDefinition); } } } } return Optional.empty(); }

Target:
Optional<ItemDefinition> findItemDefinitionParent(final DataType dataType) { final Optional<ItemDefinition> itemDefinitionParent = Optional.ofNullable(itemDefinitionStore.get(dataType.getParentUUID())); if (itemDefinitionParent.isPresent()) { final ItemDefinition parent = itemDefinitionParent.get(); if (parent.getTypeRef() == null) { return Optional.of(parent); } else { for (final ItemDefinition itemDefinition : itemDefinitions()) { if (Objects.equals(itemDefinition.getName().getValue(), parent.getTypeRef().getLocalPart())) { return Optional.of(itemDefinition); } } } } return Optional.empty(); }
Source:
public String toString() { return String.format("AmqpBrokerConfig [host=%s, port=%d, username=%s, password=%s, virtualHost=%s, groupId=%s, durable=%s, consumerThreadPoolSize=%s]", host, port, username, password, virtualHost, groupId, durable, consumerThreadPoolSize); }

Target:
public String toString() { return String.format("AmqpBrokerConfig [host=%s, port=%d, username=%s, password=xxx, virtualHost=%s, groupId=%s, durable=%s, consumerThreadPoolSize=%s]", host, port, username, virtualHost, groupId, durable, consumerThreadPoolSize); }
Source:
public static void verifyAggregations( List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { Preconditions.checkNotNull(aggFactories, "aggregations cannot be null"); Preconditions.checkArgument(aggFactories.size() > 0, "Must have at least one AggregatorFactory"); if (postAggs != null && !postAggs.isEmpty()) { Set<String> combinedAggNames = Sets.newHashSet( Lists.transform( aggFactories, new Function<AggregatorFactory, String>() { @Override public String apply(@Nullable AggregatorFactory input) { return input.getName(); } } ) ); for (PostAggregator postAgg : postAggs) { Set<String> dependencies = postAgg.getDependentFields(); Set<String> missing = Sets.difference(dependencies, combinedAggNames); Preconditions.checkArgument( missing.isEmpty(), String.format("Missing fields [%s] for postAggregator [%s]", Joiner.on(",").join(missing), postAgg.getName()) ); combinedAggNames.add(postAgg.getName()); } } }

Target:
public static void verifyAggregations( List<AggregatorFactory> aggFactories, List<PostAggregator> postAggs ) { Preconditions.checkNotNull(aggFactories, "aggregations cannot be null"); Preconditions.checkArgument(aggFactories.size() > 0, "Must have at least one AggregatorFactory"); if (postAggs != null && !postAggs.isEmpty()) { Set<String> combinedAggNames = Sets.newHashSet( Lists.transform( aggFactories, new Function<AggregatorFactory, String>() { @Override public String apply(@Nullable AggregatorFactory input) { return input.getName(); } } ) ); for (PostAggregator postAgg : postAggs) { Set<String> dependencies = postAgg.getDependentFields(); Set<String> missing = Sets.difference(dependencies, combinedAggNames); Preconditions.checkArgument( missing.isEmpty(), "Missing fields [%s] for postAggregator [%s]", missing, postAgg.getName() ); combinedAggNames.add(postAgg.getName()); } } }
Source:
private void loadMedia() { MediaFactory mediaFactory = new MediaFactory(); GetMediasUseCase getMediasUseCase = mediaFactory.getGetMediasUseCase(); getMediasUseCase.execute(new GetMediasUseCase.Callback() { @Override public void onSuccess(List<Media> medias) { mView.showMediaItems(medias); } }); }

Target:
private void loadMedia() { mGetMediasUseCase.execute(new GetMediasUseCase.Callback() { @Override public void onSuccess(List<Media> medias) { mView.showMediaItems(medias); } }); }
Source:
private void initializeSSLContext(SSLChannelMode preferredChannelMode) throws NoSuchAlgorithmException, KeyManagementException { switch (preferredChannelMode) { case Default: try { if (!openSSLProviderRegistered) { OpenSSLProvider.register(); openSSLProviderRegistered = true; } java.util.logging.Logger logger = java.util.logging.Logger.getLogger( SSL.class.getName()); logger.setLevel(Level.WARNING); ctx = SSLContext.getInstance("openssl.TLS"); ctx.init(null, null, null); logger.setLevel(Level.INFO); channelMode = SSLChannelMode.OpenSSL; } catch (LinkageError | NoSuchAlgorithmException | RuntimeException e) { LOG.debug("Failed to load OpenSSL. Falling back to the JSSE default.", e); ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; } break; case OpenSSL: if (!openSSLProviderRegistered) { OpenSSLProvider.register(); openSSLProviderRegistered = true; } java.util.logging.Logger logger = java.util.logging.Logger.getLogger( SSL.class.getName()); logger.setLevel(Level.WARNING); ctx = SSLContext.getInstance("openssl.TLS"); ctx.init(null, null, null); logger.setLevel(Level.INFO); channelMode = SSLChannelMode.OpenSSL; break; case Default_JSSE: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; break; case Default_JSSE_with_GCM: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE_with_GCM; break; default: throw new NoSuchAlgorithmException("Unknown channel mode: " + preferredChannelMode); } }

Target:
private void initializeSSLContext(SSLChannelMode preferredChannelMode) throws NoSuchAlgorithmException, KeyManagementException, IOException { LOG.debug("Initializing SSL Context to channel mode {}", preferredChannelMode); switch (preferredChannelMode) { case Default: try { bindToOpenSSLProvider(); channelMode = SSLChannelMode.OpenSSL; } catch (LinkageError | NoSuchAlgorithmException | RuntimeException e) { LOG.debug("Failed to load OpenSSL. Falling back to the JSSE default.", e); ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; } break; case OpenSSL: bindToOpenSSLProvider(); channelMode = SSLChannelMode.OpenSSL; break; case Default_JSSE: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE; break; case Default_JSSE_with_GCM: ctx = SSLContext.getDefault(); channelMode = SSLChannelMode.Default_JSSE_with_GCM; break; default: throw new IOException("Unknown channel mode: " + preferredChannelMode); } }
Source:
public CompletableFuture<Void> deleteAsync(K key) { writeMetrics.numDeletes.inc(); long startNs = System.nanoTime(); Preconditions.checkNotNull(rwTable, "Cannot delete from a read-only table: " + rdTable); return rwTable.deleteAsync(key).handle((result, e) -> { if (e != null) { throw new SamzaException("Failed to delete the record for " + key, e); } else if (!isWriteAround) { cache.delete(key); writeMetrics.deleteNs.update(System.nanoTime() - startNs); } return result; }); }

Target:
public CompletableFuture<Void> deleteAsync(K key) { writeMetrics.numDeletes.inc(); long startNs = System.nanoTime(); Preconditions.checkNotNull(rwTable, "Cannot delete from a read-only table: " + rdTable); return rwTable.deleteAsync(key).handle((result, e) -> { if (e != null) { throw new SamzaException("Failed to delete the record for " + key, e); } else if (!isWriteAround) { cache.delete(key); } writeMetrics.deleteNs.update(System.nanoTime() - startNs); return result; }); }
Source:
String basicToString(int tab) { StringBuilder sb = new StringBuilder("\n"); for (int i = tab; --i >= 0;) { sb.append("\t"); } sb.append("--- Method Scope ---"); sb.append("\t"); sb.append("locals:"); for (int i = 0; i < localIndex; i++) { sb.append("\t"); sb.append(locals[i].toString()); } sb.append("startIndex = "); sb.append(startIndex); sb.append("isConstructorCall = "); sb.append(isConstructorCall); sb.append("initializedField = "); sb.append(initializedField); sb.append("lastVisibleFieldID = "); sb.append(lastVisibleFieldID); sb.append("referenceContext = "); sb.append(referenceContext); return sb.toString(); }

Target:
String basicToString(int tab) { StringBuilder sb = new StringBuilder("\n"); for (int i = tab; --i >= 0;) { sb.append("\t"); } sb.append("--- Method Scope ---"); sb.append("\t"); sb.append("locals:"); for (int i = 0; i < localIndex; i++) { sb.append("\t"); sb.append(locals[i]); } sb.append("startIndex = "); sb.append(startIndex); sb.append("isConstructorCall = "); sb.append(isConstructorCall); sb.append("initializedField = "); sb.append(initializedField); sb.append("lastVisibleFieldID = "); sb.append(lastVisibleFieldID); sb.append("referenceContext = "); sb.append(referenceContext); return sb.toString(); }
Source:
public void testChildrenOffsets() { int numBuildRects = 10; int degree = 8; Random random = new Random(122); int firstParentIndex = 2 * degree * ENVELOPE_SIZE; int secondParentIndex = firstParentIndex + ENVELOPE_SIZE; int grandparentIndex = 3 * degree * ENVELOPE_SIZE; List<Rectangle> buildRects = makeRectangles(random, numBuildRects); Flatbush<Rectangle> rtree = new Flatbush<>(buildRects.toArray(new Rectangle[] {}), degree); assertEquals(rtree.getHeight(), 3); assertEquals(rtree.getChildrenOffset(firstParentIndex, 1), 0); assertEquals(rtree.getChildrenOffset(secondParentIndex, 1), degree * ENVELOPE_SIZE); assertEquals(rtree.getChildrenOffset(grandparentIndex, 2), 2 * degree * ENVELOPE_SIZE); }

Target:
public void testChildrenOffsets() { int numRectangles = 10; int degree = 8; Random random = new Random(122); int firstParentIndex = 2 * degree * ENVELOPE_SIZE; int secondParentIndex = firstParentIndex + ENVELOPE_SIZE; int grandparentIndex = 3 * degree * ENVELOPE_SIZE; List<Rectangle> rectangles = makeRectangles(random, numRectangles); Flatbush<Rectangle> rtree = new Flatbush<>(rectangles.toArray(new Rectangle[] {}), degree); assertEquals(rtree.getHeight(), 3); assertEquals(rtree.getChildrenOffset(firstParentIndex, 1), 0); assertEquals(rtree.getChildrenOffset(secondParentIndex, 1), degree * ENVELOPE_SIZE); assertEquals(rtree.getChildrenOffset(grandparentIndex, 2), 2 * degree * ENVELOPE_SIZE); }
Source:
private void setStormHostConf() { try { String host_addr = InetAddress.getLocalHost().getHostAddress(); LOG.info("Storm master host:"+host_addr); _storm_conf.put(Config.NIMBUS_HOST, host_addr); } catch (UnknownHostException ex) { } }

Target:
private void setStormHostConf() { try { String host_addr = InetAddress.getLocalHost().getHostAddress(); LOG.info("Storm master host:"+host_addr); _storm_conf.put(Config.NIMBUS_HOST, host_addr); } catch (UnknownHostException ex) { LOG.warn("Failed to get IP address of local host"); } }
Source:
private void writeToFile(File file, String body) throws IOException { FileOutputStream fos = new FileOutputStream(file); BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(fos, UTF_8)); bw.write(body); } finally { if (bw != null) { bw.close(); } fos.close(); } }

Target:
private static void writeToFile(File file, String body) throws IOException { FileOutputStream fos = new FileOutputStream(file); BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(fos, UTF_8)); bw.write(body); } finally { if (bw != null) { bw.close(); } fos.close(); } }
Source:
public void generateCpuQuota(long elapsedSeconds) { synchronized (getRoot()) { if (elapsedSeconds > 0) { internalGenerateCpuQuota(elapsedSeconds); } } }

Target:
public void generateCpuQuota(long elapsedSeconds) { synchronized (super.root) { if (elapsedSeconds > 0) { internalGenerateCpuQuota(elapsedSeconds); } } }
Source:
public Credentials getHttpCredentials() { return new UsernamePasswordCredentials(gerritHttpUserName, Secret.toString(gerritHttpPassword)); }

Target:
public Credentials getHttpCredentials() { return new UsernamePasswordCredentials(gerritHttpUserName, getGerritHttpPassword()); }
Source:
public JnKeysScalarEvaluator(IHyracksTaskContext ctx, IScalarEvaluator[] args) { super(args); this.ctx = ctx; sp1 = (SequencePointable) SequencePointable.FACTORY.createPointable(); sp2 = (SequencePointable) SequencePointable.FACTORY.createPointable(); pointables = new ArrayList<>(); sb = new SequenceBuilder(); abvs = new ArrayBackedValueStorage(); }

Target:
public JnKeysScalarEvaluator(IHyracksTaskContext ctx, IScalarEvaluator[] args) { super(args); this.ctx = ctx; sp1 = (SequencePointable) SequencePointable.FACTORY.createPointable(); sp2 = (SequencePointable) SequencePointable.FACTORY.createPointable(); sb = new SequenceBuilder(); abvs = new ArrayBackedValueStorage(); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ViewerCell<E> other = (ViewerCell<E>) obj; if (columnIndex != other.columnIndex) return false; if (row == null) { if (other.row != null) return false; } else if (!row.equals(other.row)) return false; return true; }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("unchecked") final ViewerCell<E> other = (ViewerCell<E>) obj; if (columnIndex != other.columnIndex) return false; if (row == null) { if (other.row != null) return false; } else if (!row.equals(other.row)) return false; return true; }
Source:
protected void executeCommand() { VM vm = getVm(); if (vm.getVdsGroupId().equals(getParameters().getClusterId())) { setSucceeded(true); return; } List<Network> networks = getNetworkDAO().getAllForCluster(getParameters().getClusterId()); List<VmNic> interfaces = getVmNicDao().getAllForVm(getParameters().getVmId()); for (final VmNic iface : interfaces) { if (iface.getVnicProfileId() != null) { final Network network = NetworkHelper.getNetworkByVnicProfileId(iface.getVnicProfileId()); Network net = LinqUtils.firstOrNull(networks, new Predicate<Network>() { @Override public boolean eval(Network n) { return ObjectUtils.equals(n.getId(), network.getId()); } }); if (net == null) { iface.setVnicProfileId(null); getVmNicDao().update(iface); } } } if (vm.getDedicatedVmForVds() != null) { vm.setDedicatedVmForVds(null); dedicatedHostWasCleared = true; } vm.setCpuProfileId(null); vm.setVdsGroupId(getParameters().getClusterId()); DbFacade.getInstance().getVmStaticDao().update(vm.getStaticData()); List<AffinityGroup> allAffinityGroupsByVmId = DbFacade.getInstance().getAffinityGroupDao().getAllAffinityGroupsByVmId(vm.getId()); if (!allAffinityGroupsByVmId.isEmpty()) { StringBuilder sb = new StringBuilder(); for (AffinityGroup affinityGroup : allAffinityGroupsByVmId) { sb.append(affinityGroup.getName() + " "); } log.info("Due to cluster change, removing VM from associated affinity group(s): {}", sb.toString()); DbFacade.getInstance().getAffinityGroupDao().removeVmFromAffinityGroups(vm.getId()); } setSucceeded(true); }

Target:
protected void executeCommand() { VM vm = getVm(); if (vm.getVdsGroupId().equals(getParameters().getClusterId())) { setSucceeded(true); return; } List<Network> networks = getNetworkDAO().getAllForCluster(getParameters().getClusterId()); List<VmNic> interfaces = getVmNicDao().getAllForVm(getParameters().getVmId()); for (final VmNic iface : interfaces) { if (iface.getVnicProfileId() != null) { final Network network = NetworkHelper.getNetworkByVnicProfileId(iface.getVnicProfileId()); Network net = LinqUtils.firstOrNull(networks, new Predicate<Network>() { @Override public boolean eval(Network n) { return ObjectUtils.equals(n.getId(), network.getId()); } }); if (net == null) { iface.setVnicProfileId(null); getVmNicDao().update(iface); } } } if (vm.getDedicatedVmForVds() != null) { vm.setDedicatedVmForVds(null); dedicatedHostWasCleared = true; } vm.setCpuProfileId(null); vm.setVdsGroupId(getParameters().getClusterId()); DbFacade.getInstance().getVmStaticDao().update(vm.getStaticData()); List<AffinityGroup> allAffinityGroupsByVmId = DbFacade.getInstance().getAffinityGroupDao().getAllAffinityGroupsByVmId(vm.getId()); if (!allAffinityGroupsByVmId.isEmpty()) { StringBuilder sb = new StringBuilder(); for (AffinityGroup affinityGroup : allAffinityGroupsByVmId) { sb.append(affinityGroup.getName() + " "); } log.info("Due to cluster change, removing VM from associated affinity group(s): {}", sb); DbFacade.getInstance().getAffinityGroupDao().removeVmFromAffinityGroups(vm.getId()); } setSucceeded(true); }