Example usage for java.util.concurrent ExecutionException ExecutionException

List of usage examples for java.util.concurrent ExecutionException ExecutionException

Introduction

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

Prototype

public ExecutionException(String message, Throwable cause) 

Source Link

Document

Constructs an ExecutionException with the specified detail message and cause.

Usage

From source file:org.apache.bookkeeper.meta.MetadataDrivers.java

/**
 * Process the provided <i>function</i> with metadata bookie driver resolved
 * from the metadata service uri returned by {@link ServerConfiguration#getMetadataServiceUri()}.
 *
 * @param conf server configuration//from ww  w  . ja  va2 s. c o m
 * @param function function to apply with metadata bookie driver.
 * @throws MetadataException when failed to access metadata store
 * @throws ExecutionException exception thrown when processing <tt>function</tt>.
 */
public static <T> T runFunctionWithMetadataBookieDriver(ServerConfiguration conf,
        Function<MetadataBookieDriver, T> function) throws MetadataException, ExecutionException {
    try (MetadataBookieDriver driver = MetadataDrivers
            .getBookieDriver(URI.create(conf.getMetadataServiceUri()))) {
        driver.initialize(conf, () -> {
        }, NullStatsLogger.INSTANCE);
        try {
            return function.apply(driver);
        } catch (Exception uee) {
            if (uee.getCause() instanceof MetadataException) {
                throw (MetadataException) uee.getCause();
            } else {
                throw new ExecutionException(uee.getMessage(), uee.getCause());
            }
        }
    } catch (ConfigurationException e) {
        throw new MetadataException(Code.INVALID_METADATA_SERVICE_URI, e);
    }
}

From source file:org.kitodo.production.helper.tasks.EmptyTask.java

/**
 * The procedure setException can be used to save an exception that occurred
 * and show it in the front end. It will only record the first exception
 * (which is likely to be the source of all the misery) and it will not
 * record an InterruptedException if the thread has already been
 * interrupted.// w ww  .j a  v a  2  s . com
 *
 * @param exception
 *            exception to save
 */
public void setException(Throwable exception) {
    if (exception instanceof InterruptedException) {
        Thread.currentThread().interrupt();
    }
    if (Objects.isNull(this.exception) && (!isInterrupted() || !(exception instanceof InterruptedException))) {
        if (exception instanceof Exception) {
            this.exception = (Exception) exception;
        } else {
            this.exception = new ExecutionException(exception.getMessage(), exception);
        }
    }
}

From source file:org.openspaces.grid.gsm.rebalancing.RebalancingUtils.java

