auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void afterDelete(Attachable object) { for (FileAttachment a : object.getAttachments()) { File file = new File(makeFullPath(a.getPath())); deleteFileOrLog(file, object, a); } File dir = new File(makeFullPath(makeRelativeDir(object.getAttachmentsTarget(), object.getId()))); if (dir.exists() && dir.isDirectory()) { if (dir.listFiles() != null) { for (File file : dir.listFiles()) { deleteFileOrLog(file, object, null); } } if (!dir.delete()) { log.error("Failed to delete directory for deleted object: " + dir.getAbsolutePath()); } } }

Target:
public void afterDelete(Attachable object) { for (FileAttachment a : object.getAttachments()) { File file = new File(makeFullPath(a.getPath())); deleteFileOrLog(file, object, a); } File dir = new File(makeFullPath(makeRelativeDir(object.getAttachmentsTarget(), object.getId()))); if (dir.exists() && dir.isDirectory()) { if (dir.listFiles() != null) { for (File file : dir.listFiles()) { deleteFileOrLog(file, object, null); } } if (!dir.delete()) { log.error("Failed to delete directory for deleted object: {}", dir.getAbsolutePath()); } } }
Source:
protected List<String> getInitialRepositories() { List<String> configuredRepos = util.getConfiguredRepositories(); return configuredRepos.stream().map(name -> { File gitDir = new File(name); if (gitDir.exists()) { try { Repository repo = cache.lookupRepository(gitDir); if (ResourcePropertyTester.hasGerritConfiguration(repo)) { return name; } } catch (IOException e) { e.printStackTrace(); return null; } } return null; }).filter(r -> r != null).collect(Collectors.toList()); }

Target:
protected List<String> getInitialRepositories() { List<String> configuredRepos = util.getConfiguredRepositories(); return configuredRepos.stream().map(name -> { File gitDir = new File(name); if (gitDir.exists()) { try { Repository repo = cache.lookupRepository(gitDir); if (repo == null) { return null; } if (ResourcePropertyTester.hasGerritConfiguration(repo)) { return name; } } catch (IOException e) { Activator.logError(e.getMessage(), e); return null; } } return null; }).filter(Objects::nonNull).collect(Collectors.toList()); }
Source:
public <S> void set(final S instance, final T value) { try { if (propertyMetadata.isDeserializable()) { if (propertyMetadata.getSetter() != null) { propertyMetadata.getSetter().invoke(instance, value); } else { propertyMetadata.getField().set(instance, value); } } else if (propertyMetadata.getGetter() != null && value instanceof Collection) { T collection = (T) propertyMetadata.getGetter().invoke(instance); Collection<?> col = ((Collection<?>) collection); if (col != null && col.isEmpty()) { col.addAll((Collection) value); } } } catch (final Exception e) { throw setError(e); } }

Target:
public <S> void set(final S instance, final T value) { try { if (propertyMetadata.isDeserializable()) { if (propertyMetadata.getSetter() != null) { propertyMetadata.getSetter().invoke(instance, value); } else { propertyMetadata.getField().set(instance, value); } } else if (propertyMetadata.isSerializable() && value instanceof Collection) { T collection; if (propertyMetadata.getGetter() != null) { collection = (T) propertyMetadata.getGetter().invoke(instance); } else { collection = (T) propertyMetadata.getField().get(instance); } Collection<?> col = ((Collection<?>) collection); if (col != null && col.isEmpty()) { col.addAll((Collection) value); } } } catch (final Exception e) { throw setError(e); } }
Source:
private static CharSequence generateMarkdown(Context c, String message) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { return trimTrailingWhitespace( Markwon.markdown(c, convertCharacterEncodings(message))); } return trimTrailingWhitespace( new Bypass(c).markdownToSpannable(convertCharacterEncodings(message))); }

Target:
private static CharSequence generateMarkdown(Context c, String message) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { return trimTrailingWhitespace( new Bypass(c).markdownToSpannable(convertCharacterEncodings(message))); } return trimTrailingWhitespace( Markwon.markdown(c, convertCharacterEncodings(message))); }
Source:
public void multiQueuesRotation() throws IOException, InterruptedException { final Queue queueA = this.client.getQueues().get("testA"); final Queue queueB = this.client.getQueues().get("testB"); final Queue queueC = this.client.getQueues().get("testC"); queueA.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); queueA.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); queueB.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); queueC.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); queueC.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); final SerialWorker worker = new SerialWorker( Arrays.asList(new String[] {"testA", "testB", "testC"}), this.client, null, 10); IntegrationTestJob.runningHistory.clear(); final Thread signal = new Thread() { @Override public void run() { try { Thread.sleep(5000); worker.shutDown(); } catch (final InterruptedException v) { System.out.println(v); } } }; signal.start(); worker.run(); assertThat(IntegrationTestJob.runningHistory, contains( "com.moz.qless.IntegrationTestJob.testA", "com.moz.qless.IntegrationTestJob.testB", "com.moz.qless.IntegrationTestJob.testC", "com.moz.qless.IntegrationTestJob.testA", "com.moz.qless.IntegrationTestJob.testC")); }

