Example usage for java.util.concurrent ExecutionException getCause

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

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.dcache.chimera.JdbcFs.java

@Override
public String inode2id(FsInode inode) throws ChimeraFsException {
    try {/*  w w  w.  j a  v a2  s.co m*/
        return _idCache.get(inode.ino(), () -> {
            String id = _sqlDriver.getId(inode);
            if (id == null) {
                throw new FileNotFoundHimeraFsException(String.valueOf(inode.ino()));
            }
            return id;
        });
    } catch (ExecutionException e) {
        Throwables.propagateIfInstanceOf(e.getCause(), ChimeraFsException.class);
        Throwables.propagateIfInstanceOf(e.getCause(), DataAccessException.class);
        throw Throwables.propagate(e.getCause());
    }
}

From source file:org.dcache.chimera.JdbcFs.java

@Override
public FsInode id2inode(String id, StatCacheOption option) throws ChimeraFsException {
    if (option == NO_STAT) {
        try {//from   w  ww.  j a  va  2s  . co m
            return new FsInode(this, _inoCache.get(id, () -> {
                Long ino = _sqlDriver.getInumber(id);
                if (ino == null) {
                    throw new FileNotFoundHimeraFsException(id);
                }
                return ino;
            }));
        } catch (ExecutionException e) {
            Throwables.propagateIfInstanceOf(e.getCause(), ChimeraFsException.class);
            Throwables.propagateIfInstanceOf(e.getCause(), DataAccessException.class);
            throw Throwables.propagate(e.getCause());
        }
    } else {
        Stat stat = _sqlDriver.stat(id);
        if (stat == null) {
            throw new FileNotFoundHimeraFsException(id);
        }
        _inoCache.put(stat.getId(), stat.getIno());
        _idCache.put(stat.getIno(), stat.getId());
        return new FsInode(this, stat.getIno(), FsInodeType.INODE, 0, stat);
    }
}

From source file:org.apache.bookkeeper.client.BookieWriteLedgerTest.java

/**
 * Verify that LedgerHandleAdv cannnot handle addEntry without the entryId.
 *
 * @throws Exception/*from w  w  w  .j  a v a2 s  .  c o m*/
 */
@Test
public void testNoAddEntryLedgerCreateAdv() throws Exception {

    ByteBuffer entry = ByteBuffer.allocate(4);
    entry.putInt(rng.nextInt(maxInt));
    entry.position(0);

    lh = bkc.createLedgerAdv(5, 3, 2, digestType, ledgerPassword);
    assertTrue(lh instanceof LedgerHandleAdv);

    try {
        lh.addEntry(entry.array());
        fail("using LedgerHandleAdv addEntry without entryId is forbidden");
    } catch (BKException e) {
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }

    try {
        lh.addEntry(entry.array(), 0, 4);
        fail("using LedgerHandleAdv addEntry without entryId is forbidden");
    } catch (BKException e) {
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }

    try {
        CompletableFuture<Object> done = new CompletableFuture<>();
        lh.asyncAddEntry(Unpooled.wrappedBuffer(entry.array()),
                (int rc, LedgerHandle lh1, long entryId, Object ctx) -> {
                    SyncCallbackUtils.finish(rc, null, done);
                }, null);
        done.get();
    } catch (ExecutionException ee) {
        assertTrue(ee.getCause() instanceof BKException);
        BKException e = (BKException) ee.getCause();
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }

    try {
        CompletableFuture<Object> done = new CompletableFuture<>();
        lh.asyncAddEntry(entry.array(), (int rc, LedgerHandle lh1, long entryId, Object ctx) -> {
            SyncCallbackUtils.finish(rc, null, done);
        }, null);
        done.get();
    } catch (ExecutionException ee) {
        assertTrue(ee.getCause() instanceof BKException);
        BKException e = (BKException) ee.getCause();
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }

    try {
        CompletableFuture<Object> done = new CompletableFuture<>();
        lh.asyncAddEntry(entry.array(), 0, 4, (int rc, LedgerHandle lh1, long entryId, Object ctx) -> {
            SyncCallbackUtils.finish(rc, null, done);
        }, null);
        done.get();
    } catch (ExecutionException ee) {
        assertTrue(ee.getCause() instanceof BKException);
        BKException e = (BKException) ee.getCause();
        assertEquals(e.getCode(), BKException.Code.IllegalOpException);
    }
    lh.close();
}

From source file:org.corpus_tools.pepper.core.PepperJobImpl.java

