auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Set<Long> getUserItems(long userId) { if (Context.getPermissionsManager() != null) { Set<Long> result = new HashSet<>(); for (long deviceId : Context.getPermissionsManager().getDevicePermissions(userId)) { Device device = Context.getIdentityManager().getById(deviceId); if (device != null && !device.getDisabled()) { result.add(deviceId); } } return result; } else { return new HashSet<>(); } }

Target:
public Set<Long> getUserItems(long userId) { if (Context.getPermissionsManager() != null) { Set<Long> result = new HashSet<>(); for (long deviceId : Context.getPermissionsManager().getDevicePermissions(userId)) { Device device = getById(deviceId); if (device != null && !device.getDisabled()) { result.add(deviceId); } } return result; } else { return new HashSet<>(); } }
Source:
private static void notify(final String title, final String subtitle, NotificationType type) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { Notification start = new Notification(PantsConstants.PANTS, PantsIcons.Icon, title, subtitle, null, type, null); Notifications.Bus.notify(start); } }); }

Target:
private void notify(final String title, final String subtitle, NotificationType type) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { Notification start = new Notification(PantsConstants.PANTS, PantsIcons.Icon, title, subtitle, null, type, null); Notifications.Bus.notify(start); } }); }
Source:
MediaPlayer createMediaPlayer(Context ctx) { if (isUiThread()) { return new MediaPlayer(); } mplayerCreated_ = false; mediaPlayer_ = null; Handler mainHandler = new Handler(ctx.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { synchronized(lock1_) { try { mediaPlayer_ = new MediaPlayer(); Log.e(TAG, "media player created"); } finally { mplayerCreated_ = true; lock1_.notifyAll(); } } } }; mainHandler.post(myRunnable); try { synchronized(lock1_) { while(mplayerCreated_ == false) { lock1_.wait(); } } }catch (InterruptedException e){ Log.e(TAG, "Cought exception", e); } return mediaPlayer_; }

Target:
MediaPlayer createMediaPlayer(Context ctx) { if (isUiThread()) { return new MediaPlayer(); } mplayerCreated_ = false; mediaPlayer_ = null; Handler mainHandler = new Handler(ctx.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { synchronized(lock1_) { try { mediaPlayer_ = new MediaPlayer(); Log.i(TAG, "media player created"); } finally { mplayerCreated_ = true; lock1_.notifyAll(); } } } }; mainHandler.post(myRunnable); try { synchronized(lock1_) { while(mplayerCreated_ == false) { lock1_.wait(); } } }catch (InterruptedException e){ Log.e(TAG, "Cought exception", e); } return mediaPlayer_; }
Source:
private int distanceUntilTurn() { final GeoPoint whereIam = whereIAm(); final int fromEnd; if (whereIam == null) { fromEnd = Integer.MAX_VALUE;} else { final Segment activeSeg = Route.journey().activeSegment(); fromEnd = activeSeg.distanceFromEnd(whereIam); } return fromEnd; }

Target:
private Integer distanceUntilTurn() { final GeoPoint whereIam = whereIAm(); if (whereIam != null) { final Segment activeSeg = Route.journey().activeSegment(); return activeSeg.distanceFromEnd(whereIam); } return null; }
Source:
public void leaveTree(CssRootNode root) { String remaining = Generator.escape(sb.toString()); masterStringBuilder.append(remaining).append("\")"); super.leaveTree(root); }

Target:
public void leaveTree(CssRootNode root) { masterStringBuilder.append(flushInternalStringBuilder()).append(")"); super.leaveTree(root); }
Source:
public BundleMessagesRequestDto mapAllActions(final BundleMessageRequest bundleMessageDataContainer, final SmartMeter smartMeter) throws FunctionalException { final List<ActionDto> actionValueObjectDtoList = new ArrayList<>(); for (ActionRequest action : bundleMessageDataContainer.getBundleList()) { @SuppressWarnings("unchecked") final CustomValueToDtoConverter<ActionRequest, ActionRequestDto> customValueToDtoConverter = (CustomValueToDtoConverter<ActionRequest, ActionRequestDto>) CUSTOM_CONVERTER_FOR_CLASS .get(action.getClass()); if (customValueToDtoConverter != null) { actionValueObjectDtoList.add(new ActionDto(customValueToDtoConverter.convert(action, smartMeter))); } else { final ConfigurableMapper mapper = CLASS_TO_MAPPER_MAP.get(action.getClass()); final Class<? extends ActionRequestDto> clazz = CLASS_MAP.get(action.getClass()); if (mapper != null) { if (action instanceof MBusActionRequest) { action = this.verifyAndFindChannelForMBusRequest((MBusActionRequest) action, smartMeter); } actionValueObjectDtoList.add(new ActionDto(this.performDefaultMapping(action, mapper, clazz))); } else { throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.DOMAIN_SMART_METERING, new AssertionError("No mapper defined for class: " + clazz.getName())); } } } return new BundleMessagesRequestDto(actionValueObjectDtoList); }

Target:
public BundleMessagesRequestDto mapAllActions(final BundleMessageRequest bundleMessageDataContainer, final SmartMeter smartMeter) throws FunctionalException { final List<ActionDto> actionValueObjectDtoList = new ArrayList<>(); for (ActionRequest action : bundleMessageDataContainer.getBundleList()) { @SuppressWarnings("unchecked") final CustomValueToDtoConverter<ActionRequest, ActionRequestDto> customValueToDtoConverter = (CustomValueToDtoConverter<ActionRequest, ActionRequestDto>) CUSTOM_CONVERTER_FOR_CLASS .get(action.getClass()); if (customValueToDtoConverter != null) { actionValueObjectDtoList.add(new ActionDto(customValueToDtoConverter.convert(action, smartMeter))); } else { final ConfigurableMapper mapper = CLASS_TO_MAPPER_MAP.get(action.getClass()); final Class<? extends ActionRequestDto> clazz = CLASS_MAP.get(action.getClass()); if (mapper != null) { if (action instanceof MbusActionRequest) { action = this.verifyAndFindChannelForMbusRequest((MbusActionRequest) action, smartMeter); } actionValueObjectDtoList.add(new ActionDto(this.performDefaultMapping(action, mapper, clazz))); } else { throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.DOMAIN_SMART_METERING, new AssertionError("No mapper defined for class: " + clazz.getName())); } } } return new BundleMessagesRequestDto(actionValueObjectDtoList); }
Source:
public boolean verifyDigitalSignature( InputStream data, InputStream signature, String certificateAlias) throws IOException, CatalogCommandRuntimeException { byte[] sigToVerify = IOUtils.toByteArray(signature); Certificate certificate = getCertificate(certificateAlias); if (certificate == null) { throw new CatalogCommandRuntimeException(""); } try (BufferedInputStream bufferedInputStream = new BufferedInputStream(data)) { Signature rsa = Signature.getInstance("SHA256withRSA"); rsa.initVerify(certificate); byte[] buffer = new byte[BUFFER_SIZE]; int len; while (bufferedInputStream.available() != 0) { len = bufferedInputStream.read(buffer); rsa.update(buffer, OFFSET, len); } return rsa.verify(sigToVerify); } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) { String message = "An error occurred while signing file"; LOGGER.debug(message, e); throw new CatalogCommandRuntimeException(message, e); } }