Target:
public void multiQueuesRotation() throws IOException, InterruptedException { final Queue queueA = this.client.getQueue("testA"); final Queue queueB = this.client.getQueue("testB"); final Queue queueC = this.client.getQueue("testC"); queueA.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); queueA.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); queueB.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); queueC.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); queueC.put(SerialWorkerTest.DEFAULT_JOB_NAME, null, null); final SerialWorker worker = new SerialWorker( Arrays.asList("testA", "testB", "testC"), this.client, null, 10); IntegrationTestJob.runningHistory.clear(); final Thread signal = this.getWorkerThread(worker, 3); signal.start(); worker.run(); assertThat(IntegrationTestJob.runningHistory, contains( "com.moz.qless.IntegrationTestJob.testA", "com.moz.qless.IntegrationTestJob.testB", "com.moz.qless.IntegrationTestJob.testC", "com.moz.qless.IntegrationTestJob.testA", "com.moz.qless.IntegrationTestJob.testC")); }
Source:
public void cleanUp() { MageFrame.removeGame(gameId); saveDividerLocations(); this.gameChatPanel.disconnect(); this.userChatPanel.disconnect(); this.removeListener(); this.handContainer.cleanUp(); this.stackObjects.cleanUp(); for (Map.Entry<UUID, PlayAreaPanel> playAreaPanelEntry : players.entrySet()) { playAreaPanelEntry.getValue().CleanUp(); } this.players.clear(); this.playersWhoLeft.clear(); if (jLayeredPane!= null) { jLayeredPane.remove(abilityPicker); } this.abilityPicker.cleanUp(); if (jLayeredPane != null) { jLayeredPane.remove(DialogManager.getManager(gameId)); } DialogManager.removeGame(gameId); if (pickNumber != null) { pickNumber.removeDialog(); } for (CardInfoWindowDialog exileDialog : exiles.values()) { exileDialog.cleanUp(); exileDialog.removeDialog(); } for (CardInfoWindowDialog graveyardDialog : graveyardWindows.values()) { graveyardDialog.cleanUp(); graveyardDialog.removeDialog(); } for (CardInfoWindowDialog revealDialog : revealed.values()) { revealDialog.cleanUp(); revealDialog.removeDialog(); } for (CardInfoWindowDialog lookedAtDialog : lookedAt.values()) { lookedAtDialog.cleanUp(); lookedAtDialog.removeDialog(); } for (ShowCardsDialog pickTargetDialog : pickTarget) { pickTargetDialog.cleanUp(); pickTargetDialog.removeDialog(); } Plugins.instance.getActionCallback().hideOpenComponents(); try { Component popupContainer = MageFrame.getUI().getComponent(MageComponents.POPUP_CONTAINER); popupContainer.setVisible(false); } catch (InterruptedException ex) { logger.fatal("popupContainer error:", ex); } jPanel2.remove(bigCard); this.bigCard = null; }

Target:
public void cleanUp() { MageFrame.removeGame(gameId); saveDividerLocations(); this.gameChatPanel.disconnect(); this.userChatPanel.disconnect(); this.removeListener(); this.handContainer.cleanUp(); this.stackObjects.cleanUp(); for (Map.Entry<UUID, PlayAreaPanel> playAreaPanelEntry : players.entrySet()) { playAreaPanelEntry.getValue().CleanUp(); } this.players.clear(); this.playersWhoLeft.clear(); if (jLayeredPane!= null) { jLayeredPane.remove(abilityPicker); jLayeredPane.remove(DialogManager.getManager(gameId)); } this.abilityPicker.cleanUp(); DialogManager.removeGame(gameId); if (pickNumber != null) { pickNumber.removeDialog(); } for (CardInfoWindowDialog exileDialog : exiles.values()) { exileDialog.cleanUp(); exileDialog.removeDialog(); } for (CardInfoWindowDialog graveyardDialog : graveyardWindows.values()) { graveyardDialog.cleanUp(); graveyardDialog.removeDialog(); } for (CardInfoWindowDialog revealDialog : revealed.values()) { revealDialog.cleanUp(); revealDialog.removeDialog(); } for (CardInfoWindowDialog lookedAtDialog : lookedAt.values()) { lookedAtDialog.cleanUp(); lookedAtDialog.removeDialog(); } for (ShowCardsDialog pickTargetDialog : pickTarget) { pickTargetDialog.cleanUp(); pickTargetDialog.removeDialog(); } Plugins.instance.getActionCallback().hideOpenComponents(); try { Component popupContainer = MageFrame.getUI().getComponent(MageComponents.POPUP_CONTAINER); popupContainer.setVisible(false); } catch (InterruptedException ex) { logger.fatal("popupContainer error:", ex); } jPanel2.remove(bigCard); this.bigCard = null; }
Source:
private CertificateStatus getStatusFromOcspResponse( OCSPResp ocspResponse, X509Certificate certificate) { try { BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); if (basicResponse == null) { return new UnknownStatus(); } SingleResp[] singleResps = basicResponse.getResponses(); if (singleResps == null) { return new UnknownStatus(); } SingleResp response = Arrays.stream(singleResps) .filter(singleResp -> singleResp.getCertID() != null) .collect(Collectors.toList()) .stream() .filter( singleResp -> singleResp .getCertID() .getSerialNumber() .equals(certificate.getSerialNumber())) .findFirst() .orElse(null); if (response == null) { LOGGER.debug("Certificate status from OCSP response is unknown."); return new UnknownStatus(); } if (response.getCertStatus() == null) { LOGGER.debug("Certificate status from OCSP response is good."); return CertificateStatus.GOOD; } return response.getCertStatus(); } catch (OCSPException e) { return new UnknownStatus(); } }

Target:
private CertificateStatus getStatusFromOcspResponse( OCSPResp ocspResponse, X509Certificate certificate) { try { BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); if (basicResponse == null) { return new UnknownStatus(); } SingleResp[] singleResps = basicResponse.getResponses(); if (singleResps == null) { return new UnknownStatus(); } SingleResp response = Arrays.stream(singleResps) .filter(singleResp -> singleResp.getCertID() != null) .filter( singleResp -> singleResp .getCertID() .getSerialNumber() .equals(certificate.getSerialNumber())) .findFirst() .orElse(null); if (response == null) { LOGGER.debug("Certificate status from OCSP response is unknown."); return new UnknownStatus(); } if (response.getCertStatus() == null) { LOGGER.debug("Certificate status from OCSP response is good."); return CertificateStatus.GOOD; } return response.getCertStatus(); } catch (OCSPException e) { return new UnknownStatus(); } }
Source:
public void action() throws Exception { log("Create an remove an empty local node source with cron policy"); createEmptyNodeSource(EMPTY_NODE_SOURCE_NAME); removeNodeSource(EMPTY_NODE_SOURCE_NAME); log("Create a local node source with " + NODES_NUMBER + " nodes with cron policy"); createNodeSource(NODE_SOURCE_NAME); log("Waiting for the cron policy to remove the nodes"); for (int i = 0; i < NODES_NUMBER; i++) { this.rmHelper.waitForAnyNodeEvent(RMEventType.NODE_REMOVED); } log("Waiting for the cron policy to add the nodes again"); for (int i = 0; i < NODES_NUMBER; i++) { this.rmHelper.waitForAnyNodeEvent(RMEventType.NODE_ADDED); } }

