Example usage for java.util.concurrent Future isCancelled

List of usage examples for java.util.concurrent Future isCancelled

Introduction

In this page you can find the example usage for java.util.concurrent Future isCancelled.

Prototype

boolean isCancelled();

Source Link

Document

Returns true if this task was cancelled before it completed normally.

Usage

From source file:org.elasticsearch.client.sniff.SnifferTests.java

public void testTaskCancelling() throws Exception {
    RestClient restClient = mock(RestClient.class);
    HostsSniffer hostsSniffer = mock(HostsSniffer.class);
    Scheduler noOpScheduler = new Scheduler() {
        @Override/*from   w w w  .  j a v a 2 s  . c om*/
        public Future<?> schedule(Sniffer.Task task, long delayMillis) {
            return null;
        }

        @Override
        public void shutdown() {
        }
    };
    Sniffer sniffer = new Sniffer(restClient, hostsSniffer, noOpScheduler, 0L, 0L);
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    try {
        int numIters = randomIntBetween(50, 100);
        for (int i = 0; i < numIters; i++) {
            Sniffer.Task task = sniffer.new Task(0L);
            TaskWrapper wrapper = new TaskWrapper(task);
            Future<?> future;
            if (rarely()) {
                future = executor.schedule(wrapper, randomLongBetween(0L, 200L), TimeUnit.MILLISECONDS);
            } else {
                future = executor.submit(wrapper);
            }
            Sniffer.ScheduledTask scheduledTask = new Sniffer.ScheduledTask(task, future);
            boolean skip = scheduledTask.skip();
            try {
                assertNull(future.get());
            } catch (CancellationException ignore) {
                assertTrue(future.isCancelled());
            }

            if (skip) {
                //the task was either cancelled before starting, in which case it will never start (thanks to Future#cancel),
                //or skipped, in which case it will run but do nothing (thanks to Task#skip).
                //Here we want to make sure that whenever skip returns true, the task either won't run or it won't do anything,
                //otherwise we may end up with parallel sniffing tracks given that each task schedules the following one. We need to
                // make sure that onFailure takes scheduling over while at the same time ordinary rounds don't go on.
                assertFalse(task.hasStarted());
                assertTrue(task.isSkipped());
                assertTrue(future.isCancelled());
                assertTrue(future.isDone());
            } else {
                //if a future is cancelled when its execution has already started, future#get throws CancellationException before
                //completion. The execution continues though so we use a latch to try and wait for the task to be completed.
                //Here we want to make sure that whenever skip returns false, the task will be completed, otherwise we may be
                //missing to schedule the following round, which means no sniffing will ever happen again besides on failure sniffing.
                assertTrue(wrapper.await());
                //the future may or may not be cancelled but the task has for sure started and completed
                assertTrue(task.toString(), task.hasStarted());
                assertFalse(task.isSkipped());
                assertTrue(future.isDone());
            }
            //subsequent cancel calls return false for sure
            int cancelCalls = randomIntBetween(1, 10);
            for (int j = 0; j < cancelCalls; j++) {
                assertFalse(scheduledTask.skip());
            }
        }
    } finally {
        executor.shutdown();
        executor.awaitTermination(1000, TimeUnit.MILLISECONDS);
    }
}

From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java

/**
 * Used by batch import and export to wait for queued tasks to complete. Handles fail-fast behavior
 * if any of the tasks threw and exception by canceling all queued futures and logging a summary of
 * the failures. All completed futures are removed from the queue.
 *
 * @param futures Queued futures to check for completeness
 * @param wait If true it will wait for all futures to complete, if false only check for completed futures
 * @return a list of futures that either threw exceptions or timed out
 *//*ww w .java  2 s.  c o m*/