Target:
public boolean verifyDigitalSignature( InputStream data, InputStream signature, String certificateAlias) throws IOException { byte[] sigToVerify = IOUtils.toByteArray(signature); Certificate certificate = getCertificate(certificateAlias); if (certificate == null) { throw new CatalogCommandRuntimeException("Unable to retrieve certificate"); } try { Signature rsa = Signature.getInstance("SHA256withRSA"); rsa.initVerify(certificate); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = data.read(buffer)) >= 0) { rsa.update(buffer, OFFSET, len); } return rsa.verify(sigToVerify); } catch (InvalidKeyException | SignatureException | NoSuchAlgorithmException e) { String message = "An error occurred while verifying file"; LOGGER.debug(message, e); throw new CatalogCommandRuntimeException(message, e); } }
Source:
protected void paintCenter(GC g) { TableMergeViewer leftMergeViewer = getLeftMergeViewer(); TableMergeViewer rightMergeViewer = getRightMergeViewer(); Table leftTable = leftMergeViewer.getStructuredViewer().getTable(); Table rightTable = rightMergeViewer.getStructuredViewer().getTable(); Rectangle leftClientArea = leftTable.getClientArea(); Rectangle rightClientArea = rightTable.getClientArea(); TableItem[] leftItems = leftTable.getItems(); TableItem[] rightItems = rightTable.getItems(); TableItem[] selection = leftTable.getSelection(); for (TableItem leftItem : leftItems) { final boolean selected; if (selection.length > 0) { selected = leftItem == selection[0]; } else { selected = false; } final Diff leftDiff = ((IMergeViewerItem)leftItem.getData()).getDiff(); if (leftDiff != null) { TableItem rightItem = findRightTableItemFromLeftDiff(rightItems, leftDiff); if (rightItem != null) { Color strokeColor = getCompareColor().getStrokeColor(leftDiff, isThreeWay(), false, selected); g.setForeground(strokeColor); drawCenterLine(g, leftClientArea, rightClientArea, leftItem, rightItem); } } } }

Target:
protected void paintCenter(GC g) { TableMergeViewer leftMergeViewer = getLeftMergeViewer(); TableMergeViewer rightMergeViewer = getRightMergeViewer(); Table leftTable = leftMergeViewer.getStructuredViewer().getTable(); Table rightTable = rightMergeViewer.getStructuredViewer().getTable(); Rectangle leftClientArea = leftTable.getClientArea(); Rectangle rightClientArea = rightTable.getClientArea(); TableItem[] leftItems = leftTable.getItems(); TableItem[] rightItems = rightTable.getItems(); final ImmutableSet<TableItem> selection = ImmutableSet.copyOf(leftTable.getSelection()); for (TableItem leftItem : leftItems) { final boolean selected = Iterables.any(selection, equalTo(leftItem)); IMergeViewerItem leftData = (IMergeViewerItem)leftItem.getData(); final Diff leftDiff = ((IMergeViewerItem)leftItem.getData()).getDiff(); boolean doPaint = true; if (leftDiff != null) { for (IDifferenceFilter filter : getEMFCompareConfiguration().getSelectedFilters()) { TreeNode treeNode = MergeViewerUtil.getTreeNode(getEMFCompareConfiguration() .getComparison(), getEMFCompareConfiguration().getSelectedGroup(), leftDiff); if (filter.getPredicateWhenSelected().apply(treeNode) && !DiffUtil.isPrimeRefining(treeNode.getData())) { doPaint = false; break; } } } if (doPaint) { if (leftDiff != null) { TableItem rightItem = findRightTableItemFromLeftDiff(rightItems, leftDiff, leftData); if (rightItem != null) { Color strokeColor = getCompareColor().getStrokeColor(leftDiff, isThreeWay(), false, selected); g.setForeground(strokeColor); drawCenterLine(g, leftClientArea, rightClientArea, leftItem, rightItem); } } } } }
Source:
private void startDismissTimerIfNeeded() { if (!(dismissDuration >= 0)) return; if (scheduleDismissRunnable != null) return; scheduleDismissRunnable = new Runnable() { public void run() { if (currentActivity != null) { dismissAndAwaitNextMessage(null); scheduleDismissRunnable = null; } else { shouldDismissWhenActive = true; } } }; handler.postDelayed(scheduleDismissRunnable, (long) dismissDuration * 1_000); }

Target:
private void startDismissTimerIfNeeded() { if (dismissDuration <= 0) return; if (scheduleDismissRunnable != null) return; scheduleDismissRunnable = new Runnable() { public void run() { if (currentActivity != null) { dismissAndAwaitNextMessage(null); scheduleDismissRunnable = null; } else { shouldDismissWhenActive = true; } } }; handler.postDelayed(scheduleDismissRunnable, (long) dismissDuration * 1_000); }
Source:
public void testTimeout() throws InterruptedException { final String lockOwner1 = "LO1"; final String lockOwner2 = "LO2"; final InfinispanLock lock = new InfinispanLock(commonPool(), commonPool(), AbstractCacheTest.TIME_SERVICE); final LockPromise lockPromise1 = lock.acquire(lockOwner1, 0, TimeUnit.MILLISECONDS); final LockPromise lockPromise2 = lock.acquire(lockOwner2, 0, TimeUnit.MILLISECONDS); assertTrue(lockPromise1.isAvailable()); assertTrue(lockPromise2.isAvailable()); lockPromise1.lock(); assertEquals(lockOwner1, lock.getLockOwner()); try { lockPromise2.lock(); fail(); } catch (TimeoutException e) { } lock.release(lockOwner1); assertNull(lock.getLockOwner()); assertFalse(lock.isLocked()); lock.release(lockOwner2); assertFalse(lock.isLocked()); assertNull(lock.getLockOwner()); }

