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:cat.calidos.morfeu.model.injection.DocumentModule.java

@Produces
public static Document produceDocument(@Named("NormalisedDocument") Document doc,
        Provider<ModelSubcomponent.Builder> modelComponentProvider,
        Provider<ContentParserSubcomponent.Builder> contentParserComponentProvider) throws ExecutionException {

    // FIXME: what exception should we throw here?
    Model model;//from w w  w  .j a  v a 2 s  . c om
    try {

        model = modelComponentProvider.get().builder().model().get();
        doc.setModel(model);
        ContentParserSubcomponent contentParser = contentParserComponentProvider.get().builder();
        doc.setValidator(contentParser.validator().get());
        doc.validate(); // if this does not throw an exception, it means content is valid
        doc.setContent(contentParser.content().get());

    } catch (Exception e) {
        throw new ExecutionException("Problem with model of document '" + doc.getName() + "' with model: '"
                + doc.getModelURI() + "'", e);
    }

    return doc;

}

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

protected Organisation convertLdapOrganizationToOrganisation(
        NamingEnumeration<SearchResult> pOrganizationResult, NamingEnumeration<SearchResult> pPrivilegesResult)
        throws ExecutionException, NameNotFoundException {
    Organisation vOrganisation = null;/*w w  w  . jav  a2s.com*/
    try {
        if ((pOrganizationResult != null) && pOrganizationResult.hasMore()) {

            SearchResult sr = pOrganizationResult.next();
            vOrganisation = convertSearchResultToOrganization(sr);
            // -- Organization privileges:
            vOrganisation = this.convertLdapGroupsToOrganizationPrivileges(vOrganisation, pPrivilegesResult);
        }
    } catch (NameNotFoundException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw ex;
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        // -- releases this context's resources immediately, instead of waiting for the garbage collector
        if (pOrganizationResult != null) {
            try {
                pOrganizationResult.close();
            } catch (NamingException ex) {
            }
        }
    }
    return vOrganisation;
}

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);
    }/* ww  w.  j av  a  2  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;
}

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

protected Organisation convertSearchResultToOrganization(final SearchResult sr)
        throws ExecutionException, NameNotFoundException {
    if (sr == null) {
        throw new ExecutionException("SearchResult sr == NULL", new NullPointerException());
    }//w  w w.  jav  a2s.  co  m
    Organisation vOrganisation = null;
    try {
        Attributes attributes = sr.getAttributes();

        Attribute attr;
        String vStr;
        String vOrgName = ((attr = attributes.get(Constants.ldap_ddbOrg_Id)) != null
                ? String.valueOf(attr.get())
                : null);
        String vName = sr.getName();
        String vNameInNamespace = sr.getNameInNamespace();
        // --- EntryDN
        String vEntryDN = ((attr = attributes.get(Constants.ldap_ddb_EntryDN)) != null
                ? String.valueOf(attr.get())
                : "");

        int idx;
        // -- Parent node detections:
        String vParent = null;
        //vParent = sr.getName();
        //LOG.log(Level.INFO, "getNameInNamespace() = '" + sr.getNameInNamespace() + "'");
        //LOG.log(Level.INFO, "getName() = '" + sr.getName() + "'");
        // -- getNameInNamespace() = 'o=99900711,o=00008125,o=00050350,ou=Organizations,dc=de'
        // -- getName() = 'o=99900711,o=00008125,o=00050350'

        //sr.getName(): 'o=00000116', 
        //sr.getNameInNamespace(): 'o=00000116,o=00050350,ou=Organizations,dc=de', 
        //vOrgEntryDN: 'o=00000116,o=00050350,ou=Organizations,dc=de'            
        vParent = sr.getNameInNamespace();
        if ((idx = vParent.indexOf(",ou=")) >= 0) {
            vParent = vParent.substring(0, idx);
        }
        vParent = vParent.replaceAll(Constants.ldap_ddbOrg_Id + "=", "");
        // -- 99900711,00008125,00050350'
        String[] vParents = vParent.split(",");

        if (vParents.length >= 2) {
            vParent = vParents[1];
        } else {
            vParent = null;
        }

        LOG.log(Level.INFO,
                "convertLdapOrganizationToOrganisation: o: '" + vOrgName + "', vParent: '" + vParent
                        + "', sr.getName(): '" + vName + "', sr.getNameInNamespace(): '" + vNameInNamespace
                        + "', vOrgEntryDN: '" + vEntryDN + "', sr.isRelative(): '" + sr.isRelative() + "'");
        /*
         * if ( (vOrgName != null)&&(!vOrgName.isEmpty()) ) { vOrganisation = new Organisation(vOrgName,
         * vDescription, vParent);
         */
        if ((vEntryDN != null) && (!vEntryDN.isEmpty())) {
            vOrganisation = new Organisation(vEntryDN,
                    (attr = sr.getAttributes().get(Constants.ldap_ddbOrg_PID)) != null
                            ? String.valueOf(attr.get())
                            : null);
            // Public-ID: (s.o.)
            // vOrganisation.setOrgPID( (attr = attributes.get(ddbOrg_PID)) != null ? String.valueOf(attr.get()) :
            // "");
            // Parent (s.o.)
            vOrganisation.setOrgParent(vParent);

            // Kurzbeschreibung der Einrichtung
            vOrganisation.setDescription((attr = attributes.get(Constants.ldap_ddbOrg_Description)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- Rechtsform
            try {
                vOrganisation.setBusinessCategory(
                        (attr = attributes.get(Constants.ldap_ddbOrg_BusinessCategory)) != null
                                ? ConstEnumOrgSector.valueOf(String.valueOf(attr.get()))
                                : null);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Sector-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            // -- Sub-Sectors:
            if ((attr = attributes.get(Constants.ldap_ddbOrg_SubBusinessCategory)) != null) {
                ConstEnumOrgSubSector vSubSector;
                NamingEnumeration<?> allSubSectors = attr.getAll();
                while (allSubSectors.hasMore()) {
                    try {
                        vSubSector = ConstEnumOrgSubSector.valueOf((String) allSubSectors.next());
                        vOrganisation.addSubSectors(vSubSector);
                    } catch (IllegalArgumentException ex) {
                        LOG.log(Level.WARNING, "Organisation-SubSector-Error: {0}", ex.getMessage());
                    }
                }
            }

            // -- Funding Agency
            vOrganisation.setFundingAgency((attr = attributes.get(Constants.ldap_ddbOrg_FundingAgency)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // Name der Einrichtung
            vOrganisation.setDisplayName((attr = attributes.get(Constants.ldap_ddbOrg_DisplayName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            // E-Mail
            vOrganisation.setEmail(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Email)) != null ? String.valueOf(attr.get())
                            : null);
            // Telefonnummer
            vOrganisation.setTel((attr = attributes.get(Constants.ldap_ddbOrg_TelephoneNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);
            // -- FAX
            vOrganisation.setFax((attr = attributes.get(Constants.ldap_ddbOrg_FaxNumber)) != null
                    ? String.valueOf(attr.get())
                    : null);

            // -- PLZ
            vOrganisation.getAddress()
                    .setPostalCode((attr = attributes.get(Constants.ldap_ddbOrg_PostalCode)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- City/Ortsname [l, localityName]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_LocalityName)) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("l")) != null) {
                vOrganisation.getAddress().setLocalityName(String.valueOf(attr.get()));
            }

            // -- HouseIdentifier
            vOrganisation.getAddress()
                    .setHouseIdentifier((attr = attributes.get(Constants.ldap_ddbOrg_HouseIdentifier)) != null
                            ? String.valueOf(attr.get())
                            : "");
            // -- Strasse
            vOrganisation.getAddress()
                    .setStreet((attr = attributes.get(Constants.ldap_ddbOrg_Street)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Bundesland [stateOrProvinceName, st]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_StateOrProvinceName)) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            } else if ((attr = attributes.get("st")) != null) {
                vOrganisation.getAddress().setStateOrProvinceName(String.valueOf(attr.get()));
            }

            // -- Land [countryName, c]
            if ((attr = attributes.get(Constants.ldap_ddbOrg_CountryName)) != null) {
                vOrganisation.getAddress().setCountryName(String.valueOf(attr.get()));
            }
            // -- AddressSuplement
            vOrganisation.getAddress()
                    .setAddressSuplement((attr = attributes.get(Constants.ldap_ddbOrg_AddressSuplement)) != null
                            ? String.valueOf(attr.get())
                            : "");

            // -- Geokoordinaten
            try {
                vOrganisation.getAddress()
                        .setLatitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLatitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLatitude-Error: {0}", ex.getMessage());
            }
            try {
                vOrganisation.getAddress()
                        .setLongitude((attr = attributes.get(Constants.ldap_ddbOrg_GeoLongitude)) != null
                                ? Double.valueOf(String.valueOf(attr.get()))
                                : 0.0);
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "GeoLongitude-Error: {0}", ex.getMessage());
            }
            vOrganisation.getAddress().setLocationDisplayName(
                    (attr = attributes.get(Constants.ldap_ddbOrg_LocationDisplayName)) != null
                            ? String.valueOf(attr.get())
                            : null);

            vOrganisation.setAbbreviation((attr = attributes.get(Constants.ldap_ddbOrg_Abbreviation)) != null
                    ? String.valueOf(attr.get())
                    : null);

            vOrganisation.setLegalStatus((attr = attributes.get(Constants.ldap_ddbOrg_LegalStatus)) != null
                    ? String.valueOf(attr.get())
                    : null);

            if ((attr = attributes.get(Constants.ldap_ddbOrg_URL)) != null) {
                NamingEnumeration<?> allURLs = attr.getAll();
                while (allURLs.hasMore()) {
                    vOrganisation.addURLs((String) allURLs.next());
                }
            }

            vOrganisation.setLogo(
                    (attr = attributes.get(Constants.ldap_ddbOrg_Logo)) != null ? String.valueOf(attr.get())
                            : null);

            // -- org-Status:
            //vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null ? String
            //  .valueOf(attr.get()) : "");
            try {
                vOrganisation.setStatus((attr = attributes.get(Constants.ldap_ddbOrg_Status)) != null
                        ? ConstEnumOrgStatus.valueOf(String.valueOf(attr.get()))
                        : ConstEnumOrgStatus.pending);
            } catch (IllegalArgumentException ex) {
                LOG.log(Level.WARNING, "Organisation-Status-Error: {0}", ex.getMessage());
                vOrganisation.setStatus(null);
            }

            vOrganisation.setCreatedBy((attr = attributes.get(Constants.ldap_ddb_CreatorsName)) != null
                    ? String.valueOf(attr.get())
                    : "");

            try { // createTimestamp-Error: For input string: "20120620142810Z"
                  // 1340205676692 - 20120620152116Z - 2012-06-20-15-21-16Z
                  // vOrganisation.setCreated( (attr = attributes.get(ddbOrg_CreateTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_CreateTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setCreated(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "createTimestamp-Error: {0}", ex.getMessage());
            }

            vOrganisation.setModifiedBy((attr = attributes.get(Constants.ldap_ddb_ModifiersName)) != null
                    ? String.valueOf(attr.get())
                    : "");
            try { // modifyTimestamp-Error: For input string: "20120620142810Z"
                  // vOrganisation.setModified( (attr = attributes.get(ddbOrg_ModifyTimestamp)) != null ?
                  // Long.valueOf(String.valueOf(attr.get())) : Long.valueOf(-1));
                if ((attr = attributes.get(Constants.ldap_ddb_ModifyTimestamp)) != null) {
                    vStr = String.valueOf(attr.get());
                    vOrganisation.setModified(convertLdapDateToLong(vStr));
                }
            } catch (NumberFormatException ex) {
                LOG.log(Level.WARNING, "modifyTimestamp-Error: {0}", ex.getMessage());
            }

            if ((attr = attributes.get(Constants.ldap_ddbOrg_Properties)) != null
                    && attributes.get(Constants.ldap_ddbOrg_Properties).get() != null) {
                vOrganisation.setProperties(serializer.deserialize((String) attr.get()));
            }

        } else {
            throw new NameNotFoundException();
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.SEVERE, null, ex);
        throw ex;
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    }
    return vOrganisation;
}

From source file:com.ignorelist.kassandra.steam.scraper.FileCache.java

@Override
public InputStream get(String key, Callable<? extends InputStream> valueLoader) throws ExecutionException {
    InputStream inputStream = getIfPresent(key);
    if (null != inputStream) {
        return inputStream;
    }/*www . j  ava 2  s. c  o  m*/
    final Lock writeLock = stripedLock.get(key).writeLock();
    writeLock.lock();
    try {
        inputStream = getIfPresentNonBlocking(key);
        if (null != inputStream) {
            return inputStream;
        }
        try {
            inputStream = valueLoader.call();
            try {
                putNonBlocking(key, inputStream);
                return getIfPresentNonBlocking(key);
            } catch (IOException ex) {
                Logger.getLogger(FileCache.class.getName()).log(Level.SEVERE, "failed to write cache file", ex);
                throw new ExecutionException("failed to load " + key, ex);
            }
        } catch (Exception e) {
            Logger.getLogger(FileCache.class.getName()).log(Level.SEVERE, null, e);
            throw new ExecutionException(e);
        }
    } finally {
        writeLock.unlock();
    }

}

From source file:org.openspaces.grid.gsm.containers.ContainersSlaUtils.java

static FutureGridServiceContainer startGridServiceContainerAsync(final InternalAdmin admin,
        final InternalGridServiceAgent gsa, final GridServiceContainerConfig config, final Log logger,
        final long duration, final TimeUnit timeUnit) {

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

    admin.scheduleAdminOperation(new Runnable() {
        public void run() {
            try {
                final OperatingSystemStatistics operatingSystemStatistics = gsa.getMachine()
                        .getOperatingSystem().getStatistics();

                // get total free system memory + cached (without sigar returns -1)
                long freeBytes = operatingSystemStatistics.getActualFreePhysicalMemorySizeInBytes();
                if (freeBytes <= 0) {
                    // fallback - no sigar. Provides a pessimistic number since does not take into
                    // account OS cache that can be allocated.
                    freeBytes = operatingSystemStatistics.getFreePhysicalMemorySizeInBytes();
                    if (freeBytes <= 0) {
                        // machine is probably going down.
                        ref.set(new AdminException("Cannot determine machine "
                                + machineToString(gsa.getMachine()) + " free memory."));
                    }//from  w w  w .  j  av a 2 s .  co  m
                }

                final long freeInMB = MemoryUnit.MEGABYTES.convert(freeBytes, MemoryUnit.BYTES);
                if (freeInMB < config.getMaximumJavaHeapSizeInMB()) {
                    ref.set(new AdminException("Machine " + machineToString(gsa.getMachine()) + " free memory "
                            + freeInMB + "MB is not enough to start a container with "
                            + config.getMaximumJavaHeapSizeInMB()
                            + "MB. Free machine memory or increase machine provisioning reservedMemoryPerMachine property."));
                } else {
                    ref.set(gsa.internalStartGridService(config));
                }
            } catch (AdminException e) {
                ref.set(e);
            } catch (Throwable e) {
                logger.error("Unexpected Exception " + e.getMessage(), e);
                ref.set(e);
            }
        }
    });

    FutureGridServiceContainer future = new FutureGridServiceContainer() {

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

        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 GridServiceContainer get() throws ExecutionException, IllegalStateException, TimeoutException {

            Object result = ref.get();

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

            GridServiceContainer container = null;
            if (result != null) {
                int agentId = (Integer) result;
                container = getGridServiceContainerInternal(agentId);
                //container could still be null if not discovered
            }

            if (container == null) {
                if (isTimedOut()) {
                    throw new TimeoutException("Starting a new container took more than "
                            + timeUnit.toSeconds(duration) + " seconds to complete.");
                }

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

            return container;

        }

        public boolean isDone() {
            Object result = ref.get();

            if (System.currentTimeMillis() > end) {
                return true;
            }

            if (result == null) {
                return false;
            }

            if (result instanceof Throwable) {
                return true;
            }

            GridServiceContainer container = getGridServiceContainerInternal((Integer) result);
            if (container != null) {
                return true;
            }

            return false;
        }

        public GridServiceContainer getGridServiceContainerInternal(int agentId) {
            for (GridServiceContainer container : admin.getGridServiceContainers()) {

                String agentUid = ((InternalGridServiceContainer) container).getAgentUid();
                if (agentUid != null && agentUid.equals(gsa.getUid())) {
                    if (agentId == container.getAgentId()) {
                        return container;
                    }
                }
            }
            return null;
        }

        public GridServiceAgent getGridServiceAgent() {
            return gsa;
        }

        public GridServiceContainerConfig getGridServiceContainerConfig() {
            return config;
        }

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

        @Override
        public int getAgentId() throws ExecutionException, TimeoutException {
            ExecutionException exception = getException();
            if (exception != null) {
                throw exception;
            }

            if (isTimedOut() && ref.get() == null) {
                throw new TimeoutException(
                        "Starting a new container on machine " + gsa.getMachine().getHostAddress()
                                + " took more than " + timeUnit.toSeconds(duration) + " seconds to complete.");
            }

            if (ref.get() == null) {
                throw new IllegalStateException("Async operation is not done yet.");
            }

            return (Integer) ref.get();
        }

        public boolean isStarted() {
            return ref.get() != null;
        }
    };

    return future;
}

From source file:org.grouplens.lenskit.util.parallel.TaskGraphManager.java

public synchronized void waitForFinished() throws ExecutionException, InterruptedException {
    while (!isFinished() && !threads.isEmpty()) {
        try {/*w  w w .  jav  a2  s  . c  o  m*/
            wait();
        } catch (InterruptedException ex) {
            for (Thread th : threads) {
                try {
                    th.join();
                } catch (InterruptedException ex2) {
                    logger.debug("interrupted waiting for interrupted thread to finish", ex2);
                }
            }
            if (!errors.isEmpty()) {
                throw new ExecutionException("thread in group " + name + " failed", errors.get(0).getRight());
            } else {
                throw ex;
            }
        }
    }
    if (!errors.isEmpty()) {
        throw new ExecutionException("thread in group " + name + " failed", errors.get(0).getRight());
    }
    if (!isFinished()) {
        // all threads terminated, but we aren't marked as finished
        logger.warn("threads terminated, but not finished - job problem?");
    }
}

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

static Collection<FutureStatelessProcessingUnitInstance> incrementNumberOfStatelessInstancesAsync(
        final ProcessingUnit pu, final GridServiceContainer[] containers, final Log logger, final long duration,
        final TimeUnit timeUnit) {

    if (pu.getMaxInstancesPerVM() != 1) {
        throw new IllegalArgumentException("Only one instance per VM is allowed");
    }/* www. j a v a2 s. c  o  m*/

    List<GridServiceContainer> unusedContainers = getUnusedContainers(pu, containers);

    final Admin admin = pu.getAdmin();
    final Map<GridServiceContainer, FutureStatelessProcessingUnitInstance> futureInstances = new HashMap<GridServiceContainer, FutureStatelessProcessingUnitInstance>();

    final AtomicInteger targetNumberOfInstances = new AtomicInteger(pu.getNumberOfInstances());

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

    for (GridServiceContainer container : unusedContainers) {
        final GridServiceContainer targetContainer = container;
        futureInstances.put(container, new FutureStatelessProcessingUnitInstance() {

            AtomicReference<Throwable> throwable = new AtomicReference<Throwable>();
            ProcessingUnitInstance newInstance;

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

            public boolean isDone() {

                end();

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

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

                end();

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

                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() {

                end();
                Throwable t = throwable.get();
                if (t != null) {
                    return new ExecutionException(t.getMessage(), t);
                }
                return null;
            }

            public GridServiceContainer getTargetContainer() {
                return targetContainer;
            }

            public ProcessingUnit getProcessingUnit() {
                return pu;
            }

            public String getFailureMessage() throws IllegalStateException {
                if (isTimedOut()) {
                    return "deployment timeout of processing unit " + pu.getName() + " on "
                            + gscToString(targetContainer);
                }

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

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

            private void end() {

                if (!targetContainer.isDiscovered()) {
                    throwable.set(new RemovedContainerProcessingUnitDeploymentException(pu, targetContainer));
                }

                else if (throwable.get() != null || newInstance != null) {
                    //do nothing. idempotent method
                }

                else {
                    incrementInstance();

                    ProcessingUnitInstance[] instances = targetContainer
                            .getProcessingUnitInstances(pu.getName());

                    if (instances.length > 0) {
                        newInstance = instances[0];
                    }
                }
            }

            private void incrementInstance() {
                final String uuid = "[incrementUid:" + UUID.randomUUID().toString() + "] ";
                int numberOfInstances = pu.getNumberOfInstances();
                int maxNumberOfInstances = getContainersOnMachines(pu).length;
                if (numberOfInstances < maxNumberOfInstances) {
                    if (targetNumberOfInstances.get() == numberOfInstances + 1) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Waiting for pu.numberOfInstances to increment from "
                                    + numberOfInstances + " to " + targetNumberOfInstances.get() + ". "
                                    + "Number of relevant containers " + maxNumberOfInstances);
                        }
                    } else if (admin.getGridServiceManagers().getSize() > 1
                            && !((InternalProcessingUnit) pu).isBackupGsmInSync()) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Waiting for backup gsm to sync with active gsm");
                        }
                    } else {
                        targetNumberOfInstances.set(numberOfInstances + 1);
                        if (logger.isInfoEnabled()) {
                            logger.info(uuid + " Planning to increment pu.numberOfInstances from "
                                    + numberOfInstances + " to " + targetNumberOfInstances.get() + ". "
                                    + "Number of relevant containers " + maxNumberOfInstances);
                        }
                        ((InternalAdmin) admin).scheduleAdminOperation(new Runnable() {
                            public void run() {
                                try {
                                    // this is an async operation 
                                    // pu.getNumberOfInstances() still shows the old value.
                                    pu.incrementInstance();
                                    if (logger.isInfoEnabled()) {
                                        logger.info(uuid + " pu.incrementInstance() called");
                                    }
                                } catch (AdminException e) {
                                    throwable.set(e);
                                } catch (Throwable e) {
                                    logger.error(uuid + " Unexpected Exception: " + e.getMessage(), e);
                                    throwable.set(e);
                                }
                            }
                        });
                    }
                }
            }
        });

    }

    return futureInstances.values();

}