Target:
public void action() throws Exception { log("Create an remove an empty local node source with cron policy"); createEmptyNodeSource(EMPTY_NODE_SOURCE_NAME); removeNodeSource(EMPTY_NODE_SOURCE_NAME); log("Create a local node source with " + NODES_NUMBER + " nodes with cron policy"); createNodeSource(NODE_SOURCE_NAME); log("Waiting for the cron policy to remove the nodes"); repeater.accept(NODES_NUMBER, () -> this.rmHelper.waitForAnyNodeEvent(RMEventType.NODE_REMOVED)); log("Waiting for the cron policy to add the nodes again"); repeater.accept(NODES_NUMBER, () -> this.rmHelper.waitForAnyNodeEvent(RMEventType.NODE_ADDED)); }
Source:
public void commit() throws IOException{ if(LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG,"Before commit: txn=%s",this); if (getSubId() == 0) { switch (state) { case COMMITTED: return; case ROLLEDBACK: throw exceptionFactory.cannotCommit(txnId, state); } synchronized (this) { switch (state) { case COMMITTED: return; case ROLLEDBACK: throw exceptionFactory.cannotCommit(txnId, state); } commitTimestamp = tc.commit(txnId); state = State.COMMITTED; } } else { state = State.COMMITTED; } if(LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG,"After commit: txn=%s,commitTimestamp=%s",this,commitTimestamp); }

Target:
public void commit() throws IOException{ if(LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG,"Before commit: txn=%s",this); if (getSubId() == 0) { switch (state) { case COMMITTED: return; case ROLLEDBACK: throw exceptionFactory.cannotCommit(txnId, state); } synchronized (this) { switch (state) { case COMMITTED: return; case ROLLEDBACK: throw exceptionFactory.cannotCommit(txnId, state); case ACTIVE: commitTimestamp = tc.commit(txnId); state = State.COMMITTED; } } } else { state = State.COMMITTED; } if(LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG,"After commit: txn=%s,commitTimestamp=%s",this,commitTimestamp); }
Source:
private void setTimer(final MessageKey key, int seconds) { if(seconds > 0) { int limit = seconds*1000; new CountDownTimer(limit, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { mMessagesList.remove(key); updateList(); } }.start(); } }

Target:
private void setTimer(final MessageKey key, int seconds) { int limit = seconds*1000; new CountDownTimer(limit, limit) { @Override public void onTick(long millisUntilFinished) @Override public void onFinish() { mMessagesList.remove(key); adapter.notifyDataSetChanged(); } }.start(); }
Source:
private Collection<T> attemptUpdateAsBatch(final Iterable<T> instances) throws OrmException { Collection<T> inserts = null; try { PreparedStatement ps = null; try { int cnt = 0; List<T> allInstances = new ArrayList<>(); for (final T o : instances) { if (ps == null) { ps = schema.getConnection().prepareStatement(getUpdateOneSql()); } bindOneUpdate(ps, o); ps.addBatch(); allInstances.add(o); cnt++; } if (0 < cnt && ps != null) { final int[] states = ps.executeBatch(); if (states == null) { inserts = allInstances; } else { int i = 0; for (T o : allInstances) { if (states.length <= i || states[i] != 1) { if (inserts == null) { inserts = new ArrayList<>(cnt - i); } inserts.add(o); } i++; } } } } finally { if (ps != null) { ps.close(); } } } catch (SQLException e) { throw convertError("update", e); } return inserts; }

Target:
private Collection<T> attemptUpdateAsBatch(final Iterable<T> instances) throws OrmException { Collection<T> inserts = null; try { PreparedStatement ps = null; try { int cnt = 0; List<T> allInstances = new ArrayList<>(); for (final T o : instances) { if (ps == null) { ps = schema.getConnection().prepareStatement(getUpdateOneSql()); } bindOneUpdate(ps, o); ps.addBatch(); allInstances.add(o); cnt++; } if (0 < cnt) { Preconditions.checkNotNull(ps); final int[] states = ps.executeBatch(); if (states == null) { inserts = allInstances; } else { int i = 0; for (T o : allInstances) { if (states.length <= i || states[i] != 1) { if (inserts == null) { inserts = new ArrayList<>(cnt - i); } inserts.add(o); } i++; } } } } finally { if (ps != null) { ps.close(); } } } catch (SQLException e) { throw convertError("update", e); } return inserts; }
Source:
public String[] getFromExpressions(ConversionContext conversionContext) { if ( sourceType == targetType ) { return new String[] { "", "" }; } else { return new String[] { "", "." + sourceType.getName() + "Value()" }; } }

Target:
public ConversionExpression getFromExpressions(ConversionContext conversionContext) { if ( sourceType == targetType ) { return ConversionExpression.empty(); } else { return new ConversionExpression( "", "." + sourceType.getName() + "Value()" ); } }
Source:
public void adsFandomDesktopArticleAds(String article) throws IOException { String testedPage = urlBuilder.getUrlForFandomPage(article); AdsBaseObject wikiPage = new AdsBaseObject(driver, testedPage); getJquery(); wikiPage.verifyFandomDesktopArticleTopLeaderboard(); wikiPage.verifyFandomTopBoxad(); wikiPage.verifyFandomDesktopArticleBottomLeaderboard(); }

Target:
public void adsFandomDesktopArticleAds(String article) { String testedPage = urlBuilder.getUrlForFandomPage(article); AdsFandomObject fandomPage = new AdsFandomObject(driver, testedPage); getJquery(); fandomPage.verifyFandomDesktopArticleTopLeaderboard(); fandomPage.verifyFandomDesktopTopBoxad(); fandomPage.verifyFandomDesktopArticleBottomLeaderboard(); }
Source:
public static ModuleManager create(String masterServerAddress) throws Exception { ModuleManager moduleManager = new ModuleManagerImpl(masterServerAddress); return LoadModuleEnvironment(moduleManager); }

Target:
public static ModuleManager create(String masterServerAddress) throws Exception { ModuleManager moduleManager = new ModuleManagerImpl(masterServerAddress); return loadModuleEnvironment(moduleManager); }
Source:
private DiscoveryClientEndpointLocator discoveryClientEndpointLocator() { if (this.client!=null) { return new DiscoveryClientEndpointLocator(this.client, new EndpointCacheImpl(this.zipkinProperties)); } return null; }