Target:
public void testTimeout() throws InterruptedException { final String lockOwner1 = "LO1"; final String lockOwner2 = "LO2"; final InfinispanLock lock = new InfinispanLock(testExecutor(), AbstractCacheTest.TIME_SERVICE); final LockPromise lockPromise1 = lock.acquire(lockOwner1, 0, TimeUnit.MILLISECONDS); final LockPromise lockPromise2 = lock.acquire(lockOwner2, 0, TimeUnit.MILLISECONDS); assertTrue(lockPromise1.isAvailable()); assertTrue(lockPromise2.isAvailable()); lockPromise1.lock(); assertEquals(lockOwner1, lock.getLockOwner()); try { lockPromise2.lock(); fail(); } catch (TimeoutException e) { } lock.release(lockOwner1); assertNull(lock.getLockOwner()); assertFalse(lock.isLocked()); lock.release(lockOwner2); assertFalse(lock.isLocked()); assertNull(lock.getLockOwner()); }
Source:
public void apply(NodeRemovalNomadChange change) throws NomadException { Cluster runtime = topologyService.getRuntimeNodeContext().getCluster(); Node node = change.getNode(); if (!runtime.containsNode(node.getUID())) { return; } if (killAtCommit.equals(topologyService.getUpcomingNodeContext().getNode().getTcProperties().orDefault().get(failoverKey))) { Path path = null; try { path = path().resolve("killed"); Files.createFile(path); platformService.stopPlatform(); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); try { org.terracotta.utilities.io.Files.deleteIfExists(path); } catch (IOException ex) { throw new RuntimeException(ex); } } } try { LOGGER.info("Removing node: from stripe UID: {}", node.getName(), change.getStripeUID()); LOGGER.debug("Calling mBean {}#{}", TOPOLOGY_MBEAN, PLATFORM_MBEAN_OPERATION_NAME); mbeanServer.invoke( TOPOLOGY_MBEAN, PLATFORM_MBEAN_OPERATION_NAME, new Object[]{node.getHostname(), node.getPort().orDefault(), node.getGroupPort().orDefault()}, new String[]{String.class.getName(), int.class.getName(), int.class.getName()} ); dynamicConfigEventFiring.onNodeRemoval(change.getStripeUID(), node); } catch (RuntimeException | JMException e) { throw new NomadException("Error when applying: '" + change.getSummary() + "': " + e.getMessage(), e); } }

Target:
public void apply(NodeRemovalNomadChange change) throws NomadException { Cluster runtime = topologyService.getRuntimeNodeContext().getCluster(); Node node = change.getNode(); if (!runtime.containsNode(node.getUID())) { return; } if (killAtCommit.equals(topologyService.getUpcomingNodeContext().getNode().getTcProperties().orDefault().get(failoverKey))) { Path path = null; try { path = path().resolve("killed"); Files.createFile(path); platformService.stopPlatform(); } catch (FileAlreadyExistsException e) { LOGGER.warn(e.getMessage(), e); try { org.terracotta.utilities.io.Files.deleteIfExists(path); } catch (IOException ex) { throw new RuntimeException(ex); } } catch (IOException e) { throw new RuntimeException(e); } } try { LOGGER.info("Removing node: from stripe UID: {}", node.getName(), change.getStripeUID()); LOGGER.debug("Calling mBean {}#{}", TOPOLOGY_MBEAN, PLATFORM_MBEAN_OPERATION_NAME); mbeanServer.invoke( TOPOLOGY_MBEAN, PLATFORM_MBEAN_OPERATION_NAME, new Object[]{node.getHostname(), node.getPort().orDefault(), node.getGroupPort().orDefault()}, new String[]{String.class.getName(), int.class.getName(), int.class.getName()} ); dynamicConfigEventFiring.onNodeRemoval(change.getStripeUID(), node); } catch (RuntimeException | JMException e) { throw new NomadException("Error when applying: '" + change.getSummary() + "': " + e.getMessage(), e); } }
Source:
public TimerJobInstance getTimerByName(String jobName) { if(USE_LOCAL_CACHE) { if (localCache.containsKey(jobName)) { logger.debug("Found job in cache returning", jobName); return localCache.get(jobName); } } TimerJobInstance found = null; for (Timer timer : timerService.getTimers()) { try { Serializable info = timer.getInfo(); if (info instanceof EjbTimerJob) { EjbTimerJob job = (EjbTimerJob) info; EjbGlobalJobHandle handle = (EjbGlobalJobHandle) job.getTimerJobInstance().getJobHandle(); if(USE_LOCAL_CACHE) localCache.putIfAbsent(jobName, handle.getTimerJobInstance()); if (handle.getUuid().equals(jobName)) { logger.debug("Job does match timer and is going to be returned", jobName); found = handle.getTimerJobInstance(); } } } catch (NoSuchObjectLocalException e) { logger.debug("Timer info for was not found ", timer); } } return found; }

Target:
public TimerJobInstance getTimerByName(String jobName) { if (USE_LOCAL_CACHE) { if (localCache.containsKey(jobName)) { logger.debug("Found job in cache returning", jobName); return localCache.get(jobName); } } TimerJobInstance found = null; for (Timer timer : timerService.getTimers()) { try { Serializable info = timer.getInfo(); if (info instanceof EjbTimerJob) { EjbTimerJob job = (EjbTimerJob) info; EjbGlobalJobHandle handle = (EjbGlobalJobHandle) job.getTimerJobInstance().getJobHandle(); if (USE_LOCAL_CACHE) { localCache.putIfAbsent(jobName, handle.getTimerJobInstance()); } if (handle.getUuid().equals(jobName)) { logger.debug("Job does match timer and is going to be returned", jobName); found = handle.getTimerJobInstance(); } } } catch (NoSuchObjectLocalException e) { logger.debug("Timer info for was not found ", timer); } } return found; }
Source:
public Boolean isDirectDownload() { return directDownload == null ? Boolean.FALSE : directDownload; }