protected List<FutureHolder<?>> waitForFutures(final Queue<? extends FutureHolder<?>> futures,
        final PrintWriter reportWriter, final File reportDirectory, final boolean wait)
        throws InterruptedException {

    final List<FutureHolder<?>> failedFutures = new LinkedList<FutureHolder<?>>();

    for (Iterator<? extends FutureHolder<?>> futuresItr = futures.iterator(); futuresItr.hasNext();) {
        final FutureHolder<?> futureHolder = futuresItr.next();

        //If waiting, or if not waiting but the future is already done do the get
        final Future<?> future = futureHolder.getFuture();
        if (wait || (!wait && future.isDone())) {
            futuresItr.remove();

            try {
                //Don't bother doing a get() on canceled futures
                if (!future.isCancelled()) {
                    if (this.maxWait > 0) {
                        future.get(this.maxWait, this.maxWaitTimeUnit);
                    } else {
                        future.get();
                    }

                    reportWriter.printf(REPORT_FORMAT, "SUCCESS", futureHolder.getDescription(),
                            futureHolder.getExecutionTimeMillis());
                }
            } catch (CancellationException e) {
                //Ignore cancellation exceptions
            } catch (ExecutionException e) {
                logger.error("Failed: " + futureHolder);

                futureHolder.setError(e);
                failedFutures.add(futureHolder);
                reportWriter.printf(REPORT_FORMAT, "FAIL", futureHolder.getDescription(),
                        futureHolder.getExecutionTimeMillis());

                try {
                    final String dataReportName = SafeFilenameUtils.makeSafeFilename(
                            futureHolder.getDataType() + "_" + futureHolder.getDataName() + ".txt");
                    final File dataReportFile = new File(reportDirectory, dataReportName);
                    final PrintWriter dataReportWriter = new PrintWriter(
                            new BufferedWriter(new FileWriter(dataReportFile)));
                    try {
                        dataReportWriter.println(
                                "FAIL: " + futureHolder.getDataType() + " - " + futureHolder.getDataName());
                        dataReportWriter.println(
                                "--------------------------------------------------------------------------------");
                        e.getCause().printStackTrace(dataReportWriter);
                    } finally {
                        IOUtils.closeQuietly(dataReportWriter);
                    }
                } catch (Exception re) {
                    logger.warn("Failed to write error report for failed " + futureHolder
                            + ", logging root failure here", e.getCause());
                }
            } catch (TimeoutException e) {
                logger.warn("Failed: " + futureHolder);

                futureHolder.setError(e);
                failedFutures.add(futureHolder);
                future.cancel(true);
                reportWriter.printf(REPORT_FORMAT, "TIMEOUT", futureHolder.getDescription(),
                        futureHolder.getExecutionTimeMillis());
            }
        }
    }

    return failedFutures;
}

From source file:org.apache.gobblin.scheduler.JobScheduler.java

/**
 * Schedule a job immediately./*from  ww w.  ja  v a  2 s.  co m*/
 *
 * <p>
 *   This method calls the Quartz scheduler to scheduler the job.
 * </p>
 *
 * @param jobProps Job configuration properties
 * @param jobListener {@link JobListener} used for callback,
 *                    can be <em>null</em> if no callback is needed.
 * @throws JobException when there is anything wrong
 *                      with scheduling the job
 */
public Future<?> scheduleJobImmediately(Properties jobProps, JobListener jobListener, JobLauncher jobLauncher) {
    Callable<Void> callable = new Callable<Void>() {
        @Override
        public Void call() throws JobException {
            try {
                runJob(jobProps, jobListener, jobLauncher);
            } catch (JobException je) {
                LOG.error("Failed to run job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), je);
                throw je;
            }
            return null;
        }
    };

    final Future<?> future = this.jobExecutor.submit(callable);
    return new Future() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (!cancelRequested) {
                return false;
            }
            boolean result = true;
            try {
                jobLauncher.cancelJob(jobListener);
            } catch (JobException e) {
                LOG.error("Failed to cancel job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), e);
                result = false;
            }
            if (mayInterruptIfRunning) {
                result &= future.cancel(true);
            }
            return result;
        }

        @Override
        public boolean isCancelled() {
            return future.isCancelled();
        }

        @Override
        public boolean isDone() {
            return future.isDone();
        }

        @Override
        public Object get() throws InterruptedException, ExecutionException {
            return future.get();
        }

        @Override
        public Object get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return future.get(timeout, unit);
        }
    };
}

From source file:com.mobilyzer.MeasurementScheduler.java