Target:
private DiscoveryClientEndpointLocator discoveryClientEndpointLocator() { if (this.client!=null) { return new DiscoveryClientEndpointLocator(this.client, this.zipkinProperties); } return null; }
Source:
public List<CacheConfigurationChangeListener> getConfigurationChangeListeners() { List<CacheConfigurationChangeListener> configurationChangeListenerList = new ArrayList<CacheConfigurationChangeListener>(); configurationChangeListenerList.addAll(((Store)cachingTier()).getConfigurationChangeListeners()); configurationChangeListenerList.addAll(((Store)authoritativeTier).getConfigurationChangeListeners()); return configurationChangeListenerList; }

Target:
public List<CacheConfigurationChangeListener> getConfigurationChangeListeners() { List<CacheConfigurationChangeListener> configurationChangeListenerList = new ArrayList<CacheConfigurationChangeListener>(); configurationChangeListenerList.addAll(((Store)realCachingTier).getConfigurationChangeListeners()); configurationChangeListenerList.addAll(((Store)authoritativeTier).getConfigurationChangeListeners()); return configurationChangeListenerList; }
Source:
public CalculatorExpressionTokenizer(Context context) { mReplacementMap = new HashMap<>(); NumberFormat nf = DecimalFormat.getInstance( context.getResources().getConfiguration().locale); mReplacementMap.put(".", context.getString(R.string.dec_point)); for (int i = 0; i < 9; ++i) { mReplacementMap.put(String.valueOf(i), nf.format(i)); } mReplacementMap.put("/", context.getString(R.string.op_div)); mReplacementMap.put("*", context.getString(R.string.op_mul)); mReplacementMap.put("-", context.getString(R.string.op_sub)); mReplacementMap.put("cos", context.getString(R.string.fun_cos)); mReplacementMap.put("ln", context.getString(R.string.fun_ln)); mReplacementMap.put("log", context.getString(R.string.fun_log)); mReplacementMap.put("sin", context.getString(R.string.fun_sin)); mReplacementMap.put("tan", context.getString(R.string.fun_tan)); mReplacementMap.put("Infinity", context.getString(R.string.inf)); }

Target:
public CalculatorExpressionTokenizer(Context context) { mReplacementMap = new HashMap<>(); NumberFormat nf = DecimalFormat.getInstance( context.getResources().getConfiguration().locale); mReplacementMap.put(".", context.getString(R.string.dec_point)); for (int i = 0; i <= 9; ++i) { mReplacementMap.put(String.valueOf(i), nf.format(i)); } mReplacementMap.put("/", context.getString(R.string.op_div)); mReplacementMap.put("*", context.getString(R.string.op_mul)); mReplacementMap.put("-", context.getString(R.string.op_sub)); mReplacementMap.put("cos", context.getString(R.string.fun_cos)); mReplacementMap.put("ln", context.getString(R.string.fun_ln)); mReplacementMap.put("log", context.getString(R.string.fun_log)); mReplacementMap.put("sin", context.getString(R.string.fun_sin)); mReplacementMap.put("tan", context.getString(R.string.fun_tan)); mReplacementMap.put("Infinity", context.getString(R.string.inf)); }
Source:
@Test public void provideLazyFails() { @Module class ProvideProvidesModule { @Provides Lazy<Object> provideObject() { return null; } } try { ObjectGraph.create(new ProvideProvidesModule()); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()) .startsWith("@Provides method must not return Lazy directly: ") .endsWith("ProvideLazyModule.provideObject"); } }

Target:
@Test public void provideLazyFails() { @Module class ProvidesLazyModule { @Provides Lazy<Object> provideObject() { return null; } } try { ObjectGraph.create(new ProvidesLazyModule()); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()) .startsWith("@Provides method must not return Lazy directly: ") .endsWith("ProvidesLazyModule.provideObject"); } }
Source:
public JobId submit(Job userJob) throws NotConnectedException, PermissionException, SubmissionClosedException, JobCreationException { try { if (logger.isDebugEnabled()) { logger.debug("New job submission requested : " + userJob.getName()); } if (!schedulingService.isSubmitPossible()) { String msg = "Scheduler is stopped, cannot submit job"; logger.info(msg); throw new SubmissionClosedException(msg); } final UserIdentificationImpl ident = frontendState.checkPermission("submit", YOU_DO_NOT_HAVE_PERMISSION_TO_SUBMIT_A_JOB); final InternalJob job = frontendState.createJob(userJob, ident); pool.submit(() -> { try { schedulingService.submitJob(job); frontendState.jobSubmitted(job, ident); } catch (Exception e) { logger.error(String.format("Error while submiting a job[id:%s] ", job.getId().value()), e); } finally { unregisterSumbittedJob(job.getId()); } }); while (job.getId().longValue() == 0) { try { Thread.sleep(10); } catch (InterruptedException e) { } } registerJobAsUnderSumbission(job.getId()); return job.getId(); } catch (Exception e) { logger.warn("Error when submitting job.", e); throw e; } }