Target:
public boolean isDirectDownload() { return directDownload; }
Source:
public CtfIterator getIterator(final CtfTmfContext context) { CtfIterator iter = fMap.get(context); if (iter == null) { fAccessLock.lock(); try { if (fRandomAccess.size() < MAX_SIZE) { iter = (CtfIterator) fTrace.createIterator(); if (iter == null) { return null; } addElement(context, iter); } else { iter = replaceRandomElement(context); } if (context.getLocation() != null) { final CtfLocationInfo location = (CtfLocationInfo) context.getLocation().getLocationInfo(); iter.seek(location); } } finally { fAccessLock.unlock(); } } return iter; }

Target:
public @Nullable CtfIterator getIterator(final CtfTmfContext context) { CtfIterator iter = fMap.get(context); if (iter == null) { fAccessLock.lock(); try { if (fRandomAccess.size() < MAX_SIZE) { iter = (CtfIterator) fTrace.createIterator(); if (iter == null) { return null; } addElement(context, iter); } else { iter = replaceRandomElement(context); } if (context.getLocation() != null) { final CtfLocationInfo location = (CtfLocationInfo) context.getLocation().getLocationInfo(); iter.seek(location); } } finally { fAccessLock.unlock(); } } return iter; }
Source:
public UserDevfileSearchQueryBuilder withFilter(List<Pair<String, String>> filter) { if (filter == null || filter.isEmpty()) { this.filter = ""; return this; } final StringJoiner matcher = new StringJoiner(" AND ", " WHERE ", " "); int i = 0; for (Pair<String, String> attribute : filter) { final String parameterName = "parameterName" + i++; if (attribute.second.startsWith("like:")) { params.put(parameterName, attribute.second.substring(5)); matcher.add("userdevfile." + attribute.first + " LIKE :" + parameterName); } else { params.put(parameterName, attribute.second); matcher.add("userdevfile." + attribute.first + " = :" + parameterName); } } this.filter = matcher.toString(); return this; }

Target:
public UserDevfileSearchQueryBuilder withFilter(List<Pair<String, String>> filter) { if (filter == null || filter.isEmpty()) { return this; } final StringJoiner matcher = new StringJoiner(" AND ", " WHERE ", " "); int i = 0; for (Pair<String, String> attribute : filter) { if (!VALID_SEARCH_FIELDS.contains(attribute.first.toLowerCase())) { throw new IllegalArgumentException( "Filtering allowed only by " + VALID_SEARCH_FIELDS + " but got: " + attribute.first); } final String parameterName = "parameterName" + i++; if (attribute.second.startsWith("like:")) { params.put(parameterName, attribute.second.substring(5)); matcher.add("userdevfile." + attribute.first + " LIKE :" + parameterName); } else { params.put(parameterName, attribute.second); matcher.add("userdevfile." + attribute.first + " = :" + parameterName); } } this.filter = matcher.toString(); return this; }
Source:
private boolean isInStudy(StudyIdentifier studyId, Survey survey) { if (studyId == null || survey == null || survey.getStudyIdentifier() == null) { return true; } return survey.getStudyIdentifier().equals("shared") || survey.getStudyIdentifier().equals(studyId.getIdentifier()); }

Target:
private boolean isInStudy(StudyIdentifier studyId, Survey survey) { return isInStudy(ImmutableSet.of(), studyId, survey); }
Source:
private boolean mustCheckPasswordValidity() { return Framework.getService(ConfigurationService.class).getBoolean(VALIDATE_PASSWORD_PARAM, true); }

Target:
private boolean mustCheckPasswordValidity() { return Framework.getService(ConfigurationService.class).isBooleanTrue(VALIDATE_PASSWORD_PARAM); }
Source:
protected void doDelivery(ResourceDeliveryMessage theMsg, CanonicalSubscription theSubscription, IChannelProducer theChannelProducer, IBaseResource thePayloadResource) { ResourceModifiedMessage payload = new ResourceModifiedMessage(myFhirContext, thePayloadResource, theMsg.getOperationType()); payload.setParentTransactionGuid(theMsg.getParentTransactionGuid()); ResourceModifiedJsonMessage message = new ResourceModifiedJsonMessage(payload); theChannelProducer.send(message); ourLog.debug("Delivering message payload for {}", theMsg.getOperationType(), theMsg.getPayloadId(), theSubscription.getIdElement(myFhirContext).toUnqualifiedVersionless().getValue()); }

Target:
protected void doDelivery(ResourceDeliveryMessage theMsg, CanonicalSubscription theSubscription, IChannelProducer theChannelProducer, IBaseResource thePayloadResource) { ResourceModifiedMessage payload = new ResourceModifiedMessage(myFhirContext, thePayloadResource, theMsg.getOperationType()); payload.setTransactionId(theMsg.getTransactionId()); ResourceModifiedJsonMessage message = new ResourceModifiedJsonMessage(payload); theChannelProducer.send(message); ourLog.debug("Delivering message payload for {}", theMsg.getOperationType(), theMsg.getPayloadId(), theSubscription.getIdElement(myFhirContext).toUnqualifiedVersionless().getValue()); }
Source:
protected TokenTaskResult doInBackground(Void... empty) { Oauth2 oauthRequest = new Oauth2(mAuthRequest, mWebRequestHandler); TokenTaskResult result = new TokenTaskResult(); try { result.taskResult = oauthRequest.getToken(mUrl); Logger.v(TAG, "TokenTask processed the result. " + mAuthRequest.getLogInfo()); } catch (Exception exc) { Logger.e(TAG, "Error in processing code to get a token. " + mAuthRequest.getLogInfo(), "", ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN, exc); result.taskException = exc; } if (result != null && result.taskResult != null && result.taskResult.getAccessToken() != null) { Logger.v(TAG, "Setting account:" + mAuthRequest.getLogInfo()); try { setAccount(result); } catch (Exception exc) { Logger.e(TAG, "Error in setting the account" + mAuthRequest.getLogInfo(), "", ADALError.BROKER_ACCOUNT_SAVE_FAILED, exc); result.taskException = exc; } } return result; }