private void uploadResults() {
    Vector<MeasurementResult> finishedTasks = new Vector<MeasurementResult>();
    MeasurementResult[] results;/*w w  w  . j a  v  a 2  s  .c  o m*/
    Future<MeasurementResult[]> future;
    Logger.d("pendingTasks: " + pendingTasks.size());
    synchronized (this.pendingTasks) {
        try {
            for (MeasurementTask task : this.pendingTasks.keySet()) {
                future = this.pendingTasks.get(task);
                if (future != null) {
                    if (future.isDone()) {
                        this.pendingTasks.remove(task);
                        if (future.isCancelled()) {
                            Logger.e("Task execution was canceled");
                            results = MeasurementResult.getFailureResult(task,
                                    new CancellationException("Task cancelled"));
                            for (MeasurementResult r : results) {
                                finishedTasks.add(r);
                            }
                        }
                    }
                }
            }
        } catch (ConcurrentModificationException e) {
            /*
             * keySet is a synchronized view of the keys. However, changes during iteration will throw
             * ConcurrentModificationException. Since we have synchronized all changes to pendingTasks
             * this should not happen.
             */
            Logger.e("Pending tasks is changed during measurement upload");
        }
    }
    Logger.i("A total of " + finishedTasks.size() + " from pendingTasks is uploaded");
    Logger.i("A total of " + this.pendingTasks.size() + " is in pendingTasks");

    try {
        for (MeasurementResult r : finishedTasks) {
            r.getMeasurementDesc().parameters = null;
        }
        this.checkin.uploadMeasurementResult(finishedTasks, resourceCapManager);
    } catch (IOException e) {
        Logger.e("Error when uploading message");
    }
}

From source file:de.hopmann.msc.slave.service.PackageInstallationBean.java

public Future<InstallationContext> acquireInstallation(PackageResolved packageResolved,
        PackageInstallerHolder packageInstallerHolder) throws PackageNotFoundException {
    // TODO exception, close context to rollback on error

    final InstallationContext context = new InstallationContext();

    final Future<PackageInstallationEntity> installationFuture = acquireInstallation(packageResolved,
            packageInstallerHolder, context);

    return new Future<InstallationContext>() {

        @Override//from  w w  w.  j  a  va2s  .  c o m
        public boolean cancel(boolean mayInterruptIfRunning) {
            boolean cancelled = installationFuture.cancel(mayInterruptIfRunning);
            try {
                // Close installation context to release resources
                context.close();
            } catch (Exception e) {
                log.log(Level.WARNING, "Could not close installation context", e);
            }
            return cancelled;
        }

        @Override
        public InstallationContext get() throws InterruptedException, ExecutionException {
            context.setInstallation(installationFuture.get());
            return context;
        }

        @Override
        public InstallationContext get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            context.setInstallation(installationFuture.get(timeout, unit));
            return context;
        }

        @Override
        public boolean isCancelled() {
            return installationFuture.isCancelled();
        }

        @Override
        public boolean isDone() {
            return installationFuture.isDone();
        }
    };

}

From source file:com.mobiperf.MeasurementScheduler.java