/**
 * Starts the conversion of this job./*from w w  w. j  ava2  s. co m*/
 * <ul>
 * <li>If the single steps of the job has not already been wired, they will
 * be wired.
 * <li>
 * <li>If {@link PepperImporter#importCorpusStructure(SCorpusGraph)} has not
 * already been called, it will be done.
 * <li>
 * </ul>
 */
public void convert() {
    if (!inProgress.tryLock()) {
        throw new PepperInActionException(
                "Cannot run convert() of job '" + getId() + "', since this job was already started.");
    }

    inProgress.lock();
    try {
        startTime = System.currentTimeMillis();
        status = JOB_STATUS.INITIALIZING;
        if (!isWired) {
            wire();
        }
        if (!isReadyToStart) {
            Collection<Pair<Step, Collection<String>>> notReadyModules = checkReadyToStart();
            if (notReadyModules.size() != 0) {
                StringBuilder str = new StringBuilder();
                for (Pair<Step, Collection<String>> problems : notReadyModules) {
                    str.append("[");
                    str.append(problems.getLeft());
                    str.append(": ");
                    str.append(problems.getRight());
                    str.append("], ");
                }
                throw new PepperException("Cannot run Pepper job '" + getId()
                        + "', because at least one of the involved jobs is not ready to run: '" + str.toString()
                        + "'. ");
            }
        }
        status = JOB_STATUS.IMPORTING_CORPUS_STRUCTURE;
        if (!isImportedCorpusStructure) {
            importCorpusStructures();
        }
        status = JOB_STATUS.IMPORTING_DOCUMENT_STRUCTURE;
        List<Pair<ModuleControllerImpl, Future<?>>> futures = new Vector<Pair<ModuleControllerImpl, Future<?>>>();
        // create a future for each step
        for (Step step : getAllSteps()) {
            if (step.getModuleController().getPepperModule().getSaltProject() == null)
                step.getModuleController().getPepperModule().setSaltProject(getSaltProject());
            {
                futures.add(new ImmutablePair<ModuleControllerImpl, Future<?>>(step.getModuleController(),
                        step.getModuleController().processDocumentStructures()));
            }
        }

        // log workflow information
        int stepNum = 0; // current number of step
        StringBuilder str = new StringBuilder();
        for (Step step : getAllSteps()) {
            stepNum++;
            str.append("+----------------------------------- step ");
            str.append(stepNum);
            str.append(" -----------------------------------+\n");

            String format = "|%-15s%-63s|\n";
            str.append(
                    String.format(format, step.getModuleType().toString().toLowerCase() + ":", step.getName()));
            str.append(String.format(format, "path:", step.getCorpusDesc().getCorpusPath()));
            if (MODULE_TYPE.IMPORTER.equals(step.getModuleType())) {
                int idxCorpusGraph = getSaltProject().getCorpusGraphs().indexOf(
                        ((PepperImporter) step.getModuleController().getPepperModule()).getCorpusGraph());
                str.append(String.format(format, "corpus index:", idxCorpusGraph));
            }

            boolean hasProperties = false;
            StringBuilder propStr = new StringBuilder();
            if (step.getModuleController().getPepperModule().getProperties()
                    .getPropertyDesctriptions() != null) {
                // log all properties of all modules and their values

                format = "|               %-25s%-38s|\n";
                for (PepperModuleProperty<?> prop : step.getModuleController().getPepperModule().getProperties()
                        .getPropertyDesctriptions()) {
                    if (prop.getValue() != null) {
                        hasProperties = true;
                        propStr.append(String.format(format, prop.getName() + ":", prop.getValue()));
                    }
                }
            }
            format = "|%-15s%-63s|\n";
            if (hasProperties) {
                str.append(String.format(format, "properties:", ""));
                str.append(propStr.toString());
            } else {
                str.append(String.format(format, "properties:", "- none -"));
            }
            str.append("|                                                                              |\n");
        }
        str.append("+------------------------------------------------------------------------------+\n");
        logger.info(str.toString());

        for (Pair<ModuleControllerImpl, Future<?>> future : futures) {
            // wait until all document-structures have been imported
            try {
                future.getRight().get();
            } catch (ExecutionException e) {
                if ((e.getCause() != null) && (e.getCause() instanceof PepperException)) {
                    throw (PepperException) e.getCause();
                }
                throw new PepperModuleException("Failed to process document by module '" + future.getLeft()
                        + "'. Nested exception was: ", e.getCause());
            } catch (InterruptedException e) {
                if ((e.getCause() != null) && (e.getCause() instanceof PepperException)) {
                    throw (PepperException) e.getCause();
                }
                throw new PepperFWException("Failed to process document by module '" + future.getLeft()
                        + "'. Nested exception was: ", e.getCause());
            } catch (CancellationException e) {
                if ((e.getCause() != null) && (e.getCause() instanceof PepperException)) {
                    throw (PepperException) e.getCause();
                }
                throw new PepperFWException("Failed to process document by module '" + future.getLeft()
                        + "'. Nested exception was: ", e.getCause());
            }
        }
        status = JOB_STATUS.ENDED;
    } catch (RuntimeException e) {
        status = JOB_STATUS.ENDED_WITH_ERRORS;
        if (e instanceof PepperException) {
            throw (PepperException) e;
        } else {
            throw new PepperFWException(
                    "An exception occured in job '" + getId()
                            + "' while importing the corpus-structure. See nested exception: " + e.getMessage(),
                    e);
        }
    } finally {
        inProgress.unlock();
    }
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Locate the current alert for the provided service and alert name. This
 * method will first consult the cache if configured with
 * {@link Configuration#isAlertCacheEnabled()}.
 *
 * @param clusterId/* w w  w. ja  v a 2  s .c  o m*/
 *          the cluster id
 * @param hostName
 *          the name of the host (not {@code null}).
 * @param alertName
 *          the name of the alert (not {@code null}).
 * @return the current record, or {@code null} if not found
 */
public AlertCurrentEntity findCurrentByHostAndName(long clusterId, String hostName, String alertName) {

    if (m_configuration.isAlertCacheEnabled()) {
        AlertCacheKey key = new AlertCacheKey(clusterId, alertName, hostName);

        try {
            return m_currentAlertCache.get(key);
        } catch (ExecutionException executionException) {
            Throwable cause = executionException.getCause();
            if (!(cause instanceof AlertNotYetCreatedException)) {
                LOG.warn("Unable to retrieve alert for key {} from the cache", key);
            }
        }
    }

    return findCurrentByHostAndNameInJPA(clusterId, hostName, alertName);
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Locate the current alert for the provided service and alert name, but when
 * host is not set ({@code IS NULL}). This method will first consult the cache
 * if configured with {@link Configuration#isAlertCacheEnabled()}.
 *
 * @param clusterId/*from w ww.  j  av  a  2s .  c  o  m*/
 *          the cluster id
 * @param alertName
 *          the name of the alert
 * @return the current record, or {@code null} if not found
 */
public AlertCurrentEntity findCurrentByNameNoHost(long clusterId, String alertName) {
    if (m_configuration.isAlertCacheEnabled()) {
        AlertCacheKey key = new AlertCacheKey(clusterId, alertName);

        try {
            return m_currentAlertCache.get(key);
        } catch (ExecutionException executionException) {
            Throwable cause = executionException.getCause();

            if (!(cause instanceof AlertNotYetCreatedException)) {
                LOG.warn("Unable to retrieve alert for key {} from, the cache", key);
            }
        }
    }

    return findCurrentByNameNoHostInternalInJPA(clusterId, alertName);
}

From source file:org.corpus_tools.pepper.core.PepperJobImpl.java

/**
 * Imports corpus structures of all registered
 * {@link ImportCorpusStructureTest} steps. After calling
 * {@link PepperImporter#importCorpusStructure(SCorpusGraph)} , all
 * following modules will be asked, if they want to influence the order of
 * importing documents. If this is the case, an order is created and put to
 * all {@link PepperImporter} objects. <br/>
 * This method produces as much as {@link SCorpusGraph} objects as
 * {@link Step} given in import step list {@link #getImportSteps()}. The
 * position of {@link SCorpusGraph} corresponding to {@link PepperImporter}
 * (importing that graph) in {@link SaltProject#getCorpusGraphs()} is
 * equivalent to position of {@link Step} in list {@link #getImportSteps()}.
 *///from ww  w  . j  av a  2s .c o  m
protected synchronized void importCorpusStructures() {
    try {
        if (!isWired) {
            wire();
        }
        List<Future<?>> futures = new Vector<Future<?>>();
        int numOfImportStep = 0;
        for (Step importStep : getImportSteps()) {
            if (getSaltProject() == null) {
                throw new PepperFWException("Cannot import corpus structure, because no salt project is set.");
            }
            SCorpusGraph sCorpusGraph = null;

            if ((getSaltProject().getCorpusGraphs().size() > numOfImportStep)
                    && (getSaltProject().getCorpusGraphs().get(numOfImportStep) != null)) {
                sCorpusGraph = getSaltProject().getCorpusGraphs().get(numOfImportStep);
            } else {
                sCorpusGraph = SaltFactory.createSCorpusGraph();
                getSaltProject().addCorpusGraph(sCorpusGraph);
            }

            futures.add(importStep.getModuleController().importCorpusStructure(sCorpusGraph));
            numOfImportStep++;
        }
        for (Future<?> future : futures) {
            // wait until all corpus structures have been imported
            try {
                future.get();
            } catch (ExecutionException e) {
                throw new PepperModuleException("Failed to import corpus by module. Nested exception was: ",
                        e.getCause());
            } catch (InterruptedException e) {
                throw new PepperFWException("Failed to import corpus by module. Nested exception was: ",
                        e.getCause());
            } catch (CancellationException e) {
                throw new PepperFWException("Failed to import corpus by module. Nested exception was: ",
                        e.getCause());
            }
        }
        int i = 0;
        for (Step step : getImportSteps()) {
            if (getSaltProject().getCorpusGraphs().get(i) == null) {
                throw new PepperModuleException("The importer '" + step.getModuleController().getPepperModule()
                        + "' did not import a corpus structure.");
            }

            // handle proposed import order
            List<Identifier> importOrder = unifyProposedImportOrders(getSaltProject().getCorpusGraphs().get(i));
            for (Identifier sDocumentId : importOrder) {
                DocumentControllerImpl documentController = new DocumentControllerImpl();
                SDocument sDoc = (SDocument) sDocumentId.getIdentifiableElement();
                if (sDoc.getDocumentGraph() == null) {
                    sDoc.setDocumentGraph(SaltFactory.createSDocumentGraph());
                }
                documentController.setDocument(sDoc);
                // sets flag to determine whether garbage collector should
                // be called after document was send to sleep
                if (getConfiguration() != null) {
                    documentController.setCallGC(getConfiguration().getGcAfterDocumentSleep());
                }
                getDocumentControllers().add(documentController);
                File docFile = null;
                String prefix = sDoc.getName();
                File tmpPath = new File(getConfiguration().getWorkspace().getAbsolutePath() + "/" + getId());
                if (!tmpPath.exists()) {
                    if (!tmpPath.mkdirs()) {
                        logger.warn("Cannot create folder {}. ", tmpPath);
                    }
                }
                try {
                    if (prefix.length() < 3) {
                        prefix = prefix + "artificial";
                    }
                    docFile = File.createTempFile(prefix, "." + SaltUtil.FILE_ENDING_SALT_XML, tmpPath);
                } catch (IOException e) {
                    throw new PepperFWException(
                            "Cannot store document '" + sDoc.getName() + "' to file '" + docFile
                                    + "' in folder for temporary files '" + tmpPath + "'. " + e.getMessage(),
                            e);
                }
                documentController.setLocation(URI.createFileURI(docFile.getAbsolutePath()));
                if (!getConfiguration().getKeepDocuments()) {
                    docFile.deleteOnExit();
                }

                initialDocumentBuses.get(i).put(documentController);
                // notify document controller about all modules in workflow
                documentController.addModuleControllers(step.getModuleController());
                for (Step manipulationStep : getManipulationSteps()) {
                    documentController.addModuleControllers(manipulationStep.getModuleController());
                }
                for (Step exportStep : getExportSteps()) {
                    documentController.addModuleControllers(exportStep.getModuleController());
                }
            }
            initialDocumentBuses.get(i).finish(InitialDocumentBus.ID_INTITIAL);
            i++;
        }
        isImportedCorpusStructure = true;
    } catch (RuntimeException e) {
        if (e instanceof PepperException) {
            throw (PepperException) e;
        } else {
            throw new PepperFWException("An exception occured in job '" + getId()
                    + "' while importing the corpus-structure. See nested exception: ", e);
        }
    }
}

From source file:mzb.Balancer.java

private long dispatchBlockMoves() throws InterruptedException {
    long bytesLastMoved = bytesMoved.get();
    try {//from ww w  .j  a v a 2s  .c o m
        Future<?>[] futures = new Future<?>[sources.size()];
        int i = 0;

        for (Source source : sources) {
            futures[i++] = dispatcherExecutor.submit(source.new BlockMoveDispatcher());
        }

        // wait for all dispatcher threads to finish
        for (Future<?> future : futures) {
            try {
                future.get();
            } catch (ExecutionException e) {
                LOG.warn("Dispatcher thread failed", e.getCause());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error("no move! QAQ");
        System.exit(0);
    }
    // wait for all block moving to be done
    waitForMoveCompletion();

    return bytesMoved.get() - bytesLastMoved;
}

From source file:de.fu_berlin.inf.dpp.net.internal.StreamServiceManager.java

/**
 * Try to establish a new session./*from  ww  w. jav  a 2  s . c  o m*/
 * 
 * @threadsafe
 * @blocking
 * 
 * @param service
 *            service used for the session to be created
 * @param user
 *            start a session with
 * @param initiationDescription
 *            is passed to
 *            {@link StreamService#sessionRequest(User, Object)} at
 *            receiver's side, which is an optional description for the
 *            kind/purpose of this session. Can be <code>null</code>.
 * @param sessionListener
 *            Will be added to created session. Can be <code>null</code>.
 * @param timeout
 *            Cancel negotiation after given seconds.
 * @return A started session
 * @throws IllegalArgumentException
 *             when given {@link StreamService} is not found.
 * @throws TimeoutException
 *             Timeout reached, negotiation canceled.
 * @throws RemoteCancellationException
 *             Receiver rejected initiation-request.
 * @throws ExecutionException
 *             Unknown error happened during negotiation.
 * @throws InterruptedException
 *             Interrupted while negotiating.
 * @throws ConnectionException
 *             Not connected and can't send any data.
 */
public StreamSession createSession(StreamService service, User user, Serializable initiationDescription,
        StreamSessionListener sessionListener, int timeout) throws TimeoutException,
        RemoteCancellationException, ExecutionException, InterruptedException, ConnectionException {
    if (!registeredServices.containsKey(service.getServiceName()))
        throw new IllegalArgumentException("Tried to create a stream with unregistered service " + service);
    int initiationID = nextStreamSessionID.getAndIncrement();

    StreamPath streamPath = new StreamPath(saros.getMyJID(), service, initiationID);

    if (initiationDescription != null) {
        byte[] serializedInitial = Utils.serialize(initiationDescription);
        if (serializedInitial == null)
            log.warn("Given serializable is not serializable! " + initiationDescription);
    }

    // holder for result
    Initiation initiation = new Initiation(service, initiationID, initiationDescription, streamPath,
            sessionListener);

    // store initiation
    initiations.put(streamPath, initiation);
    // send negotiation
    TransferDescription transferDescription = TransferDescription.createStreamMetaTransferDescription(
            user.getJID(), saros.getMyJID(), streamPath.toString(), sarosSessionID.getValue());

    if (sender != null)
        sender.sendPacket(transferDescription, StreamMetaPacketData.INIT.serializeInto(initiationDescription),
                SubMonitor.convert(new NullProgressMonitor()));
    else
        throw new ConnectionException();

    Future<StreamSession> initiationProcess = negotiations.submit(initiation);

    StreamSession session;
    try {
        session = initiationProcess.get(timeout, TimeUnit.SECONDS);
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof RemoteCancellationException) {
            RemoteCancellationException remoteCancellationException = (RemoteCancellationException) cause;
            throw remoteCancellationException;
        }
        log.error("Unknown error during negotiation: ", e.getCause());
        throw e;
    } finally {
        initiations.remove(streamPath);
    }

    return session;
}

From source file:org.openspaces.grid.gsm.machines.DefaultMachinesSlaEnforcementEndpoint.java

@Override
public void cleanupCloud(ProcessingUnit pu, NonBlockingElasticMachineProvisioning machineProvisioning)
        throws MachinesSlaEnforcementInProgressException {
    if (state.getCleanupFuture(pu) == null) {
        FutureCleanupCloudResources future = machineProvisioning
                .cleanupCloudResources(CLEANUP_CLOUD_TIMEOUT_SECONDS, TimeUnit.SECONDS);
        state.setCleanupFuture(pu, future);
    }/*from   w w  w .j  a va 2 s  .  c  o  m*/

    FutureCleanupCloudResources future = state.getCleanupFuture(pu);

    if (!future.isDone()) {
        throw new MachinesSlaEnforcementInProgressException(getProcessingUnit(),
                "Cloud cleanup is in progress");
    }
    Exception exception = null;
    try {
        future.get();
    } catch (ExecutionException e) {
        // if runtime or error propagate exception "as-is"
        Throwable cause = e.getCause();
        if (cause instanceof TimeoutException || cause instanceof ElasticMachineProvisioningException
                || cause instanceof InterruptedException) {
            // expected exception
            exception = e;
        } else {
            throw new IllegalStateException("Unexpected Exception from machine provisioning.", e);
        }
    } catch (TimeoutException e) {
        // expected exception
        exception = e;
    }

    if (exception != null && !future.isMarked()) {
        future.mark(); // throw exception only once, complete undeployment even though there was one failure.
        throw new CloudCleanupFailedException(pu, exception);
    }
}