Target:
protected TokenTaskResult doInBackground(Void... empty) { Oauth2 oauthRequest = new Oauth2(mAuthRequest, mWebRequestHandler); TokenTaskResult result = new TokenTaskResult(); try { result.taskResult = oauthRequest.getToken(mUrl); Logger.v(TAG, "TokenTask processed the result. " + mAuthRequest.getLogInfo()); } catch (Exception exc) { Logger.e(TAG, "Error in processing code to get a token. " + mAuthRequest.getLogInfo(), "Request url:" + mUrl, ADALError.AUTHORIZATION_CODE_NOT_EXCHANGED_FOR_TOKEN, exc); result.taskException = exc; } if (result != null && result.taskResult != null && result.taskResult.getAccessToken() != null) { Logger.v(TAG, "Setting account:" + mAuthRequest.getLogInfo()); try { setAccount(result); } catch (Exception exc) { Logger.e(TAG, "Error in setting the account" + mAuthRequest.getLogInfo(), "", ADALError.BROKER_ACCOUNT_SAVE_FAILED, exc); result.taskException = exc; } } return result; }
Source:
private void executeBatchUpdateAssociation(Map<DBCollection, BatchInsertionTask> inserts, UpdateAssociationOperation updateOp) { AssociationKey associationKey = updateOp.getAssociationKey(); AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy( associationKey, updateOp.getContext() ); if ( AssociationStorageStrategy.IN_ENTITY == storageStrategy ) { DBCollection collection = getCollection( associationKey.getEntityKey() ); if ( inserts.containsKey( collection ) ) { BatchInsertionTask insertionTask = inserts.get( collection ); if ( insertionTask.containsKey( associationKey.getEntityKey() ) ) { WriteConcern writeConcern = getWriteConcern( updateOp.getContext() ); BatchInsertionTask batchInsertionTask = getOrCreateBatchInsertionTask( inserts, collection, writeConcern ); DBObject currentDocument = batchInsertionTask.get( associationKey.getEntityKey() ); List<?> rows = getAssociationRows( updateOp.getAssociation(), updateOp.getAssociationKey() ); MongoHelpers.setValue( currentDocument, associationKey.getMetadata().getCollectionRole(), rows ); return; } } } insertOrUpdateAssociation( updateOp.getAssociationKey(), updateOp.getAssociation(), updateOp.getContext() ); }

Target:
private void executeBatchUpdateAssociation(Map<DBCollection, BatchInsertionTask> inserts, UpdateAssociationOperation updateOp) { AssociationKey associationKey = updateOp.getAssociationKey(); AssociationStorageStrategy storageStrategy = getAssociationStorageStrategy( associationKey, updateOp.getContext() ); if ( AssociationStorageStrategy.IN_ENTITY == storageStrategy ) { DBCollection collection = getCollection( associationKey.getEntityKey() ); if ( inserts.containsKey( collection ) ) { BatchInsertionTask insertionTask = inserts.get( collection ); if ( insertionTask.containsKey( associationKey.getEntityKey() ) ) { updateDocumentWithAssociationRows( inserts, updateOp, associationKey, collection ); return; } } } insertOrUpdateAssociation( updateOp.getAssociationKey(), updateOp.getAssociation(), updateOp.getContext() ); }
Source:
public void buildBasicImage() throws Exception { final String rule = "rultor-on-commit"; final ButtonRs res = new ButtonRs( new ButtonRs.Build() { @Override public String info(final URI uri, final String stand) { return String.format( "<page><widgets><widget class=\"com.rultor.widget.BuildHealth\"><builds><build>" + " <coordinates><rule>%s</rule></coordinates>" + " <duration>1212602</duration>" + " <code>0</code>" + " <health>0.6153846153846154</health>" + "</build></builds></widget></widgets></page>", rule ); } } ); res.setUriInfo(new UriInfoMocker().mock()); res.setHttpHeaders(new HttpHeadersMocker().mock()); res.setSecurityContext(Mockito.mock(SecurityContext.class)); res.setStand("stand"); res.setRule(rule); final ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getResourceAsStream(Mockito.anyString())) .thenReturn( this.getClass().getResourceAsStream( "/com/rultor/web/button.xsl" ) ); res.setServletContext(context); MatcherAssert.assertThat( URLConnection.guessContentTypeFromStream( new ByteArrayInputStream((byte[]) res.button().getEntity()) ), Matchers.equalTo(MediaType.PNG.toString()) ); }

Target:
public void buildBasicImage() throws Exception { final String rule = "rultor-on-commit"; final ButtonRs res = new ButtonRs( new ButtonRs.Build() { @Override public String info(final URI uri, final String stand) { return String.format( "<page><widgets><widget class=\"com.rultor.widget.BuildHealth\"><builds><build>" + " <coordinates><rule>%s</rule></coordinates>" + " <duration>1212602</duration>" + " <code>0</code>" + " <health>0.6153846153846154</health>" + "</build></builds></widget></widgets></page>", rule ); } } ); res.setUriInfo(new UriInfoMocker().mock()); res.setHttpHeaders(new HttpHeadersMocker().mock()); res.setSecurityContext(Mockito.mock(SecurityContext.class)); res.setStand("stand"); res.setRule(rule); final ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getResourceAsStream(Mockito.anyString())) .thenReturn( this.getClass().getResourceAsStream( "button.xsl" ) ); res.setServletContext(context); MatcherAssert.assertThat( URLConnection.guessContentTypeFromStream( new ByteArrayInputStream((byte[]) res.button().getEntity()) ), Matchers.equalTo(MediaType.PNG.toString()) ); }
Source:
private void createResourceSelectionComposite(Composite parent) { resourceSelectionComposite = new ResourceSelectionComposite( parent, SWT.BORDER | SWT.V_SCROLL, PlatformUI.getPreferenceStore() .getBoolean(EclipsePreferenceConstants.PROJECTSELECTION_FILTERCLOSEDPROJECTS)); final Runnable takeOverPerspectiveSelection = new Runnable() { @Override public void run() { final List<IResource> selectedResources = new ArrayList<IResource>(); resourceSelectionComposite.addResourceSelectionListener(resourceSelectionListener); if (preselectedResources != null && preselectedResources.size() > 0) { selectedResources.addAll(preselectedResources); resourceSelectionComposite.setSelectedResources(selectedResources); } preselectedResources = null; List<IProject> displayedProjects = resourceSelectionComposite.getDisplayedProjects(); if (selectedResources.size() == 0 && displayedProjects.size() == 1) { selectedResources.addAll(displayedProjects); resourceSelectionComposite.setSelectedResources(selectedResources); } resourceSelectionComposite.rememberSelection(); if (selectedResources.size() > 0) { setPageComplete(true); } else { setErrorMessage(Messages.ProjectSelectionWizardPage_selected_no_project); setPageComplete(false); } } }; SWTUtils.runSafeSWTAsync( log, new Runnable() { @Override public void run() { final Shell shell = ResourceSelectionWizardPage.this.getShell(); if (shell == null || shell.isDisposed()) return; BusyIndicator.showWhile(shell.getDisplay(), takeOverPerspectiveSelection); } }); }