@SuppressWarnings("unchecked")
private void uploadResults() {
    MeasurementResult result;/*from ww  w  .j a v  a2  s . c  om*/
    Future<MeasurementResult> future;
    JSONArray results = readResultsFromFile();

    synchronized (this.pendingTasks) {
        try {
            for (MeasurementTask task : this.pendingTasks.keySet()) {
                future = this.pendingTasks.get(task);
                if (future != null) {
                    sendStringMsg("Finished:\n" + task);
                    if (future.isDone()) {
                        try {
                            this.pendingTasks.remove(task);

                            if (!future.isCancelled()) {
                                result = future.get();
                            } else {
                                Logger.e("Task execution was canceled");
                                JSONObject cancelledResult = MeasurementJsonConvertor.encodeToJson(this
                                        .getFailureResult(task, new CancellationException("Task cancelled")));
                                results.put(cancelledResult);
                            }

                        } catch (InterruptedException e) {
                            Logger.e("Task execution interrupted", e);
                        } catch (ExecutionException e) {
                            if (e.getCause() instanceof MeasurementSkippedException) {
                                // Don't do anything with this - no need to report skipped measurements
                                sendStringMsg("Task skipped - " + e.getCause().toString() + "\n" + task);
                                Logger.i("Task skipped", e.getCause());
                            } else {
                                // Log the error
                                sendStringMsg("Task failed - " + e.getCause().toString() + "\n" + task);
                                Logger.e("Task execution failed", e.getCause());
                                // Was already sent
                                // finishedTasks.add(this.getFailureResult(task, e.getCause()));
                            }
                        } catch (CancellationException e) {
                            Logger.e("Task cancelled", e);
                        }
                    } else if (task.isPassedDeadline()) {
                        /*
                         * If a task has reached its deadline but has not been run, remove it and report
                         * failure
                         */
                        this.pendingTasks.remove(task);
                        future.cancel(true);
                        JSONObject cancelledResult = MeasurementJsonConvertor
                                .encodeToJson(this.getFailureResult(task,
                                        new RuntimeException("Deadline passed before execution")));
                        results.put(cancelledResult);
                    }
                }

                if (future == null) {
                    /*
                     * Tasks that are scheduled after deadline are put into pendingTasks with a null future.
                     */
                    this.pendingTasks.remove(task);
                    JSONObject cancelledResult = MeasurementJsonConvertor.encodeToJson(
                            this.getFailureResult(task, new RuntimeException("Task scheduled after deadline")));
                    results.put(cancelledResult);
                }
            }
        } catch (ConcurrentModificationException e) {
            /*
             * keySet is a synchronized view of the keys. However, changes during iteration will throw
             * ConcurrentModificationException. Since we have synchronized all changes to pendingTasks
             * this should not happen.
             */
            Logger.e("Pending tasks is changed during measurement upload");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (results.length() > 0) {
        try {
            this.checkin.uploadMeasurementResult(results, resourceCapManager);
        } catch (IOException e) {
            Logger.e("Error when uploading message");
        }
    }

    Logger.i("A total of " + results.length() + " uploaded");
    Logger.i("A total of " + results.length() + " is in the results list");
}

From source file:com.splout.db.dnode.HttpFileExchanger.java

public void send(final String tablespace, final int partition, final long version, final File binaryFile,
        final String url, boolean blockUntilComplete) {
    Future<?> future = clientExecutors.submit(new Runnable() {
        @Override//from   w w w . ja va  2s .c  o  m
        public void run() {
            DataOutputStream writer = null;
            InputStream input = null;
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setChunkedStreamingMode(config.getInt(FetcherProperties.DOWNLOAD_BUFFER));
                connection.setDoOutput(true);
                connection.setRequestProperty("filename", binaryFile.getName());
                connection.setRequestProperty("tablespace", tablespace);
                connection.setRequestProperty("partition", partition + "");
                connection.setRequestProperty("version", version + "");

                Checksum checkSum = new CRC32();

                writer = new DataOutputStream(new GZIPOutputStream(connection.getOutputStream()));
                // 1 - write file size
                writer.writeLong(binaryFile.length());
                writer.flush();
                // 2 - write file content
                input = new FileInputStream(binaryFile);
                byte[] buffer = new byte[config.getInt(FetcherProperties.DOWNLOAD_BUFFER)];
                long wrote = 0;
                for (int length = 0; (length = input.read(buffer)) > 0;) {
                    writer.write(buffer, 0, length);
                    checkSum.update(buffer, 0, length);
                    wrote += length;
                }
                // 3 - add the CRC so that we can verify the download
                writer.writeLong(checkSum.getValue());
                writer.flush();
                log.info("Sent file " + binaryFile + " to " + url + " with #bytes: " + wrote + " and checksum: "
                        + checkSum.getValue());
            } catch (IOException e) {
                log.error(e);
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException ignore) {
                }
            }
        }
    });
    try {
        if (blockUntilComplete) {
            while (future.isDone() || future.isCancelled()) {
                Thread.sleep(1000);
            }
        }
    } catch (InterruptedException e) {
        // interrupted!
    }
}

From source file:fr.duminy.jbackup.swing.ProgressPanelTest.java