Target:
public JobId submit(Job userJob) throws NotConnectedException, PermissionException, SubmissionClosedException, JobCreationException { try { if (logger.isDebugEnabled()) { logger.debug("New job submission requested : " + userJob.getName()); } if (!schedulingService.isSubmitPossible()) { String msg = "Scheduler is stopped, cannot submit job"; logger.info(msg); throw new SubmissionClosedException(msg); } final UserIdentificationImpl ident = frontendState.checkPermission("submit", YOU_DO_NOT_HAVE_PERMISSION_TO_SUBMIT_A_JOB); final InternalJob job = frontendState.createJob(userJob, ident); final Future<?> submitting = submitJob(userJob, ident, job); return blockUntilJobIdInitialized(userJob, job, submitting); } catch (Exception e) { logger.warn("Error when submitting job.", e); throw e; } }
Source:
public void waitToolbar() { seleniumWebDriverHelper.waitVisibility(By.xpath(" }

Target:
public void waitToolbar() { seleniumWebDriverHelper.waitVisibility(By.xpath(Locators.TOOLBAR_XPATH)); }
Source:
public byte[] getRawHMAC(byte[] inputData) throws SigningException { try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(this.secretKey); byte[] hmacsig = mac.doFinal(inputData); return hmacsig; } catch (Exception e) { throw new SigningException("Failed to generate HMAC signature"); } }

Target:
public byte[] getRawHMAC(byte[] inputData) throws EncryptionException { try { Mac mac = Mac.getInstance(this.algorithm); mac.init(this.secretKey); byte[] hmacsig = mac.doFinal(inputData); return hmacsig; } catch (Exception e) { throw new EncryptionException("Failed to generate HMAC signature", e); } }
Source:
public BasicElementVisitor(String nsUri, String localName) { if (nsUri == null) { nsUri = ""; } if (localName == null) { localName = ""; } this.nsUri = nsUri; this.localName = localName; }

Target:
public BasicElementVisitor(String nsUri, String localName) { if (nsUri == null) { nsUri = ""; } if (localName == null || localName.equals("")) { throw new IllegalArgumentException("LocalName cannot be null"); } this.nsUri = nsUri; this.localName = localName; }
Source:
private static void internalDecrementCount(Map<ResourceProfile, ResourceCounter> primaryMap, ResourceProfile primaryKey, ResourceProfile secondaryKey, int decrement) { primaryMap.computeIfPresent( primaryKey, (resourceProfile, resourceCounter) -> { resourceCounter.decrementCount(secondaryKey, decrement); return resourceCounter.isEmpty() ? null : resourceCounter; }); }

Target:
private static void internalDecrementCount(Map<ResourceProfile, ResourceCounter> primaryMap, ResourceProfile primaryKey, ResourceProfile secondaryKey, int decrement) { primaryMap.compute( primaryKey, (resourceProfile, resourceCounter) -> { Preconditions.checkState(resourceCounter != null, "Attempting to decrement count of %s->%s, but primary key was unknown.", resourceProfile, secondaryKey); resourceCounter.decrementCount(secondaryKey, decrement); return resourceCounter.isEmpty() ? null : resourceCounter; }); }
Source:
public String getDeviceName() { String name = ""; String[] splitedJsonFile = jsonFile.split("_"); if (splitedJsonFile.length > 1){ name = splitedJsonFile[0].substring(0, splitedJsonFile[0].length()); } return name; }

Target:
public String getDeviceName() { String[] splitedJsonFile = jsonFile.split("_"); if (splitedJsonFile.length > 1){ return splitedJsonFile[0]; } else { return jsonFile.substring(0,jsonFile.lastIndexOf(".json")); } }
Source:
private void storageDomain_SelectedItemChanged() { if (getStorageDomain().getSelectedItem() != null) { updateVolumeType(((StorageDomain)getStorageDomain().getSelectedItem()).getStorageType()); } updateQuota((StoragePool) getDataCenter().getSelectedItem()); }

Target:
private void storageDomain_SelectedItemChanged() { StorageDomain selectedStorage = (StorageDomain) getStorageDomain().getSelectedItem(); if (selectedStorage != null) { updateVolumeType(selectedStorage.getStorageType()); } updateQuota((StoragePool) getDataCenter().getSelectedItem()); }
Source:
public void validate(final UsernamePasswordCredentials credentials) { final String ticketGrantingTicketId = requestTicketGrantingTicket(credentials.getUsername(), credentials.getPassword()); final HttpTGTProfile profile = new HttpTGTProfile(ticketGrantingTicketId); credentials.setUserProfile(profile); }

Target:
public void validate(final UsernamePasswordCredentials credentials) { if (credentials == null || credentials.getPassword() == null || credentials.getUsername() == null) { throw new TechnicalException("Credentials are required"); } final String ticketGrantingTicketId = requestTicketGrantingTicket(credentials.getUsername(), credentials.getPassword()); final HttpTGTProfile profile = new HttpTGTProfile(ticketGrantingTicketId, credentials.getUsername()); credentials.setUserProfile(profile); }
Source:
public static <K, V> ExpiryPolicyBuilder<K, V> expiry() { return new ExpiryPolicyBuilder<>(); }

Target:
public static ExpiryPolicyBuilder<Object, Object> expiry() { return new ExpiryPolicyBuilder<>(); }
Source:
public void populate(final World world, final Random random, Chunk source) { if (random.nextInt(100) < 10) { final int x = 4 + random.nextInt(8) + source.getX() * 16; final int z = 4 + random.nextInt(8) + source.getZ() * 16; int maxY = world.getHighestBlockYAt(x, z); if (maxY < 16) { maxY = 32; } final int y = random.nextInt(maxY); new Thread() { @Override public void run() { Set<Location> snake = startSnake(world, random, x, y, z); if (random.nextInt(16) > 5) { if (y > 36) { snake = startSnake(world, random, x, y / 2, z); } else if (y < 24) { snake = startSnake(world, random, x, y * 2, z); } } } } .start(); } }

Target:
public void populate(final World world, final Random random, Chunk source) { if (random.nextInt(100) < 10) { final int x = 4 + random.nextInt(8) + source.getX() * 16; final int z = 4 + random.nextInt(8) + source.getZ() * 16; int maxY = world.getHighestBlockYAt(x, z); if (maxY < 16) { maxY = 32; } final int y = random.nextInt(maxY); Thread t = new Thread() { @Override public void run() { Set<Location> snake = startSnake(world, random, x, y, z); if (random.nextInt(16) > 5) { if (y > 36) { snake = startSnake(world, random, x, y / 2, z); } else if (y < 24) { snake = startSnake(world, random, x, y * 2, z); } } } }; t.start(); } }
Source:
public ResponseEntity<ResourceSupport> deleteAdminGroup(@PathVariable UUID uuid, HttpServletResponse response, HttpServletRequest request) throws SQLException, AuthorizeException, IOException { Context context = ContextUtil.obtainContext(request); Community community = communityService.find(context, uuid); if (community == null) { throw new ResourceNotFoundException("No such community: " + uuid); } if (!authorizeService.isAdmin(context) && !authorizeService.authorizeActionBoolean(context, community, Constants.ADMIN, true)) { throw new AccessDeniedException("The current user was not allowed to retrieve the AdminGroup for" + " community: " + uuid); } if (community.getAdministrators() == null) { throw new UnprocessableEntityException("The community with UUID: " + uuid + " doesn't have an admin " + "group"); } communityRestRepository.deleteAdminGroup(context, community); context.complete(); return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT); }

Target:
public ResponseEntity<ResourceSupport> deleteAdminGroup(@PathVariable UUID uuid, HttpServletResponse response, HttpServletRequest request) throws SQLException, AuthorizeException, IOException { Context context = ContextUtil.obtainContext(request); Community community = communityService.find(context, uuid); if (community == null) { throw new ResourceNotFoundException("No such community: " + uuid); } AuthorizeUtil.authorizeManageAdminGroup(context, community); if (community.getAdministrators() == null) { throw new UnprocessableEntityException("The community with UUID: " + uuid + " doesn't have an admin " + "group"); } communityRestRepository.deleteAdminGroup(context, community); context.complete(); return ControllerUtils.toEmptyResponse(HttpStatus.NO_CONTENT); }
Source:
public boolean isTopicThroughput() { return counterName.startsWith("throughput.") && metricParts == TOPIC_METRICS_PARTS; }

Target:
public boolean isTopicThroughput() { return metricParts == TOPIC_METRICS_PARTS && counterName.startsWith("throughput."); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{ id: "); sb.append(this.getid()); sb.append(", connection: "); sb.append(this.getconnection()); sb.append(", iqn: "); sb.append(this.getiqn()); sb.append(", vfsType: "); sb.append(this.getVfsType()); sb.append(", mountOptions: "); sb.append(this.getMountOptions()); sb.append(", nfsVersion: "); sb.append(this.getNfsVersion()); sb.append(", nfsRetrans: "); sb.append(this.getNfsRetrans()); sb.append(", nfsTimeo: "); sb.append(this.getNfsTimeo()); if (this.getIface() != null) { sb.append(", iface: "); sb.append(this.getIface()); } if (getNetIfaceName() != null) { sb.append(", netIfacename: "); sb.append(this.getNetIfaceName()); } sb.append(" };"); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{ id: "); sb.append(this.getid()); sb.append(", connection: "); sb.append(this.getconnection()); sb.append(", iqn: "); sb.append(this.getiqn()); sb.append(", vfsType: "); sb.append(this.getVfsType()); sb.append(", mountOptions: "); sb.append(this.getMountOptions()); sb.append(", nfsVersion: "); sb.append(this.getNfsVersion()); sb.append(", nfsRetrans: "); sb.append(this.getNfsRetrans()); sb.append(", nfsTimeo: "); sb.append(this.getNfsTimeo()); if (this.getIface() != null) { sb.append(", iface: "); sb.append(this.getIface()); } if (getNetIfaceName() != null) { sb.append(", netIfaceName: "); sb.append(this.getNetIfaceName()); } sb.append(" };"); return sb.toString(); }
Source:
public PortableInfoboxPageObject clickInternalLinkWithIndex(int index) { wait.forElementVisible(internalLink.get(index)); scrollToElement(internalLink.get(index)); internalLink.get(index).click(); return this; }