Target:
private void createResourceSelectionComposite(Composite parent) { resourceSelectionComposite = new ResourceSelectionComposite( parent, SWT.BORDER | SWT.V_SCROLL, PlatformUI.getPreferenceStore() .getBoolean(EclipsePreferenceConstants.PROJECTSELECTION_FILTERCLOSEDPROJECTS)); final Runnable takeOverPerspectiveSelection = new Runnable() { @Override public void run() { resourceSelectionComposite.addResourceSelectionListener(resourceSelectionListener); if (preselectedResources != null && !preselectedResources.isEmpty()) { resourceSelectionComposite.setSelectedResources( new ArrayList<>(preselectedResources)); } preselectedResources = null; if (!resourceSelectionComposite.getSelectedBaseContainers().isEmpty()) { resourceSelectionComposite.rememberSelection(); setPageComplete(true); } else { setPageComplete(false); } } }; SWTUtils.runSafeSWTAsync( log, new Runnable() { @Override public void run() { final Shell shell = ResourceSelectionWizardPage.this.getShell(); if (shell == null || shell.isDisposed()) return; BusyIndicator.showWhile(shell.getDisplay(), takeOverPerspectiveSelection); } }); }
Source:
public static TimeDistanceMatrix provideMatrix(Config config) { if (config.getBoolean(Keys.MATRIX_ENABLE)) { String type = config.getString(Keys.MATRIX_TYPE, "locationiq"); String url = config.getString(Keys.MATRIX_URL); String key = config.getString(Keys.MATRIX_KEY); switch (type) { case "openrouteservice": return new OpenRouteServiceTimeDistance(url, key); case "locationiq": default: return new LocationIQTimeDistance(url, key); } } return null; }

Target:
public static TimeDistanceMatrix provideMatrix(Config config) { if (config.getBoolean(Keys.TIMEDISTANCEMATRIX_ENABLE)) { String type = config.getString(Keys.TIMEDISTANCEMATRIX_TYPE, "locationiq"); String url = config.getString(Keys.TIMEDISTANCEMATRIX_URL); String key = config.getString(Keys.TIMEDISTANCEMATRIX_KEY); switch (type) { case "openrouteservice": return new OpenRouteServiceTimeDistance(url, key); case "locationiq": default: return new LocationIqTimeDistance(url, key); } } return null; }
Source:
public static void main(String... args) throws IOException { final Main main = new Main(); final CommandLine commandLine = new CommandLine(main); commandLine.setUsageHelpWidth(HELP_WIDTH); commandLine.setCaseInsensitiveEnumValuesAllowed(true); int exitStatus = 0; int errorCounter = 0; try { final ParseResult parseResult = commandLine.parseArgs(args); final boolean helpWasRequested = CommandLine.printHelpIfRequested(parseResult); if (!helpWasRequested) { exitStatus = main.call(); if (exitStatus > 0) { errorCounter = exitStatus; } } } catch (ParameterException ex) { System.err.println(ex.getMessage()); ex.getCommandLine().usage(System.err); exitStatus = EXIT_WITH_INVALID_USER_INPUT_CODE; } catch (CheckstyleException ex) { exitStatus = EXIT_WITH_CHECKSTYLE_EXCEPTION_CODE; errorCounter = 1; ex.printStackTrace(); } finally { if (errorCounter > 0) { final LocalizedMessage errorCounterMessage = new LocalizedMessage(1, Definitions.CHECKSTYLE_BUNDLE, ERROR_COUNTER, new String[] {String.valueOf(errorCounter)}, null, Main.class, null); System.out.println(errorCounterMessage.getMessage()); } if (exitStatus != 0) { System.exit(exitStatus); } } }

Target:
public static void main(String... args) throws IOException { final CliOptions cliOptions = new CliOptions(); final CommandLine commandLine = new CommandLine(cliOptions); commandLine.setUsageHelpWidth(CliOptions.HELP_WIDTH); commandLine.setCaseInsensitiveEnumValuesAllowed(true); int exitStatus = 0; int errorCounter = 0; try { final ParseResult parseResult = commandLine.parseArgs(args); if (parseResult.isVersionHelpRequested()) { System.out.println(getVersionString()); } else if (parseResult.isUsageHelpRequested()) { commandLine.usage(System.out); } else { exitStatus = execute(parseResult, cliOptions); errorCounter = exitStatus; } } catch (ParameterException ex) { exitStatus = EXIT_WITH_INVALID_USER_INPUT_CODE; System.err.println(ex.getMessage()); System.err.println("Usage: checkstyle [OPTIONS]... FILES..."); System.err.println("Try 'checkstyle --help' for more information."); } catch (CheckstyleException ex) { exitStatus = EXIT_WITH_CHECKSTYLE_EXCEPTION_CODE; errorCounter = 1; ex.printStackTrace(); } finally { if (errorCounter > 0) { final LocalizedMessage errorCounterMessage = new LocalizedMessage(1, Definitions.CHECKSTYLE_BUNDLE, ERROR_COUNTER, new String[] {String.valueOf(errorCounter)}, null, Main.class, null); System.out.println(errorCounterMessage.getMessage()); } if (exitStatus != 0) { System.exit(exitStatus); } } }
Source:
private long updateInstanceId() { long nextInstanceId = 0L; boolean transactionAborted = false; do { try { runtime.getObjectsView().TXBuild() .type(TransactionType.OPTIMISTIC) .build() .begin(); nextInstanceId = distributedCounter.getOrDefault(GUID_STREAM_KEY, 1L) + 1; distributedCounter.put(GUID_STREAM_KEY, nextInstanceId); runtime.getObjectsView().TXEnd(); transactionAborted = false; } catch (TransactionAbortedException e) { log.error("Transaction aborted while trying to update GUID counter", e); transactionAborted = true; } } while (transactionAborted); instanceId = nextInstanceId; return nextInstanceId; }