From source file:co.cask.hydrator.plugin.batch.source.ExcelInputReader.java

@Override
public void transform(KeyValue<LongWritable, Object> input, Emitter<StructuredRecord> emitter)
        throws Exception {

    getOutputSchema();/*ww w .  jav a 2s. c om*/
    StructuredRecord.Builder builder = StructuredRecord.builder(outputSchema);
    String inputValue = input.getValue().toString();

    String[] excelRecords = inputValue.split("\t");

    String fileName = excelRecords[1];
    String sheetName = excelRecords[2];
    String ifEndRow = excelRecords[3];

    int prevRowNum = Integer.parseInt(excelRecords[0]);

    if (filePrevRowNumMap.containsKey(fileName)) {
        if (prevRowNum - filePrevRowNumMap.get(fileName) > 1
                && excelInputreaderConfig.terminateIfEmptyRow.equalsIgnoreCase("true")) {
            throw new ExecutionException(
                    "Encountered empty row while reading Excel file :" + fileName + " . Terminating processing",
                    new Throwable());
        }
    }

    filePrevRowNumMap.put(fileName, prevRowNum);

    Map<String, String> excelColumnValueMap = new HashMap<>();

    for (String columns : excelRecords) {
        String[] columnValueArray = columns.split("\r");
        if (columnValueArray.length > 1) {
            String columnName = columnValueArray[0];
            String columnValue = columnValueArray[1];

            if (columnMapping.containsKey(columnName)) {
                excelColumnValueMap.put(columnMapping.get(columnName), columnValue);
            } else {
                excelColumnValueMap.put(columnName, columnValue);
            }
        }
    }

    try {
        for (Schema.Field field : outputSchema.getFields()) {
            String fieldName = field.getName();
            if (excelColumnValueMap.containsKey(fieldName)) {
                builder.convertAndSet(fieldName, excelColumnValueMap.get(fieldName));
            } else {
                builder.set(fieldName, NULL);
            }
        }

        builder.set(FILE, new Path(fileName).getName());
        builder.set(SHEET, sheetName);

        if (ifEndRow.equalsIgnoreCase(END)) {
            trackProcessedFiles(fileName);
        }

        emitter.emit(builder.build());
    } catch (Exception e) {
        switch (excelInputreaderConfig.ifErrorRecord) {
        case EXIT_ON_ERROR:
            throw new IllegalStateException("Terminating processing on error : " + e.getMessage());
        case WRITE_ERROR_DATASET:
            StructuredRecord.Builder errorRecordBuilder = StructuredRecord.builder(errorRecordSchema);
            errorRecordBuilder.set(KEY, fileName + "_" + sheetName + "_" + excelRecords[0]);
            errorRecordBuilder.set(FILE, fileName);
            errorRecordBuilder.set(SHEET, sheetName);
            errorRecordBuilder.set(RECORD, inputValue);
            writeErrorRecordToDataset(errorRecordBuilder.build());
            break;
        default:
            //ignore on error
            break;
        }

    }

}

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