Target:
public PortableInfoboxPageObject clickInternalLinkWithIndex(int index) { return clickLink(internalLinks.get(index)); }
Source:
public String handleRequest(Model model, HttpServletRequest request){ if (request.getQueryString() == null || request.getQueryString().length() == 0){ AccessGroupSet accessGroups = GroupsThreadStore.getGroups(); SearchResultResponse collectionResultResponse = queryLayer.getCollectionList(accessGroups); model.addAttribute("collectionList", collectionResultResponse.getResultList()); SearchResultResponse departmentFieldObject = queryLayer.getDepartmentList(accessGroups, null); model.addAttribute("departmentList", departmentFieldObject); model.addAttribute("pageSubtitle", "Advanced Search"); model.addAttribute("formatMap", LookupMappingsSettings.getMapping("advancedFormats")); return "advancedSearch"; } SearchState searchState = searchStateFactory.createSearchStateAdvancedSearch(request.getParameterMap()); String container = request.getParameter("container"); request.getSession().setAttribute("searchState", searchState); model.addAllAttributes(SearchStateUtil.generateStateParameters(searchState)); return "redirect:/search" + ((container != null && container.length() > 0)? '/' + container : ""); }

Target:
public String handleRequest(Model model, HttpServletRequest request){ if (request.getQueryString() == null || request.getQueryString().length() == 0){ AccessGroupSet accessGroups = GroupsThreadStore.getGroups(); SearchResultResponse collectionResultResponse = queryLayer.getCollectionList(accessGroups); model.addAttribute("collectionList", collectionResultResponse.getResultList()); SearchResultResponse departmentFieldObject = queryLayer.getDepartmentList(accessGroups, null); model.addAttribute("departmentList", departmentFieldObject.getFacetFields().get(0)); model.addAttribute("pageSubtitle", "Advanced Search"); model.addAttribute("formatMap", LookupMappingsSettings.getMapping("advancedFormats")); return "advancedSearch"; } SearchState searchState = searchStateFactory.createSearchStateAdvancedSearch(request.getParameterMap()); String container = request.getParameter("container"); request.getSession().setAttribute("searchState", searchState); model.addAllAttributes(SearchStateUtil.generateStateParameters(searchState)); return "redirect:/search" + ((container != null && container.length() > 0)? '/' + container : ""); }
Source:
public void init() { registerBeanDefinitionParser("publish-subscribe-channel", new RedisChannelParser()); registerBeanDefinitionParser("inbound-channel-adapter", new RedisInboundChannelAdapterParser()); registerBeanDefinitionParser("store-inbound-channel-adapter", new RedisStoreInboundChannelAdapterParser()); registerBeanDefinitionParser("store-outbound-channel-adapter", new RedisStoreOutboundChannelAdapterParser()); registerBeanDefinitionParser("outbound-channel-adapter", new RedisOutboundChannelAdapterParser()); registerBeanDefinitionParser("message-driven-channel-adapter", new RedisMessageDrivenEndpointParser()); registerBeanDefinitionParser("queue-outbound-channel-adapter", new RedisQueueOutboundChannelAdapterParser()); }

