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.openhab.binding.darksky.internal.connection.DarkSkyConnection.java

private String getResponse(String url) {
    try {/*w w w. j  av a  2s.  co m*/
        if (logger.isTraceEnabled()) {
            logger.trace("Dark Sky request: URL = '{}'", uglifyApikey(url));
        }
        ContentResponse contentResponse = httpClient.newRequest(url).method(GET).timeout(10, TimeUnit.SECONDS)
                .send();
        int httpStatus = contentResponse.getStatus();
        String content = contentResponse.getContentAsString();
        logger.trace("Dark Sky response: status = {}, content = '{}'", httpStatus, content);
        switch (httpStatus) {
        case OK_200:
            return content;
        case BAD_REQUEST_400:
        case UNAUTHORIZED_401:
        case NOT_FOUND_404:
            logger.debug("Dark Sky server responded with status code {}: {}", httpStatus, content);
            throw new DarkSkyConfigurationException(content);
        default:
            logger.debug("Dark Sky server responded with status code {}: {}", httpStatus, content);
            throw new DarkSkyCommunicationException(content);
        }
    } catch (ExecutionException e) {
        String errorMessage = e.getLocalizedMessage();
        logger.trace("Exception occurred during execution: {}", errorMessage, e);
        if (e.getCause() instanceof HttpResponseException) {
            logger.debug("Dark Sky server responded with status code {}: Invalid API key.", UNAUTHORIZED_401);
            throw new DarkSkyConfigurationException("@text/offline.conf-error-invalid-apikey", e.getCause());
        } else {
            throw new DarkSkyCommunicationException(errorMessage, e.getCause());
        }
    } catch (InterruptedException | TimeoutException e) {
        logger.debug("Exception occurred during execution: {}", e.getLocalizedMessage(), e);
        throw new DarkSkyCommunicationException(e.getLocalizedMessage(), e.getCause());
    }
}

From source file:org.apache.http.impl.conn.JMeterPoolingClientConnectionManager.java