static FutureStatefulProcessingUnitInstance relocateProcessingUnitInstanceAsync(
        final GridServiceContainer targetContainer, final ProcessingUnitInstance puInstance, final Log logger,
        final long duration, final TimeUnit timeUnit) {

    final ProcessingUnit pu = puInstance.getProcessingUnit();
    final GridServiceContainer[] replicationSourceContainers = getReplicationSourceContainers(puInstance);
    final int instanceId = puInstance.getInstanceId();

    final AtomicReference<Throwable> relocateThrowable = new AtomicReference<Throwable>();

    final Admin admin = puInstance.getAdmin();
    final int runningNumber = puInstance.getClusterInfo().getRunningNumber();
    final String puName = puInstance.getName();

    final GridServiceContainer sourceContainer = puInstance.getGridServiceContainer();
    final Set<ProcessingUnitInstance> puInstancesFromSamePartition = getOtherInstancesFromSamePartition(
            puInstance);/*from w w w .java  2 s.c om*/
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Found instances from the same partition as " + RebalancingUtils.puInstanceToString(puInstance)
                        + " : " + RebalancingUtils.puInstancesToString(puInstancesFromSamePartition));
    }

    if (puInstancesFromSamePartition.size() != pu.getNumberOfBackups()) {
        // total number of instances per partition = numberOfBackups + 1
        throw new IllegalStateException("puInstancesFromSamePartition has "
                + puInstancesFromSamePartition.size() + " instances instead of " + pu.getNumberOfBackups());
    }

    final long start = System.currentTimeMillis();
    final long end = start + timeUnit.toMillis(duration);

    ((InternalAdmin) admin).scheduleAdminOperation(new Runnable() {
        public void run() {
            try {
                logger.debug("Relocation of " + RebalancingUtils.puInstanceToString(puInstance) + " to "
                        + ContainersSlaUtils.gscToString(targetContainer) + " has started.");
                puInstance.relocate(targetContainer);
            } catch (AdminException e) {
                logger.error("Admin exception " + e.getMessage(), e);
                relocateThrowable.set(e);
            } catch (Throwable e) {
                logger.error("Unexpected exception " + e.getMessage(), e);
                relocateThrowable.set(e);
            }
        }
    });

    return new FutureStatefulProcessingUnitInstance() {

        Throwable throwable;
        ProcessingUnitInstance newInstance;

        public boolean isTimedOut() {
            return System.currentTimeMillis() > end;
        }

        public boolean isDone() {

            endRelocation();

            return isTimedOut() || throwable != null || newInstance != null;
        }

        public ProcessingUnitInstance get() throws ExecutionException, IllegalStateException, TimeoutException {

            endRelocation();

            ExecutionException exception = getException();
            if (exception != null) {
                throw exception;
            }
            if (newInstance == null) {
                if (isTimedOut()) {
                    throw new TimeoutException("Relocation timeout");
                }
                throw new IllegalStateException("Async operation is not done yet.");
            }

            return newInstance;
        }

        public Date getTimestamp() {
            return new Date(start);
        }

        public ExecutionException getException() {

            endRelocation();
            if (throwable != null) {
                return new ExecutionException(throwable.getMessage(), throwable);
            }
            return null;
        }

        /**
         * populates this.exception or this.newInstance if relocation is complete
         */
        private void endRelocation() {
            boolean inProgress = true;

            tryStateChange(); // this makes relocation synchronous
            if (newInstance != null || throwable != null) {
                inProgress = false;
            }

            if (inProgress) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Relocation from " + ContainersSlaUtils.gscToString(getSourceContainer())
                            + " to " + ContainersSlaUtils.gscToString(getTargetContainer())
                            + " is in progress.");
                }
                // do nothing. relocate() method running on another thread has not returned yet.
            }
        }

        private void tryStateChange() {
            ProcessingUnitInstance relocatedInstance = getRelocatedProcessingUnitInstance();
            if (relocatedInstance != null) {

                if (relocatedInstance.getGridServiceContainer().equals(targetContainer)) {
                    if (relocatedInstance.getSpaceInstance() != null
                            && relocatedInstance.getSpaceInstance().getMode() != SpaceMode.NONE) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Relocation from " + ContainersSlaUtils.gscToString(getSourceContainer())
                                            + " to " + ContainersSlaUtils.gscToString(getTargetContainer())
                                            + " had ended successfully.");
                        }
                        newInstance = relocatedInstance;
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Relocation from " + ContainersSlaUtils.gscToString(getSourceContainer())
                                + " to " + ContainersSlaUtils.gscToString(getTargetContainer())
                                + " has ended with an error.");
                    }
                    throwable = new WrongContainerProcessingUnitRelocationException(puInstance,
                            targetContainer);

                }
            }
        }

        private ProcessingUnitInstance getRelocatedProcessingUnitInstance() {
            for (GridServiceContainer container : admin.getGridServiceContainers()) {
                for (ProcessingUnitInstance instance : container.getProcessingUnitInstances(puName)) {
                    if (!instance.equals(puInstance)
                            && instance.getClusterInfo().getRunningNumber() == runningNumber
                            && !puInstancesFromSamePartition.contains(instance)) {
                        return instance;
                    }
                }
            }
            return null;
        }

        private boolean isAtLeastOneInstanceValid(Set<ProcessingUnitInstance> instances) {
            boolean isValidState = false;
            for (ProcessingUnitInstance instance : instances) {
                if (instance.isDiscovered() && instance.getGridServiceContainer().isDiscovered()) {
                    isValidState = true;
                    break;
                }
            }
            return isValidState;
        }

        public String getFailureMessage() {
            if (isTimedOut()) {
                return "relocation timeout of processing unit instance " + instanceId + " from "
                        + gscToString(sourceContainer) + " to " + gscToString(targetContainer);
            }

            if (getException() != null) {
                return getException().getMessage();
            }

            throw new IllegalStateException("Relocation has not encountered any failure.");

        }

        public GridServiceContainer getTargetContainer() {
            return targetContainer;
        }

        public ProcessingUnit getProcessingUnit() {
            return pu;
        }

        public int getInstanceId() {
            return instanceId;
        }

        public GridServiceContainer getSourceContainer() {
            return sourceContainer;
        }

        public GridServiceContainer[] getReplicaitonSourceContainers() {
            return replicationSourceContainers;
        }

    };
}