Target:
private long updateInstanceId() { long nextInstanceId = 0L; while(true) { try { runtime.getObjectsView().TXBuild() .type(TransactionType.OPTIMISTIC) .build() .begin(); nextInstanceId = distributedCounter.getOrDefault(GUID_STREAM_KEY, 1L) + 1; distributedCounter.put(GUID_STREAM_KEY, nextInstanceId); runtime.getObjectsView().TXEnd(); break; } catch (TransactionAbortedException e) { log.error("updateInstanceId: Transaction aborted while updating GUID counter", e); } } instanceId = nextInstanceId; return nextInstanceId; }
Source:
public void runAppAndBasicTest() throws InterruptedException, ExecutionException { assertThat(rest.get("http://localhost:8080/binder/test"), is("hello world!")); }

Target:
public void runAppAndBasicTest() throws InterruptedException, ExecutionException { assertThat(rest.get("http://localhost:8080/binder/test/myEndPoint"), is("hello world!")); }
Source:
private void loadData() { progressBar.setVisibility(View.VISIBLE); disposable = Observable.fromCallable(DBReader::getNavDrawerData) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { navDrawerData = result; updateSelection(); navAdapter.notifyDataSetChanged(); progressBar.setVisibility(View.GONE); }, error -> Log.e(TAG, Log.getStackTraceString(error))); }