private void checkState(TaskState taskState, Long value, Long maxValue, Throwable error, Future<?> task) {
    assertThat(panel.getBorder()).isExactlyInstanceOf(TitledBorder.class);
    assertThatPanelHasTitle(panel, TITLE);

    JPanelFixture progressPanel = new JPanelFixture(robot(), panel);
    robot().settings().componentLookupScope(ComponentLookupScope.ALL);
    JProgressBarFixture progressBar = progressPanel.progressBar();
    robot().settings().componentLookupScope(ComponentLookupScope.SHOWING_ONLY);
    String expectedMessage;/*from w  w  w. j ava 2s  .  co m*/
    final boolean taskInProgress;
    switch (taskState) {
    case NOT_STARTED:
        taskInProgress = false;
        progressBar.requireIndeterminate().requireText("Not started");
        assertThat(panel.isFinished()).as("isFinished").isFalse();
        break;

    case TASK_DEFINED:
        taskInProgress = false;
        break;

    case STARTED:
        taskInProgress = (task != null);
        progressBar.requireIndeterminate().requireText("Estimating total size");
        assertThat(panel.isFinished()).as("isFinished").isFalse();
        break;

    case TOTAL_SIZE_COMPUTED:
    case PROGRESS:
        taskInProgress = (task != null);
        int iValue;
        int iMaxValue;
        if (maxValue > Integer.MAX_VALUE) {
            iValue = Utils.toInteger(value, maxValue);
            iMaxValue = Integer.MAX_VALUE;
        } else {
            iValue = value.intValue();
            iMaxValue = maxValue.intValue();
        }

        expectedMessage = format("%s/%s written (%1.2f %%)", byteCountToDisplaySize(value),
                byteCountToDisplaySize(maxValue), Utils.percent(value, maxValue));
        progressBar.requireDeterminate().requireValue(iValue).requireText(expectedMessage);
        assertThat(progressBar.component().getMinimum()).isEqualTo(0);
        assertThat(progressBar.component().getMaximum()).isEqualTo(iMaxValue);
        assertThat(panel.isFinished()).as("isFinished").isFalse();
        break;

    case FINISHED:
    default:
        taskInProgress = false;
        if (error == null) {
            progressBar.requireDeterminate().requireText("Finished");
        } else {
            expectedMessage = error.getMessage();
            if (expectedMessage == null) {
                expectedMessage = error.getClass().getSimpleName();
            }
            progressBar.requireDeterminate().requireText("Error : " + expectedMessage);
        }
        assertThat(panel.isFinished()).as("isFinished").isTrue();
        break;
    }

    Container parent = null;
    if (!TaskState.FINISHED.equals(taskState)) {
        // checks progress panel is visible
        parent = panel.getParent();
        assertThat(parent).isNotNull();
        assertThat(parent.getComponents()).contains(panel);
    }

    if (taskInProgress) {
        assertThat(panel.isFinished()).isFalse();
        assertThat(task.isCancelled()).as("task cancelled").isFalse();

        // cancel the task
        JButtonFixture cancelButton = progressPanel.button();
        cancelButton.requireText("").requireToolTip("Cancel the task");
        assertThat(cancelButton.component().getIcon()).isNotNull();
        cancelButton.click();

        // checks progress panel is not visible
        assertThat(panel.isFinished()).isTrue();
        assertThat(panel.getParent()).isNull();
        assertThat(parent.getComponents()).doesNotContain(panel);
        assertThat(task.isCancelled()).as("task cancelled").isTrue();
        assertThat(((TestableTask) task).getMayInterruptIfRunning()).as("MayInterruptIfRunning").isFalse();
    } else {
        // check no cancel button is visible if the task has been defined
        requireCancelButton(progressPanel, taskState == TaskState.TASK_DEFINED);
    }
}

From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationSetApprove.java