From source file:de.sub.goobi.helper.tasks.EmptyTask.java

/**
 * The procedure setException can be used to save an exception that occurred
 * and show it in the front end. It will only record the first exception
 * (which is likely to be the source of all the misery) and it will not
 * record an InterruptedException if the thread has already been
 * interrupted.//from   www  .j  a  va2s  .  co m
 *
 * @param exception
 *            exception to save
 */
public void setException(Throwable exception) {
    if (this.exception == null && (!isInterrupted() || !(exception instanceof InterruptedException))) {
        if (exception instanceof Exception) {
            this.exception = (Exception) exception;
        } else {
            this.exception = new ExecutionException(exception.getMessage(), exception);
        }
    }
}

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

private void createOrg() throws ExecutionException, IllegalArgumentException, AASUnauthorizedException {
    InitialLdapContext vCtx = null;

    Attributes vOrgAttributes = new BasicAttributes(true);

    BasicAttribute objectClass = new BasicAttribute("objectclass", "top");
    objectClass.add(Constants.ldap_ddbOrg_ObjectClass);
    objectClass.add("organization");

    vOrgAttributes.put(objectClass);/*from   w w  w . j  av  a  2s . c  om*/

    // ---All this occurs only if that is not a copy in the export directory
    if (!this.isAddToLicensedOrgs()) {

        // -- When creating the status always set on Pending:
        if (!this.isIngestingOperation()) {
            this._orgObj.setStatus(ConstEnumOrgStatus.pending);
            long vTimeStamp = new Date().getTime();
            this._orgObj.setModified(vTimeStamp);
            this._orgObj.setCreated(vTimeStamp);
        }

        if (this._performer != null) {
            this._orgObj.setModifiedBy(this._performer.getUid());
            this._orgObj.setCreatedBy(this._performer.getUid());
        }

        // -- Is null, if it was isIngestingOperation or isAddToLicensedOrgs 
        //    and therefore does not need to be additionally checked
        if (_submit != null) {
            GeoAdresse vGeoAdresse;
            try {
                vGeoAdresse = _submit.get(50, TimeUnit.SECONDS);
                if (vGeoAdresse.getRequestStatus() == GeoRequestStatus.OK) {
                    this._orgObj.getAddress().setLatitude(vGeoAdresse.getLatitude());
                    this._orgObj.getAddress().setLongitude(vGeoAdresse.getLongitude());
                    this._orgObj.getAddress().setLocationDisplayName(vGeoAdresse.getLocationDisplayName());
                } else {
                    LOG.log(Level.WARNING, "GeoRequestStatus: {0}, (organization id: {1})",
                            new Object[] { vGeoAdresse.getRequestStatus(), this._orgObj.getOIDs() });
                }
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._orgObj.getOIDs(), ex);
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._orgObj.getOIDs(), ex);
            }
        }
    }

    // -- Conversion of parameters to LDAP attributes:
    this.convertOrganizationToLdapOrgAttrsForCreate(this._orgObj, vOrgAttributes, getPerformer());

    StringBuilder vEntryDN = (this.isAddToLicensedOrgs() ? this.getLicensedOrgsDN(this._orgObj.getOIDs())
            : this.getOrgDN(this._orgObj.getOIDs()));

    try {
        // put arbitrary (Org) Properties as JSON-String into LDAP.
        if (this._orgObj.getProperties() != null && !this._orgObj.getProperties().isEmpty()) {
            vOrgAttributes.put(new BasicAttribute(Constants.ldap_ddbOrg_Properties,
                    serializer.serialize(this._orgObj.getProperties())));
        }

        // finally bind the entry
        vCtx = LDAPConnector.getSingletonInstance().takeCtx();
        ((InitialDirContext) vCtx).bind(vEntryDN.toString(), vCtx, vOrgAttributes);

        // -- Add default privilege(s) so we can assign performer
        //    but only if that is not a copy in the export directory
        if (!this.isAddToLicensedOrgs()) {
            this._orgObj.getPrivilegesSet().add(PrivilegeEnum.ADMIN_ORG);

            // create org-privileges
            for (PrivilegeEnum p : this._orgObj.getPrivilegesSet()) {
                ThreadSinglePrivilegeCreate threadSinglePrivilegeCreate = new ThreadSinglePrivilegeCreate(p,
                        this._orgObj, this._performer);
                threadSinglePrivilegeCreate.call();
            }
            // -- Logging:
            LOG.log(Level.INFO, "One organization with DN: ''{0}'' was created.", new Object[] { vEntryDN });
        } else {
            // -- Logging:
            LOG.log(Level.INFO, "One organization with DN: ''{0}'' was copied to the export directory.",
                    new Object[] { vEntryDN });
        }
    } catch (AssertionError ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new IllegalArgumentException(ex.getMessage(), ex.getCause());
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ex) {
        // LDAP: error code 68 - ENTRY_ALREADY_EXISTS: failed for Add
        // Request
        try {
            if (vCtx != null) {
                vCtx.close();
                vCtx = null;
            }
        } catch (NamingException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        }
        try {
            vCtx = LDAPConnector.getSingletonInstance().getDirContext();
        } catch (NamingException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        } catch (IllegalAccessException ex1) {
            LOG.log(Level.SEVERE, null, ex1);
        }
        throw new IllegalArgumentException(ex.getMessage());
    } finally {
        if (vCtx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(vCtx);
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "Exception", ex);
            }
        }
    }

}