ManagedClientConnection leaseConnection(final Future<HttpPoolEntry> future, final long timeout,
        final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
    final HttpPoolEntry entry;
    try {/*  w  ww . jav a  2s.co m*/
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return new ManagedClientConnectionImpl(this, this.operator, entry);
    } catch (final ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        this.log.error("Unexpected exception leasing connection from pool", cause);
        // Should never happen
        throw new InterruptedException();
    } catch (final TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}

From source file:org.openengsb.connector.maven.internal.MavenServiceImpl.java

private String readResultFromFuture(Future<String> future) throws InterruptedException {
    String result;//from  w  w  w.  j  a v  a 2s. c o  m
    try {
        result = future.get();
    } catch (ExecutionException e) {
        log.error(e.getCause());
        result = ExceptionUtils.getFullStackTrace(e);
    }
    return result;
}

From source file:org.codice.ddf.parser.xml.XmlParser.java

private JAXBContext getContext(List<String> contextPath, ClassLoader loader) throws ParserException {
    String joinedPath = CTX_JOINER.join(contextPath);

    JAXBContext jaxbContext;/*from w w w . ja  va 2  s . c om*/

    try {
        jaxbContext = jaxbContextCache.get(new CacheKey(joinedPath, loader));
    } catch (ExecutionException e) {
        LOGGER.error("Unable to create JAXB context using context path: {}", joinedPath, e);
        throw new ParserException("Unable to create XmlParser", e.getCause());
    }

    return jaxbContext;
}

From source file:annis.gui.QueryController.java

private boolean checkFutureCount() {
    try {//w w w  .j a  v  a 2s. co  m
        lastCount = futureCount.get(100, TimeUnit.MILLISECONDS);
        String documentString = lastCount.getDocumentCount() > 1 ? "documents" : "document";
        String matchesString = lastCount.getMatchCount() > 1 ? "matches" : "match";

        ui.getControlPanel().getQueryPanel().setStatus("" + lastCount.getMatchCount() + " " + matchesString
                + " <br/>in " + lastCount.getDocumentCount() + " " + documentString);
        if (lastResultView != null && lastCount.getMatchCount() > 0) {
            lastResultView.setCount(lastCount.getMatchCount());
        }

    } catch (InterruptedException ex) {
        log.warn(null, ex);
    } catch (ExecutionException root) {
        Throwable cause = root.getCause();

        if (cause instanceof UniformInterfaceException) {
            UniformInterfaceException ex = (UniformInterfaceException) cause;
            if (ex.getResponse().getStatus() == 400) {
                Notification.show("parsing error", ex.getResponse().getEntity(String.class),
                        Notification.Type.WARNING_MESSAGE);
            } else if (ex.getResponse().getStatus() == 504) // gateway timeout
            {
                Notification.show("Timeout: query execution took too long.",
                        "Try to simplyfiy your query e.g. by replacing \"node\" with an annotation name or adding more constraints between the nodes.",
                        Notification.Type.WARNING_MESSAGE);
            } else {
                Notification.show("unknown error " + ex.getResponse().getStatus(),
                        ex.getResponse().getEntity(String.class), Notification.Type.WARNING_MESSAGE);
            }
        } else {
            log.error("Unexcepted ExecutionException cause", root);
        }
    } catch (TimeoutException ex) {
        // we ignore this
        return false;
    }

    futureCount = null;
    ui.getControlPanel().getQueryPanel().setCountIndicatorEnabled(false);
    return true;
}

From source file:com.anrisoftware.prefdialog.miscswing.docks.dockingframes.core.DockingFramesDock.java

private void doSaveLayout(String name, OutputStream stream, PropertyChangeListener... listeners)
        throws LayoutException {
    try {//from  www.j  av  a2 s .  co  m
        SwingWorker<OutputStream, OutputStream> worker = saveFactory.create(layoutListeners, this, name,
                control, stream);
        for (PropertyChangeListener l : listeners) {
            worker.addPropertyChangeListener(l);
        }
        worker.execute();
        worker.get();
    } catch (ExecutionException e) {
        throw new LayoutSavingException(name, e.getCause());
    } catch (InterruptedException e) {
        throw new LayoutInterruptedException(name, e);
    }

}

From source file:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticleTest.java

@Test
public void testEventLogRepository_getEventCount() throws Exception {
    final Vertx vertx = vertxService.getVertx();
    final RunRightFastVerticleId verticleId = EventLogRepository.VERTICLE_ID;

    final long timeout = 60000L;

    final ProtobufMessageProducer<GetEventCount.Request> getEventCountMessageProducer = new ProtobufMessageProducer<>(
            vertx.eventBus(), EventBusAddress.eventBusAddress(verticleId, GetEventCount.class),
            new ProtobufMessageCodec<>(GetEventCount.Request.getDefaultInstance()), metricRegistry);

    // because the verticles are deployed asynchronously, the EventLogRepository verticle may not yet be deployed yet
    // the message consumer for the Verticle only gets registered, while the verticle is starting. Thus, the message consumer may not yet be registered.
    while (true) {
        final CompletableFuture<GetEventCount.Response> getEventCountFuture = new CompletableFuture<>();
        getEventCountMessageProducer.send(GetEventCount.Request.getDefaultInstance(),
                responseHandler(getEventCountFuture, GetEventCount.Response.class));
        try {/*from w ww. ja  v  a2  s .  co  m*/
            getEventCountFuture.get(timeout, TimeUnit.MILLISECONDS);
            break;
        } catch (final ExecutionException e) {
            if (e.getCause() instanceof ReplyException) {
                final ReplyException replyException = (ReplyException) e.getCause();
                if (replyException.failureType() == NO_HANDLERS) {
                    log.log(WARNING, "Waiting for EventLogRepository ... ", e);
                    Thread.sleep(5000L);
                    continue;
                }
            }
            throw e;
        }
    }
}

From source file:at.salzburgresearch.kmt.zkconfig.ZookeeperConfiguration.java

@Override
public Object getProperty(String key) {
    try {//from w  w  w . j  a v a  2  s  . c  o  m
        return cache.get(toZookeeperPath(key));
    } catch (ExecutionException e) {
        if (e.getCause() instanceof KeeperException
                && ((KeeperException) e.getCause()).code() == KeeperException.Code.NONODE) {
            return null;
        }
        log.error("Could not load property {}: {}", key, e);
    }
    return null;
}

From source file:com.rapidminer.operator.learner.tree.SelectionCreator.java

/**
 * Creates in parallel an example index start selection for each numerical attribute, or if
 * there is none, only one./* ww w.  j a  va 2s . c om*/
 *
 * @param operator
 *            the operator for which the calculation is done
 * @return a map containing for each numerical attribute an example index array such that the
 *         associated attribute values are in ascending order.
 * @throws OperatorException
 */
public Map<Integer, int[]> getStartSelectionParallel(Operator operator) throws OperatorException {
    Map<Integer, int[]> selection = new HashMap<>();
    if (columnTable.getNumberOfRegularNumericalAttributes() == 0) {
        selection.put(0, createFullArray(columnTable.getNumberOfExamples()));
    } else {
        List<Callable<int[]>> tasks = new ArrayList<Callable<int[]>>();
        final Integer[] bigSelectionArray = createFullBigArray(columnTable.getNumberOfExamples());
        for (int j = columnTable.getNumberOfRegularNominalAttributes(); j < columnTable
                .getTotalNumberOfRegularAttributes(); j++) {
            final double[] attributeColumn = columnTable.getNumericalAttributeColumn(j);
            tasks.add(new Callable<int[]>() {

                @Override
                public int[] call() {
                    Integer[] startSelection = Arrays.copyOf(bigSelectionArray, bigSelectionArray.length);
                    Arrays.sort(startSelection, new Comparator<Integer>() {

                        @Override
                        public int compare(Integer a, Integer b) {
                            return Double.compare(attributeColumn[a], attributeColumn[b]);
                        }
                    });
                    return ArrayUtils.toPrimitive(startSelection);
                }

            });
        }

        List<int[]> results = null;
        try {
            results = Resources.getConcurrencyContext(operator).call(tasks);
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else if (cause instanceof Error) {
                throw (Error) cause;
            } else {
                throw new OperatorException(cause.getMessage(), cause);
            }
        }

        for (int j = columnTable.getNumberOfRegularNominalAttributes(); j < columnTable
                .getTotalNumberOfRegularAttributes(); j++) {
            selection.put(j, results.get(j - columnTable.getNumberOfRegularNominalAttributes()));
        }
    }
    return selection;
}

From source file:com.netflix.spinnaker.clouddriver.cloudfoundry.client.Applications.java

@Nullable
public CloudFoundryServerGroup findById(String guid) {
    return safelyCall(() -> {
        try {//from w ww  . j  av  a  2  s .  co m
            return serverGroupCache.get(guid);
        } catch (ExecutionException e) {
            if (e.getCause() instanceof ResourceNotFoundException) {
                return null;
            }
            throw new CloudFoundryApiException(e.getCause(), "Unable to find server group by id");
        }
    }).orElse(null);
}