@PreAuthorize(privileges = { PrivilegeEnum.ADMIN }, scope = Scope.ORGANIZATION, cacheUpdate = true)
public Organisation call() throws AASUnauthorizedException, ExecutionException, IllegalAccessException {
    if (ConstEnumOrgStatus.approved.equals(this._organisation.getStatus())) {
        throw new ExecutionException("Die Institution ist bereits in der Status 'approved'.", null);
    }//from   ww w  . j  ava2 s  .  c o  m
    Future<Organisation> submitOrgOnWorkDir = null;
    Future<Organisation> submitOrgOnLicencedDir = null;

    Future<Organisation> submitOrgParentOnLicencedDir = null;
    Future<Organisation> submitOrgParentOnWorkDir = null;

    Organisation vOrgParentOnLicenceDir = null;
    Organisation vOrgParentOnWorkDir = null;

    try {
        // -- set a new status:
        this._organisation.setStatus(ConstEnumOrgStatus.approved);
        // -- save status:
        ThreadOrganisationUpdate threadOrganisationUpdate = new ThreadOrganisationUpdate(_ready, _organisation,
                false, _performer);
        threadOrganisationUpdate.setChangeOfStatus(true);
        submitOrgOnWorkDir = LDAPConnector.getSingletonInstance().getExecutorServiceOne()
                .submit(threadOrganisationUpdate);

        // -- Ist diese Organisation unter Licensed schon vorhanden?
        // -- Read organization on the license directory:
        ThreadOrganisationRead threadOrgOnLicencedDirRead = new ThreadOrganisationRead(
                new OIDs(this._organisation.getOIDs().getOrgName(), false), this.getPerformer());
        // -- the request goes to the branch with licensed organizations:
        threadOrgOnLicencedDirRead.setLicensedOrgs(true);
        submitOrgOnLicencedDir = LDAPConnector.getSingletonInstance().getExecutorServiceOne()
                .submit(threadOrgOnLicencedDirRead);

        // -- Operations in the licensed area...
        Boolean vIsOrgParentLicense = null;
        if (this._organisation.getOrgParent() != null) {

            // -- Parent on the license directory:
            ThreadOrganisationRead threadOrgParentOnLicencedDirRead = new ThreadOrganisationRead(
                    new OIDs(this._organisation.getOrgParent(), false), this.getPerformer());
            // -- the request goes to the branch with licensed organizations:
            threadOrgParentOnLicencedDirRead.setLicensedOrgs(true);
            submitOrgParentOnLicencedDir = LDAPConnector.getSingletonInstance().getExecutorServiceOne()
                    .submit(threadOrgParentOnLicencedDirRead);

            // -- Parent on the work directory:
            ThreadOrganisationRead threadOrgParentOnWorkDirRead = new ThreadOrganisationRead(
                    new OIDs(this._organisation.getOrgParent(), false), this.getPerformer());
            // -- the request goes to the branch with licensed organizations:
            submitOrgParentOnWorkDir = LDAPConnector.getSingletonInstance().getExecutorServiceOne()
                    .submit(threadOrgParentOnWorkDirRead);

            // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            // -- Parent on the license directory:
            try {
                //vIsOrgParentLicense = (threadOrgParentOnLicencedDirRead.call() != null);
                vIsOrgParentLicense = ((vOrgParentOnLicenceDir = submitOrgParentOnLicencedDir.get(3,
                        TimeUnit.SECONDS)) != null);
            }
            /*
            catch (NameNotFoundException ex) {
            // hier gibt es keinen Grund zur Panik! ;-)
            vIsOrgParentLicense = Boolean.FALSE;
            }
             */
            catch (ExecutionException ex) {
                if ((ex.getCause() != null)
                        && (ex.getCause().getClass().isAssignableFrom(NameNotFoundException.class))) {
                    // hier gibt es keinen Grund zur Panik! ;-)
                    vIsOrgParentLicense = Boolean.FALSE;
                } else {
                    throw ex;
                }
            } catch (InterruptedException ex) {
                throw new ExecutionException(ex);
            } catch (TimeoutException ex) {
                throw new ExecutionException(ex);
            }
        }

        try {

            // -- Update abwarten
            this._organisation = submitOrgOnWorkDir.get(3, TimeUnit.SECONDS);

            // -- die Organisation wenn mglich in der lizenzierte Verzeichnis schreiben:
            if ((vIsOrgParentLicense == null) || (vIsOrgParentLicense.booleanValue())) {
                // -- ! This institution is classified to the licensed organizations:
                Organisation vOrgOnLicensedDir = null;
                try {
                    vOrgOnLicensedDir = submitOrgOnLicencedDir.get(3, TimeUnit.SECONDS);
                    if (!vOrgOnLicensedDir.getOrgRDN().equalsIgnoreCase(this._organisation.getOrgRDN())) {
                        /*
                         * The shift operation works beautifully but may cause to error, because there are 
                         * potential changes from the sub-organizations in the Work Directory will not be included.
                         * ...therefore the Orgnanisation is first deleted and then will be re-copied
                        ThreadOrganisationMove threadOrganisationMove =
                        new ThreadOrganisationMove(vOrgOnLicensedDir.getOIDs().getOrgName(), this._organisation
                            .getOrgParent(), true, _performer);
                        vOrgOnLicensedDir = threadOrganisationMove.call();
                         */
                        this.deletingFromLicensedOrgsDir(vOrgOnLicensedDir);
                        // -- !!! very important for further processing:
                        vOrgOnLicensedDir = null;
                    }
                }
                /*
                catch (NameNotFoundException ex) {
                // es gibt keinen Grund zur Panik! ;-)
                }
                 */
                catch (ExecutionException ex) {
                    if ((ex.getCause() != null)
                            && (ex.getCause().getClass().isAssignableFrom(NameNotFoundException.class))) {
                        // hier gibt es keinen Grund zur Panik...
                    } else {
                        // hier aber schon...
                        throw ex;
                    }
                } catch (InterruptedException ex) {
                    throw new ExecutionException(ex);
                } catch (TimeoutException ex) {
                    throw new ExecutionException(ex);
                }

                if (vOrgOnLicensedDir != null) {
                    if (!ConstEnumOrgStatus.revised.equals(this._oldStatus)) {
                        // -- This should be never happen:
                        LOG.log(Level.WARNING,
                                "The old status is not ''revised'' but this organization is between the Licensed: this should never be happen! Old status: ''{0}''",
                                this._oldStatus.name());
                    }
                    // -- !!! The organization could not be moved:
                    if (vOrgOnLicensedDir.getOrgRDN().equals(this._organisation.getOrgRDN())) {
                        // -- Update licensed organization:
                        try {
                            threadOrganisationUpdate = new ThreadOrganisationUpdate(_ready, _organisation,
                                    false, _performer);
                            threadOrganisationUpdate.setUpdatingOfLicensedOrgs(true);
                            threadOrganisationUpdate.call();
                        } catch (NameNotFoundException ex) {
                            throw new ExecutionException(ex);
                        } catch (AttributeModificationException ex) {
                            throw new ExecutionException(ex);
                        }
                    } else {
                        LOG.log(Level.WARNING, "The licensed (RDN='" + vOrgOnLicensedDir.getOrgRDN()
                                + "') organization can not be updated because it has been postponed to new RDN='"
                                + this._organisation.getOrgRDN() + "'");
                    }
                } else {
                    // -- Der Knoten sollte kopiert werden aber nur unter einem Bedingung...
                    if (submitOrgParentOnWorkDir != null) {
                        // -- Parent on the work directory:
                        try {
                            vOrgParentOnWorkDir = submitOrgParentOnWorkDir.get(3, TimeUnit.SECONDS);
                        } catch (ExecutionException ex) {
                            if ((ex.getCause() != null) && (ex.getCause().getClass()
                                    .isAssignableFrom(NameNotFoundException.class))) {
                                // hier gibt es keinen Grund zur Panik! ;-)
                            } else {
                                throw ex;
                            }
                        } catch (InterruptedException ex) {
                            throw new ExecutionException(ex);
                        } catch (TimeoutException ex) {
                            throw new ExecutionException(ex);
                        }
                    }
                    // ...dass die RDN des Parnts- Knoten stimmt, das heit, dass die nicht verschoben wurde:
                    if (((vOrgParentOnWorkDir != null) && (vOrgParentOnLicenceDir != null)
                            && (vOrgParentOnWorkDir.getOrgRDN().equals(vOrgParentOnLicenceDir.getOrgRDN())))
                            || ((vOrgParentOnWorkDir == null) && (vOrgParentOnLicenceDir == null))) {
                        this.copyingToLicensedOrgs(_organisation);
                    }
                }

            }
        } catch (InterruptedException ex) {
            throw new ExecutionException(ex);
        } catch (TimeoutException ex) {
            throw new ExecutionException(ex);
        }
    } finally {
        if ((submitOrgOnWorkDir != null) && (!submitOrgOnWorkDir.isDone())
                && (!submitOrgOnWorkDir.isCancelled())) {
            submitOrgOnWorkDir.cancel(true);
        }
        if ((submitOrgOnLicencedDir != null) && (!submitOrgOnLicencedDir.isDone())
                && (!submitOrgOnLicencedDir.isCancelled())) {
            submitOrgOnLicencedDir.cancel(true);
        }
        if ((submitOrgParentOnWorkDir != null) && (!submitOrgParentOnWorkDir.isDone())
                && (!submitOrgParentOnWorkDir.isCancelled())) {
            submitOrgParentOnWorkDir.cancel(true);
        }
        if ((submitOrgParentOnLicencedDir != null) && (!submitOrgParentOnLicencedDir.isDone())
                && (!submitOrgParentOnLicencedDir.isCancelled())) {
            submitOrgParentOnLicencedDir.cancel(true);
        }
    }
    return this._organisation;
}