From source file:org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioningAdapter.java

@Override
public FutureGridServiceAgents getDiscoveredMachinesAsync(final long duration, final TimeUnit unit) {

    final AtomicReference<Object> ref = new AtomicReference<Object>(null);
    final long start = System.currentTimeMillis();
    final long end = start + unit.toMillis(duration);

    submit(new Runnable() {
        public void run() {
            try {
                GridServiceAgent[] agents = machineProvisioning.getDiscoveredMachines(duration, unit);
                ref.set(agents);/*from   w w  w  . j  a  v  a  2s . co m*/
            } catch (ElasticMachineProvisioningException e) {
                ref.set(e);
            } catch (ElasticGridServiceAgentProvisioningException e) {
                ref.set(e);
            } catch (InterruptedException e) {
                ref.set(e);
            } catch (TimeoutException e) {
                ref.set(e);
            } catch (NoClassDefFoundError e) {
                ref.set((new NoClassDefFoundElasticMachineProvisioningException(e)));
            } catch (Throwable e) {
                logger.error("Unexpected exception", e);
                ref.set(e);
            }
        }

    });

    return new FutureGridServiceAgents() {

        public boolean isDone() {
            return System.currentTimeMillis() > end || ref.get() != null;
        }

        public ExecutionException getException() {
            Object result = ref.get();
            if (result != null && result instanceof Throwable) {
                Throwable throwable = (Throwable) result;
                return new ExecutionException(throwable.getMessage(), throwable);
            }
            return null;
        }

        public boolean isTimedOut() {
            Object result = ref.get();
            return System.currentTimeMillis() > end || (result != null && result instanceof TimeoutException);
        }

        public Date getTimestamp() {
            return new Date(start);
        }

        public GridServiceAgent[] get() throws ExecutionException, IllegalStateException, TimeoutException {

            Object result = ref.get();

            if (result == null) {
                if (System.currentTimeMillis() > end) {
                    throw new TimeoutException("Starting a new machine took more than "
                            + unit.toSeconds(duration) + " seconds to complete.");
                }

                throw new IllegalStateException("Async operation is not done yet.");
            }

            if (getException() != null) {
                throw getException();
            }

            return (GridServiceAgent[]) result;

        }
    };
}

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