Target:
private void loadData() { progressBar.setVisibility(View.VISIBLE); disposable = Observable.fromCallable(DBReader::getNavDrawerData) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( result -> { navDrawerData = result; updateSelection(); navAdapter.notifyDataSetChanged(); progressBar.setVisibility(View.GONE); }, error -> { Log.e(TAG, Log.getStackTraceString(error)); progressBar.setVisibility(View.GONE); }); }
Source:
private int executeStatement(boolean silent, String user, String pw, String sql, String... args) { Connection connection = null; Statement statement = null; try { String replacedSql = sql; if (wizardModel.databaseConnection.contains("mysql")) { Class.forName("com.mysql.jdbc.Driver").newInstance(); } else { replacedSql = replacedSql.replaceAll("`", "\""); } String tempDatabaseConnection = ""; if (sql.contains("create database")) { tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", ""); } else { tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); } connection = DriverManager.getConnection(tempDatabaseConnection, user, pw); for (String arg : args) { arg = arg.replace(";", "&#094"); replacedSql = replacedSql.replaceFirst("\\?", arg); } statement = connection.createStatement(); int updateDelta = statement.executeUpdate(replacedSql); statement.close(); return updateDelta; } catch (SQLException sqlex) { if (!silent) { log.warn("error executing sql: " + sql, sqlex); errors.put("Error executing sql: " + sql + " - " + sqlex.getMessage(), null); } } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) { log.error("Error generated", e); } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { log.warn("Error while closing statement"); } try { if (connection != null) { connection.close(); } } catch (Exception e) { log.warn("Error while closing connection", e); } } return -1; }

Target:
private int executeStatement(boolean silent, String user, String pw, String sql, String... args) { Connection connection = null; Statement statement = null; try { String replacedSql = sql; if (wizardModel.databaseConnection.contains("mysql")) { Class.forName("com.mysql.jdbc.Driver").newInstance(); } else { replacedSql = replacedSql.replaceAll("`", "\""); } String tempDatabaseConnection = ""; if (sql.contains("create database")) { tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", ""); } else { tempDatabaseConnection = wizardModel.databaseConnection.replace("@DBNAME@", wizardModel.databaseName); } connection = DriverManager.getConnection(tempDatabaseConnection, user, pw); for (String arg : args) { arg = arg.replace(";", "&#094"); replacedSql = replacedSql.replaceFirst("\\?", arg); } statement = connection.createStatement(); return statement.executeUpdate(replacedSql); } catch (SQLException sqlex) { if (!silent) { log.warn("error executing sql: " + sql, sqlex); errors.put("Error executing sql: " + sql + " - " + sqlex.getMessage(), null); } } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) { log.error("Error generated", e); } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { log.warn("Error while closing statement"); } try { if (connection != null) { connection.close(); } } catch (Exception e) { log.warn("Error while closing connection", e); } } return -1; }
Source:
public void jenkinsCoreTooOld() throws Exception { PluginWrapper pw = pluginWrapper("fake").requiredCoreVersion("3.0").buildLoaded(); try { pw.resolvePluginDependencies(); fail(); } catch (IOException ex) { assertContains(ex, "Failed to load: fake (42)", "Jenkins (3.0) or higher required"); } Locale.setDefault(loc); }

Target:
public void jenkinsCoreTooOld() throws Exception { PluginWrapper pw = pluginWrapper("fake").requiredCoreVersion("3.0").buildLoaded(); try { pw.resolvePluginDependencies(); fail(); } catch (IOException ex) { assertContains(ex, "Failed to load: fake (42)", "Jenkins (3.0) or higher required"); } }
Source:
private void setCovariance(Object cov) { if (cov instanceof MatrixSpec) { cov = ((MatrixSpec) cov).getValueIfNonRandom(); } if (!((cov instanceof MatrixLib) && (((MatrixLib) cov).rowLen() == d) && (((MatrixLib) cov) .colLen() == d))) { throw new IllegalArgumentException("The covariance matrix of a " + d + "-dimensional Gaussian " + "distribution must be a " + d + "-by-" + d + " Matrix, " + "not " + cov + " of " + cov.getClass()); } sigma = (MatrixLib) cov; for (int i = 0; i < sigma.rowLen(); i++) { for (int j = 0; j < sigma.colLen(); j++) { double ratio = sigma.elementAt(i, j) / sigma.elementAt(j, i); if (Math.abs(ratio - 1) > 1e-6) throw new IllegalArgumentException( "Invalid covariance matrix (not symmetric): " + sigma); } } normConst = Math.sqrt(sigma.det()) * dimFactor; double logDet = 0.0; for (double val : sigma.eigenvals()) { logDet += Math.log(val); } logNormConst = 0.5 * logDet + logDimFactor; sigmaInverse = sigma.inverse(); sqrtSigma = sigma.choleskyFactor(); }

Target:
private void setCovariance(Object cov) { if (cov instanceof MatrixSpec) { cov = ((MatrixSpec) cov).getValueIfNonRandom(); } if (!((cov instanceof MatrixLib) && (((MatrixLib) cov).rowLen() == d) && (((MatrixLib) cov) .colLen() == d))) { throw new IllegalArgumentException("The covariance matrix of a " + d + "-dimensional Gaussian " + "distribution must be a " + d + "-by-" + d + " Matrix, " + "not " + cov + " of " + cov.getClass()); } sigma = (MatrixLib) cov; for (int i = 0; i < sigma.rowLen(); i++) { for (int j = 0; j < sigma.colLen(); j++) { double ratio = sigma.elementAt(i, j) / sigma.elementAt(j, i); if (Math.abs(ratio - 1) > 1e-6) throw new IllegalArgumentException( "Invalid covariance matrix (not symmetric): " + sigma); } } normConst = Math.sqrt(sigma.det()) * dimFactor; logNormConst = 0.5 * sigma.logDet() + logDimFactor; sigmaInverse = sigma.inverse(); sqrtSigma = sigma.choleskyFactor(); }
Source:
private GridCoverage2D loadRaster(File location) throws IOException { LOGGER.info(String.format(LOG_LOADING_SOURCE_RASTER, location.toString())); try { ArcGridReader reader = new ArcGridReader(location.toURI().toURL()); return reader.read(null); } catch (Exception e) { LOGGER.error(String.format(LOG_FAILED_TO_READ_SOURCE_RASTER, location.toString()), e); throw new IOException(String.format(LOG_FAILED_TO_READ_SOURCE_RASTER, location.toString()), e); } }

Target:
private GridCoverage2D loadRaster(File location) throws IOException { LOGGER.info(String.format(LOG_LOADING_SOURCE_RASTER, location.toString())); try { ArcGridReader reader = new ArcGridReader(location.toURI().toURL()); return reader.read(null); } catch (Exception e) { final String message = String.format(LOG_FAILED_TO_READ_SOURCE_RASTER, location.toString()); LOGGER.error(message, e); throw new IOException(message, e); } }
Source:
public IStatus validate(final IProject project, final String path) { IStatus validTrace = Status.OK_STATUS; try { final CTFTrace temp = new CTFTrace(path); boolean valid = temp.majortIsSet(); temp.dispose(); if (!valid) { validTrace = new Status(IStatus.ERROR, Messages.CtfTmfTrace_FormatName, Messages.CtfTmfTrace_MajorNotSet); } } catch (final CTFReaderException e) { validTrace = new Status(IStatus.ERROR, "CTF", Messages.CtfTmfTrace_ReadingError + e.toString()); } return validTrace; }

Target:
public IStatus validate(final IProject project, final String path) { IStatus validTrace = Status.OK_STATUS; try { final CTFTrace temp = new CTFTrace(path); boolean valid = temp.majortIsSet(); temp.dispose(); if (!valid) { validTrace = new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.CtfTmfTrace_MajorNotSet); } } catch (final CTFReaderException e) { validTrace = new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.CtfTmfTrace_ReadingError +": " + e.toString()); } return validTrace; }
Source:
protected boolean canDoAction() { VDS vds = getVds(); if (vds == null) { addCanDoActionMessage(VdcBllMessages.VDS_INVALID_SERVER_ID); return false; } if (!ObjectIdentityChecker.CanUpdateField(vds, "vds_group_id", vds.getstatus())) { addCanDoActionMessage(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE); return false; } VDSGroup targetCluster = DbFacade.getInstance().getVdsGroupDAO().get(getParameters().getClusterId()); if (targetCluster == null) { addCanDoActionMessage(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); return false; } targetStoragePool = DbFacade.getInstance().getStoragePoolDAO().getForVdsGroup(targetCluster.getId()); if (targetStoragePool != null && targetStoragePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!DbFacade.getInstance().getVdsStaticDAO().getAllForVdsGroup(getParameters().getClusterId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_ADD_MORE_THEN_ONE_HOST_TO_LOCAL_STORAGE); return false; } } if (getVdsGroup().supportsGlusterService()) { if (getGlusterUtils().hasBricks(getVdsId())) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); return false; } if (!hasUpServer(getSourceClusterId())) { return false; } } if (getVdsGroup(getTargetClusterId()).supportsGlusterService() && !hasUpServer(getTargetClusterId())) { return false; } return true; }

Target:
protected boolean canDoAction() { VDS vds = getVds(); if (vds == null) { addCanDoActionMessage(VdcBllMessages.VDS_INVALID_SERVER_ID); return false; } if (!ObjectIdentityChecker.CanUpdateField(vds, "vds_group_id", vds.getstatus())) { addCanDoActionMessage(VdcBllMessages.VDS_STATUS_NOT_VALID_FOR_UPDATE); return false; } if (getTargetCluster() == null) { addCanDoActionMessage(VdcBllMessages.VDS_CLUSTER_IS_NOT_VALID); return false; } targetStoragePool = DbFacade.getInstance().getStoragePoolDAO().getForVdsGroup(getTargetCluster().getId()); if (targetStoragePool != null && targetStoragePool.getstorage_pool_type() == StorageType.LOCALFS) { if (!DbFacade.getInstance().getVdsStaticDAO().getAllForVdsGroup(getParameters().getClusterId()).isEmpty()) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_ADD_MORE_THEN_ONE_HOST_TO_LOCAL_STORAGE); return false; } } if (getVdsGroup().supportsGlusterService()) { if (getGlusterUtils().hasBricks(getSourceCluster().getId())) { addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_REMOVE_HOST_HAVING_GLUSTER_VOLUME); return false; } if (!hasUpServer(getSourceCluster().getId())) { return false; } } if (getTargetCluster().supportsGlusterService() && !hasUpServer(getTargetCluster().getId())) { return false; } return true; }