Target:
public void init() { registerBeanDefinitionParser("publish-subscribe-channel", new RedisChannelParser()); registerBeanDefinitionParser("inbound-channel-adapter", new RedisInboundChannelAdapterParser()); registerBeanDefinitionParser("store-inbound-channel-adapter", new RedisStoreInboundChannelAdapterParser()); registerBeanDefinitionParser("store-outbound-channel-adapter", new RedisStoreOutboundChannelAdapterParser()); registerBeanDefinitionParser("outbound-channel-adapter", new RedisOutboundChannelAdapterParser()); registerBeanDefinitionParser("queue-inbound-channel-adapter", new RedisQueueInboundChannelAdapterParser()); registerBeanDefinitionParser("queue-outbound-channel-adapter", new RedisQueueOutboundChannelAdapterParser()); }
Source:
public T bucket(String name) { if (name == null) { throw new IllegalArgumentException("null bucket name"); } if (name.length() < 3 || name.length() > 63) { throw new IllegalArgumentException( name + " : " + "bucket name must be at least 3 and no more than 63 characters long"); } if (name.contains("..")) { String msg = "bucket name cannot contain successive periods. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } if (!name.matches("^[a-z0-9][a-z0-9\\.\\-]+[a-z0-9]$")) { String msg = "bucket name does not follow Amazon S3 standards. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } this.name = name; return (T) this; }

Target:
public T bucket(String name) { validateName(name); this.name = name; return (T) this; }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_CANCELED) { return; } switch (requestCode) { case AdCreationDialog.CAMERA_REQUEST: if (resultCode == Activity.RESULT_OK) { } break; case AdCreationDialog.PICK_IMAGE: if(resultCode == Activity.RESULT_OK){ Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query( selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String filePath = cursor.getString(columnIndex); cursor.close(); mApp.setFileUri(Uri.parse(filePath)); } break; } Bitmap currBitmap = Utility.retrieveBitmap(mApp.getFileUri(), mApp.AD_WIDTH, mApp.AD_HEIGHT); mApp.initAdCreationManager(currBitmap, mApp.getFileUri()); mApp.getAdCreationManager().nextStage(this, mApp.getAdCreationManager().getCurrentBitmap()); }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_CANCELED) { return; } switch (requestCode) { case AdCreationDialog.CAMERA_REQUEST: if (resultCode == Activity.RESULT_OK) { } break; case AdCreationDialog.PICK_IMAGE: if(resultCode == Activity.RESULT_OK){ Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query( selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String filePath = cursor.getString(columnIndex); cursor.close(); mApp.setFileUri(Uri.parse(filePath)); } break; } Bitmap currBitmap = Utility.retrieveBitmap(mApp.getFileUri(), AdCreationManager.AD_WIDTH, AdCreationManager.AD_HEIGHT); mApp.initAdCreationManager(currBitmap, mApp.getFileUri()); mApp.getAdCreationManager().nextStage(this, mApp.getAdCreationManager().getCurrentBitmap()); }
Source:
public void testReadingHierarchy() throws Exception { Workpiece workpiece = MetsService.getInstance() .load(new FileInputStream(new File("../Kitodo-DataFormat/src/test/resources/between.xml")), args -> { try { return new FileInputStream( new File("../Kitodo-DataFormat/src/test/resources/" + args.getLeft().getPath())); } catch (FileNotFoundException e) { throw new UncheckedIOException(e); } }); ExistingOrLinkedStructure downlink = workpiece.getStructure().getChildren().get(0); assertTrue(downlink.isLinked()); assertEquals("Leaf METS file", downlink.getLabel()); assertEquals(BigInteger.valueOf(1), ((LinkedStructure) downlink).getOrder()); assertEquals("leaf", downlink.getType()); assertEquals("leaf.xml", ((LinkedStructure) downlink).getUri().getPath()); List<LinkedStructure> uplinks = workpiece.getUplinks(); assertEquals(2, uplinks.size()); LinkedStructure top = uplinks.get(0); assertEquals("Top METS file", top.getLabel()); assertEquals(null, top.getOrder()); assertEquals("top", top.getType()); assertEquals("top.xml", top.getUri().getPath()); LinkedStructure second = uplinks.get(1); assertEquals("My branch", second.getLabel()); assertEquals(BigInteger.valueOf(10), second.getOrder()); assertEquals("two", second.getType()); assertEquals("top.xml", second.getUri().getPath()); }

Target:
public void testReadingHierarchy() throws Exception { Workpiece workpiece = MetsService.getInstance() .load(Files.newInputStream(Paths.get("../Kitodo-DataFormat/src/test/resources/between.xml")), (uri, couldHaveToBeWrittenInTheFuture) -> { try { return Files.newInputStream( Paths.get("../Kitodo-DataFormat/src/test/resources/" + uri.getPath())); } catch (IOException e) { throw new UncheckedIOException(e); } }); StructuralElement downlink = workpiece.getRootElement().getChildren().get(0); assertTrue(downlink.isLinked()); assertEquals("Leaf METS file", downlink.getLabel()); assertEquals(BigInteger.valueOf(1), ((LinkedStructuralElement) downlink).getOrder()); assertEquals("leaf", downlink.getType()); assertEquals("leaf.xml", ((LinkedStructuralElement) downlink).getUri().getPath()); List<LinkedStructuralElement> uplinks = workpiece.getUplinks(); assertEquals(2, uplinks.size()); LinkedStructuralElement top = uplinks.get(0); assertEquals("Top METS file", top.getLabel()); assertEquals(null, top.getOrder()); assertEquals("top", top.getType()); assertEquals("top.xml", top.getUri().getPath()); LinkedStructuralElement second = uplinks.get(1); assertEquals("My branch", second.getLabel()); assertEquals(BigInteger.valueOf(10), second.getOrder()); assertEquals("two", second.getType()); assertEquals("top.xml", second.getUri().getPath()); }
Source:
public void testDeleteFileUnauthorized() throws Exception { final AzureBlobFileSystem fs = this.getFileSystem(); Path testFilePath = new Path( TEST_WRITE_THEN_READ_ONLY_PATH_PREFIX + name.getMethodName()); ((MockAbfsAuthorizer) fs.getAbfsStore().getAuthorizer()) .setwriteThenReadOnly(testFilePath.getName(), WriteReadMode.WRITE_MODE); fs.create(testFilePath).close(); ((MockAbfsAuthorizer) fs.getAbfsStore().getAuthorizer()) .setwriteThenReadOnly(testFilePath.getName(), WriteReadMode.READ_MODE); intercept(AbfsAuthorizationException.class, () -> { fs.delete(testFilePath, false); }); }