private void updateOrg() throws NameNotFoundException, AASUnauthorizedException, AttributeModificationException,
        ExecutionException {// w  w  w. j  ava2  s . c  o  m
    boolean vChange = false;
    InitialLdapContext vCtx = null;
    try {

        if (this._oldOrganisation == null) {
            LOG.log(Level.WARNING, "No such organization ''{0}'' with oid: ''{1}''.",
                    new Object[] { this._organisation.getDisplayName(), this._organisation.getOIDs() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        GeoAdresse vGeoAdresse;
        String vLocalDispalyName = null;
        if (_submit != null) { // hier ist "GeoLocationDisplayName" breits ausgefhrt
            try {
                vGeoAdresse = _submit.get(10, TimeUnit.SECONDS);
                if (vGeoAdresse.getRequestStatus() == GeoRequestStatus.OK) {
                    this._organisation.getAddress().setLatitude(vGeoAdresse.getLatitude());
                    this._organisation.getAddress().setLongitude(vGeoAdresse.getLongitude());
                    this._organisation.getAddress()
                            .setLocationDisplayName(vGeoAdresse.getLocationDisplayName());
                } else {
                    LOG.log(Level.WARNING, "GeoRequestStatus: {0}, (organization id: {1})",
                            new Object[] { vGeoAdresse.getRequestStatus(), this._organisation.getOIDs() });
                }
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            }
        } else if (_submitGeoLocDisplayName != null) {
            try {
                vLocalDispalyName = _submitGeoLocDisplayName.get(5, TimeUnit.SECONDS);
                this._organisation.getAddress().setLocationDisplayName(vLocalDispalyName);
                //LOG.info("LocalDisplayName='" + vLocalDispalyName + "'" + vLocalDispalyName + "'");
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (ExecutionException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            }

        }

        LOG.info("newOIDs: '" + this._organisation.getOIDs() + "'");
        LOG.info("oldOIDs: '" + this._oldOrganisation.getOIDs() + "'");

        if (this._organisation.getOrgRDN() == null) {
            // -- Ansonsten eine nicht gesetzte RDN kann zum Knall fhren...
            this._organisation.setOrgRDN(this._oldOrganisation.getOrgRDN());
        } else if (!this._organisation.getOrgRDN().equals(this._oldOrganisation.getOrgRDN())) {
            // -- Hier ist etwas faul...
            LOG.log(Level.WARNING,
                    "The organization ''{0}'' has RDN: ''{1}'', but there exist an organization ''{0}'' with RDN: ''{2}''!",
                    new Object[] { this._organisation.getId(), this._organisation.getOrgRDN(),
                            this._oldOrganisation.getOrgRDN() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        if (this.isPrivilegesUpdate()) {
            Set<PrivilegeEnum> removePrivileges = this.privilegeDiff(this._organisation.getPrivilegesSet(),
                    this._oldOrganisation.getPrivilegesSet());
            Set<PrivilegeEnum> addPrivileges = this.privilegeDiff(this._oldOrganisation.getPrivilegesSet(),
                    this._organisation.getPrivilegesSet());
            if (!removePrivileges.isEmpty() || !addPrivileges.isEmpty()) {
                vChange = true;
                for (PrivilegeEnum p : removePrivileges) {
                    ThreadSinglePrivilegeDelete threadSinglePrivilegeDelete = new ThreadSinglePrivilegeDelete(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeDelete.call();
                }
                for (PrivilegeEnum p : addPrivileges) {
                    ThreadSinglePrivilegeCreate threadSinglePrivilegeCreate = new ThreadSinglePrivilegeCreate(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeCreate.call();
                }
            }
        }

        Attributes orgAttributes = new BasicAttributes(true);
        Attributes orgRemoveAttributes = new BasicAttributes(true);

        if (vChange = this.convertOrganizationToLdapOrgAttrsForUpdate(this._organisation, this._oldOrganisation,
                orgAttributes, orgRemoveAttributes, getPerformer())) {

            // -- If any changes, the status is set to 'revised'
            //    but not if status will be explicitly changed or by a update operation on Licenses directory
            if (!isChangeOfStatus() && !isUpdatingOfLicensedOrgs()) {
                if ((ConstEnumOrgStatus.approved.equals(this._organisation.getStatus()))) {
                    // -- ...then go retrospectively into "revised" status:
                    this._organisation.setStatus(ConstEnumOrgStatus.revised);

                    orgAttributes.put(Constants.ldap_ddbOrg_Status,
                            String.valueOf(this._organisation.getStatus().name()));
                }
            }
        }
        // ---------------------------------------------------------------------
        if (vChange) {

            // -- Save changes to the corresponding directory:
            StringBuilder vOrgEntryDN = (isUpdatingOfLicensedOrgs()
                    ? this.getLicensedOrgsDN(this._organisation.getOIDs())
                    : this.getOrgDN(this._organisation.getOIDs()));
            LOG.log(Level.INFO, "DEBUG-Info: destination OrgEntryDN = '" + vOrgEntryDN + "'");

            vCtx = LDAPConnector.getSingletonInstance().takeCtx();
            if (orgRemoveAttributes.size() > 0) {
                vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REMOVE_ATTRIBUTE, orgRemoveAttributes);
            }
            vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REPLACE_ATTRIBUTE, orgAttributes);
        } else {
            throw new AttributeModificationException(
                    "Not modified: oid = '" + this._organisation.getOIDs() + "'");
        }

    } catch (RejectedExecutionException ex) {
        LOG.log(Level.SEVERE, "RejectedExecutionException\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.WARNING, null, ex);
        throw ex;
    } catch (AttributeModificationException ex) {
        LOG.log(Level.WARNING, "AttributeModificationException\n{0}", ex.getMessage());
        // !!!!AttributeModificationException extends NamingExeption:
        //throw ex;
        throw new AttributeModificationException(ex.getMessage());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "NamingException\n{0}", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (vCtx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(vCtx);
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "Exception", ex);
            }
        }
    }

}

From source file:org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioningAdapter.java

@Override
public FutureCleanupCloudResources cleanupCloudResources(final long duration, final TimeUnit unit) {
    final AtomicReference<Throwable> atomicExceptionRef = new AtomicReference<Throwable>();
    final AtomicBoolean atomicDone = new AtomicBoolean(false);

    if (!isStartMachineSupported()) {
        throw new UnsupportedOperationException();
    }/*from  www .  j  a va 2  s .c o  m*/

    final long start = System.currentTimeMillis();
    final long end = System.currentTimeMillis() + unit.toMillis(duration);
    submit(new Runnable() {

        @Override
        public void run() {

            logger.info("Cleaning cloud resources");
            try {
                NonBlockingElasticMachineProvisioningAdapter.this.machineProvisioning
                        .cleanupMachineResources(duration, unit);
                logger.info("Cleaned cloud resources.");
                atomicDone.set(true);
            } catch (ElasticMachineProvisioningException e) {
                atomicExceptionRef.set(e);
            } catch (InterruptedException e) {
                atomicExceptionRef.set(e);
            } catch (TimeoutException e) {
                atomicExceptionRef.set(e);
            } catch (NoClassDefFoundError e) {
                atomicExceptionRef.set((new NoClassDefFoundElasticMachineProvisioningException(e)));
            } catch (Throwable e) {
                atomicExceptionRef.set(e);
            }
        }

    });

    return new FutureCleanupCloudResources() {

        boolean mark;

        @Override
        public boolean isTimedOut() {
            Throwable exception = atomicExceptionRef.get();
            return (exception instanceof TimeoutException) || (!isDone() && System.currentTimeMillis() > end);
        }

        @Override
        public boolean isDone() {
            return atomicDone.get() || (atomicExceptionRef.get() != null);
        }

        @Override
        public Date getTimestamp() {
            return new Date(start);
        }

        @Override
        public ExecutionException getException() {
            ExecutionException executionException = null;
            Throwable throwable = atomicExceptionRef.get();
            if (throwable != null) {
                executionException = new ExecutionException(throwable.getMessage(), throwable);
            }
            return executionException;
        }

        @Override
        public Void get() throws ExecutionException, IllegalStateException, TimeoutException {

            if (!isDone()) {
                // dont allow calling get() before isDone returns true.
                throw new IllegalStateException("Async operation has not completed yet");
            }

            if (isDone() && getException() == null) {
                // all is ok
                return null;
            } else {
                throw getException();
            }
        }

        @Override
        public boolean isMarked() {
            return mark;
        }

        @Override
        public void mark() {
            mark = true;
        }
    };

}

From source file:org.elasticsearch.client.RestClient.java

private void performRequestAsync(final long startTime, final HostTuple<Iterator<HttpHost>> hostTuple,
        final HttpRequestBase request, final Set<Integer> ignoreErrorCodes,
        final HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory,
        final FailureTrackingResponseListener listener) {
    final HttpHost host = hostTuple.hosts.next();
    //we stream the request body if the entity allows for it
    final HttpAsyncRequestProducer requestProducer = HttpAsyncMethods.create(host, request);
    final HttpAsyncResponseConsumer<HttpResponse> asyncResponseConsumer = httpAsyncResponseConsumerFactory
            .createHttpAsyncResponseConsumer();
    final HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(hostTuple.authCache);
    client.execute(requestProducer, asyncResponseConsumer, context, new FutureCallback<HttpResponse>() {
        @Override//w  w w . j  a v  a2 s . c om
        public void completed(HttpResponse httpResponse) {
            try {
                RequestLogger.logResponse(logger, request, host, httpResponse);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                Response response = new Response(request.getRequestLine(), host, httpResponse);
                if (isSuccessfulResponse(statusCode)
                        || ignoreErrorCodes.contains(response.getStatusLine().getStatusCode())) {
                    onResponse(host);
                    listener.onSuccess(response);
                } else {
                    ResponseException responseException = new ResponseException(response);
                    if (isRetryStatus(statusCode)) {
                        //mark host dead and retry against next one
                        onFailure(host);
                        retryIfPossible(responseException);
                    } else {
                        //mark host alive and don't retry, as the error should be a request problem
                        onResponse(host);
                        listener.onDefinitiveFailure(responseException);
                    }
                }
            } catch (Exception e) {
                listener.onDefinitiveFailure(e);
            }
        }

        @Override
        public void failed(Exception failure) {
            try {
                RequestLogger.logFailedRequest(logger, request, host, failure);
                onFailure(host);
                retryIfPossible(failure);
            } catch (Exception e) {
                listener.onDefinitiveFailure(e);
            }
        }

        private void retryIfPossible(Exception exception) {
            if (hostTuple.hosts.hasNext()) {
                //in case we are retrying, check whether maxRetryTimeout has been reached
                long timeElapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
                long timeout = maxRetryTimeoutMillis - timeElapsedMillis;
                if (timeout <= 0) {
                    IOException retryTimeoutException = new IOException(
                            "request retries exceeded max retry timeout [" + maxRetryTimeoutMillis + "]");
                    listener.onDefinitiveFailure(retryTimeoutException);
                } else {
                    listener.trackFailure(exception);
                    request.reset();
                    performRequestAsync(startTime, hostTuple, request, ignoreErrorCodes,
                            httpAsyncResponseConsumerFactory, listener);
                }
            } else {
                listener.onDefinitiveFailure(exception);
            }
        }

        @Override
        public void cancelled() {
            listener.onDefinitiveFailure(new ExecutionException("request was cancelled", null));
        }
    });
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected boolean organizationExists(String orgId) throws ExecutionException {
    NamingEnumeration<SearchResult> searchResults = null;
    try {/*from w w w  . ja  v  a 2 s .  c o m*/
        searchResults = this.query(LDAPConnector.getSingletonInstance().getInstitutionBaseDN(),
                new StringBuilder("(& (objectclass=").append(Constants.ldap_ddbOrg_ObjectClass).append(") (")
                        .append(Constants.ldap_ddbOrg_Id).append("=").append(orgId).append("))").toString(),
                new String[] { Constants.ldap_ddbOrg_Id, "+" }, SearchControls.SUBTREE_SCOPE);
        if (searchResults.hasMore()) {
            return true;
        } else {
            return false;
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "something went wrong while checking if userId exists", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (NamingException e) {
            }
        }
    }
}