@Override
public FutureGridServiceAgent[] startMachinesAsync(final CapacityRequirements capacityRequirements,
        final ExactZonesConfig zones, final FailedGridServiceAgent[] failedAgents, final long duration,
        final TimeUnit unit) {

    if (!isStartMachineSupported()) {
        throw new UnsupportedOperationException();
    }//  w  w  w .  jav  a2 s .  co m

    final GSAReservationId reservationId = GSAReservationId.randomGSAReservationId();
    final CapacityRequirements singleMachineCapacity = machineProvisioning.getCapacityOfSingleMachine();
    int numberOfMachines = calcNumberOfMachines(capacityRequirements, machineProvisioning);
    if (numberOfMachines < failedAgents.length) {
        throw new IllegalArgumentException("capacity requirements should be at least " + failedAgents.length
                + " machines for failure recovery. " + "Instead found " + numberOfMachines
                + " machines, capacity = " + capacityRequirements);
    }
    FutureGridServiceAgent[] futureAgents = new FutureGridServiceAgent[numberOfMachines];

    for (int i = 0; i < futureAgents.length; i++) {
        final AtomicReference<Object> ref = new AtomicReference<Object>(null);

        final int throttlingDelay = i * THROTTLING_DELAY_SECONDS;
        final long start = System.currentTimeMillis();
        final long end = start + throttlingDelay * 1000 + unit.toMillis(duration);
        final FailedGridServiceAgent failedAgent = failedAgents.length > i ? failedAgents[i] : null;
        submit(new Runnable() {
            public void run() {
                try {
                    logger.info("Starting a new machine");
                    StartedGridServiceAgent agent = machineProvisioning.startMachine(zones, reservationId,
                            failedAgent, duration, unit);
                    ref.set(agent);
                    logger.info("New machine started");
                } 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.getMessage(), e);
                    ref.set(e);
                }
            }

        }, throttlingDelay, TimeUnit.SECONDS);

        futureAgents[i] = new FutureGridServiceAgent() {

            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 StartedGridServiceAgent 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 (StartedGridServiceAgent) result;
            }

            public NonBlockingElasticMachineProvisioning getMachineProvisioning() {
                return NonBlockingElasticMachineProvisioningAdapter.this;
            }

            public CapacityRequirements getFutureCapacity() {
                return singleMachineCapacity;
            }

            public GSAReservationId getReservationId() {
                return reservationId;
            }

            public FailedGridServiceAgent getFailedGridServiceAgent() {
                return failedAgent;
            }
        };
    }
    return futureAgents;
}