Target:
public void testDeleteFileUnauthorized() throws Exception { runTest(FileSystemOperations.DeletePath, true); }
Source:
public Response clearAllParagraphOutput(@PathParam("noteId") String noteId) throws IOException { LOG.info("clear all paragraph output of note {}", noteId); if (!noteId.isEmpty()) { Note note = notebook.getNote(noteId); if (note == null) { return new JsonResponse(Status.NOT_FOUND, "note not found.").build(); } note.clearAllParagraphOutput(); } return new JsonResponse(Status.OK, "").build(); }

Target:
public Response clearAllParagraphOutput(@PathParam("noteId") String noteId) throws IOException { LOG.info("clear all paragraph output of note {}", noteId); checkIfUserCanWrite(noteId, "Insufficient privileges you cannot clear this note"); Note note = notebook.getNote(noteId); checkIfNoteIsNotNull(note); note.clearAllParagraphOutput(); return new JsonResponse(Status.OK, "").build(); }
Source:
private String subdomainToLower(String url, EditText mHostUrlInput) { if(url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) { if(url.indexOf("/", 8) != -1) url = url.substring(0, url.indexOf("/", 8)).toLowerCase() + url.substring(url.indexOf("/", 8), url.length()); else url = url.substring(0, url.length()).toLowerCase(); mHostUrlInput.setText(url); } else { if(url.indexOf("/") != -1) url = url.substring(0, url.indexOf("/")).toLowerCase() + url.substring(url.indexOf("/", 8), url.length()); else url = url.substring(0, url.length()).toLowerCase(); mHostUrlInput.setText(url); } return url; }

Target:
private String subdomainToLower(String url, EditText mHostUrlInput) { if(url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) { if(url.indexOf("/", 8) != -1) url = url.substring(0, url.indexOf("/", 8)).toLowerCase() + url.substring(url.indexOf("/", 8), url.length()); else url = url.substring(0, url.length()).toLowerCase(); mHostUrlInput.setText(url); } else { if(url.indexOf("/") != -1) url = url.substring(0, url.indexOf("/")).toLowerCase() + url.substring(url.indexOf("/"), url.length()); else url = url.substring(0, url.length()).toLowerCase(); mHostUrlInput.setText(url); } return url; }
Source:
public List<Event> removeEventBeforeSignificant(final List<Event> events){ final Optional<Event> significantEvent = getFirstSignificantEvent(events); if (!significantEvent.isPresent()) { return events; } final List<Event> filteredEvents = new ArrayList<>(); for(final Event event:events){ if(event.getStartTimestamp() < significantEvent.get().getStartTimestamp()){ if (event.getType() == Event.Type.LIGHTS_OUT) { final Long timeDiff = significantEvent.get().getStartTimestamp() - event.getStartTimestamp(); if (timeDiff < FILTER_NON_SIGNIFICANT_EVENT_IN_MILLIS) filteredEvents.add(event); } continue; } filteredEvents.add(event); } return filteredEvents; }

Target:
public List<Event> removeEventBeforeSignificant(final List<Event> events){ final Optional<Event> significantEvent = getFirstSignificantEvent(events); if (!significantEvent.isPresent()) { return events; } final List<Event> filteredEvents = Lists.newArrayList(); for(final Event event:events){ if(event.getStartTimestamp() < significantEvent.get().getStartTimestamp()){ if (Event.Type.LIGHTS_OUT.equals(event.getType())) { final Long timeDiff = significantEvent.get().getStartTimestamp() - event.getStartTimestamp(); if (timeDiff < FILTER_NON_SIGNIFICANT_EVENT_IN_MILLIS) filteredEvents.add(event); } continue; } filteredEvents.add(event); } return filteredEvents; }
Source:
public void run() { if (dTreeViewer != null && dTreeViewer.getControl() != null && !dTreeViewer.getControl().isDisposed()) { for (Object itemtoExpand : toExpand) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CHANGE_SWT_LINE_COLAPSE_STATE_KEY); dTreeViewer.setExpandedState(itemtoExpand, true); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CHANGE_SWT_LINE_COLAPSE_STATE_KEY); } for (Object itemToCollapse : toCollapse) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CHANGE_SWT_LINE_COLAPSE_STATE_KEY); dTreeViewer.setExpandedState(itemToCollapse, false); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CHANGE_SWT_LINE_COLAPSE_STATE_KEY); } for (Object itemToRefresh : toRefreshInViewer) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.REFRESH_SWT_LINE_KEY); dTreeViewer.refresh(itemToRefresh, true); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.REFRESH_SWT_LINE_KEY); } DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.UPDATE_SWT_LINE_KEY); dTreeViewer.update(objectsToUpdateInViewer, null); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.UPDATE_SWT_LINE_KEY); } }

Target:
public void run() { if (dTreeViewer != null && dTreeViewer.getControl() != null && !dTreeViewer.getControl().isDisposed()) { for (Object itemtoExpand : toExpand) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CHANGE_SWT_LINE_COLLAPSE_STATE_KEY); dTreeViewer.setExpandedState(itemtoExpand, true); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CHANGE_SWT_LINE_COLLAPSE_STATE_KEY); } for (Object itemToCollapse : toCollapse) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.CHANGE_SWT_LINE_COLLAPSE_STATE_KEY); dTreeViewer.setExpandedState(itemToCollapse, false); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.CHANGE_SWT_LINE_COLLAPSE_STATE_KEY); } for (Object itemToRefresh : toRefreshInViewer) { DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.REFRESH_SWT_LINE_KEY); dTreeViewer.refresh(itemToRefresh, true); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.REFRESH_SWT_LINE_KEY); } DslCommonPlugin.PROFILER.startWork(SiriusTasksKey.UPDATE_SWT_LINE_KEY); dTreeViewer.update(objectsToUpdateInViewer, null); DslCommonPlugin.PROFILER.stopWork(SiriusTasksKey.UPDATE_SWT_LINE_KEY); } }