Example usage for java.lang RuntimeException getCause

List of usage examples for java.lang RuntimeException getCause

Introduction

In this page you can find the example usage for java.lang RuntimeException 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:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java

private void searchIndexByScoreBlocking(String fieldName, String indexName, Double min, Double max,
        Integer offset, Integer limit, AsyncResultHandler<List<String>> resultHandler) {
    redissonOther//  w  w w .j  a v a 2s  . co  m
            .<String>getScoredSortedSet(getScoredSortedIndexKey(fieldName, indexName), StringCodec.INSTANCE)
            .valueRangeAsync(min, true, max, true, offset, limit).addListener(future -> {
                Collection<String> res = (Collection<String>) future.get();
                try {
                    ArrayList<String> ids = res.stream().map(r -> lookupIdFromIndex(r, fieldName, indexName))
                            .collect(Collectors.toCollection(ArrayList::new));
                    resultHandler
                            .handle(future.isSuccess()
                                    ? (future.get() != null || ids == null ? Future.succeededFuture(ids)
                                            : Future.failedFuture(
                                                    new RepositoryException("No search result returned")))
                                    : Future.failedFuture(new RepositoryException(future.cause())));
                    if (future.isSuccess()) {
                        logger.debug("[" + getStorageKey() + "] Search Index By Score Success. Records: "
                                + ((Collection<String>) future.get()).size());
                    } else {
                        logger.debug("[" + getStorageKey() + "] Search Index By Score Failure.",
                                future.cause());
                    }
                } catch (RuntimeException e) {
                    resultHandler.handle(Future.failedFuture(e.getCause()));
                    logger.debug("[" + getStorageKey() + "] Search Index By Score Failure.", e);
                }
            });
}

From source file:ponzu.impl.test.Verify.java

/**
 * Runs the {@link Runnable} {@code code} and asserts that it throws an {@code Exception} of the type
 * {@code expectedExceptionClass}, which contains a cause of type expectedCauseClass.
 * <p/>//  w  w  w.  j  av a 2s  .  c o m
 * {@code Runnable} is most appropriate when a subclass of {@link RuntimeException} will be thrown.
 * If a checked exception will be thrown, the form {@link #assertThrowsWithCause(Class, Class, Callable)}
 * may be more convenient.
 * <p/>
 * <p/>
 * e.g.
 * <pre>
 * Verify.assertThrowsWithCause(RuntimeException.class, StringIndexOutOfBoundsException.class, new Runnable()
 * {
 *    public void run()
 *    {
 *        try
 *        {
 *            LOGGER.info("Craig".substring(42, 3));
 *        }
 *        catch (final StringIndexOutOfBoundsException e)
 *        {
 *            throw new RuntimeException("Uh oh!", e);
 *        }
 *    }
 * });
 * </pre>
 *
 * @see #assertThrowsWithCause(Class, Class, Callable)
 */
public static void assertThrowsWithCause(Class<? extends Exception> expectedExceptionClass,
        Class<? extends Throwable> expectedCauseClass, Runnable code) {
    try {
        code.run();
    } catch (RuntimeException ex) {
        try {
            Assert.assertSame("Caught exception of type <" + ex.getClass().getName()
                    + ">, expected one of type <" + expectedExceptionClass.getName() + '>',
                    expectedExceptionClass, ex.getClass());
            Throwable actualCauseClass = ex.getCause();
            Assert.assertNotNull("Caught exception with null cause, expected cause of type <"
                    + expectedCauseClass.getName() + '>', actualCauseClass);
            Assert.assertSame(
                    "Caught exception with cause of type<" + actualCauseClass.getClass().getName()
                            + ">, expected cause of type <" + expectedCauseClass.getName() + '>',
                    expectedCauseClass, actualCauseClass.getClass());
            return;
        } catch (AssertionError e) {
            throwMangledException(e);
        }
    }

    try {
        Assert.fail("Block did not throw an exception of type " + expectedExceptionClass.getName());
    } catch (AssertionError e) {
        throwMangledException(e);
    }
}

From source file:it.cnr.icar.eric.client.ui.thin.RegistryObjectBean.java

/**
 * Change the current ExternalURI for ExternalLink
 * @param none// ww w.  j a  v  a  2s. com
 * @return none
 */
public void changeExternalURI() {
    RegistryObject ro = this.registryObject;
    try {
        if (externalURI != null && externalURI.trim().length() >= 0) {
            ((ExternalLinkImpl) ro).setExternalURI(externalURI);
        } else if (this.externalURI == null && ro instanceof ExternalLinkImpl) {
            ((ExternalLinkImpl) ro).setExternalURI(((ExternalLinkImpl) ro).getExternalURI());
        }
    } catch (NullPointerException nep) {
        setRegistryObjectErrorMessage(WebUIResourceBundle.getInstance().getString("nullExternalURIError"));
        String errMsg = WebUIResourceBundle.getInstance().getString("changeExternalURIError");
        log.error(errMsg + " " + nep.getMessage());
    } catch (java.lang.RuntimeException re) {
        if (re.getCause() instanceof IllegalArgumentException) {
            setRegistryObjectErrorMessage(
                    WebUIResourceBundle.getInstance().getString("illegalExternalURIError"));
        }
        String errMsg = WebUIResourceBundle.getInstance().getString("changeExternalURIError");
        log.error(errMsg + " " + re.getMessage());
    } catch (Exception ex) {
        setRegistryObjectErrorMessage("ExternalURI " + ex.getMessage());
        String errMsg = WebUIResourceBundle.getInstance().getString("changeExternalURIError");
        log.error(errMsg + " " + ex.getMessage());

    }
}

From source file:eu.stratosphere.pact.compiler.PactCompiler.java

private OptimizerPostPass getPostPassFromPlan(Plan pactPlan) {
    final String className = pactPlan.getPostPassClassName();
    if (className == null) {
        throw new CompilerException("Optimizer Post Pass class description is null");
    }//from   w w  w  .j  a  va  2  s  .  com
    try {
        Class<? extends OptimizerPostPass> clazz = Class.forName(className).asSubclass(OptimizerPostPass.class);
        try {
            return InstantiationUtil.instantiate(clazz, OptimizerPostPass.class);
        } catch (RuntimeException rtex) {
            // unwrap the source exception
            if (rtex.getCause() != null) {
                throw new CompilerException("Cannot instantiate optimizer post pass: " + rtex.getMessage(),
                        rtex.getCause());
            } else {
                throw rtex;
            }
        }
    } catch (ClassNotFoundException cnfex) {
        throw new CompilerException("Cannot load Optimizer post-pass class '" + className + "'.", cnfex);
    } catch (ClassCastException ccex) {
        throw new CompilerException("Class '" + className + "' is not an optimizer post passer.", ccex);
    }
}

From source file:eu.stratosphere.compiler.PactCompiler.java

private OptimizerPostPass getPostPassFromPlan(Plan program) {
    final String className = program.getPostPassClassName();
    if (className == null) {
        throw new CompilerException("Optimizer Post Pass class description is null");
    }// www. j av a2s .  c o m
    try {
        Class<? extends OptimizerPostPass> clazz = Class.forName(className).asSubclass(OptimizerPostPass.class);
        try {
            return InstantiationUtil.instantiate(clazz, OptimizerPostPass.class);
        } catch (RuntimeException rtex) {
            // unwrap the source exception
            if (rtex.getCause() != null) {
                throw new CompilerException("Cannot instantiate optimizer post pass: " + rtex.getMessage(),
                        rtex.getCause());
            } else {
                throw rtex;
            }
        }
    } catch (ClassNotFoundException cnfex) {
        throw new CompilerException("Cannot load Optimizer post-pass class '" + className + "'.", cnfex);
    } catch (ClassCastException ccex) {
        throw new CompilerException("Class '" + className + "' is not an optimizer post passer.", ccex);
    }
}

From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.java

private boolean receiveAndExecute(final BlockingQueueConsumer consumer) throws Throwable {

    if (this.transactionManager != null) {
        try {//from w  w  w . j  a  va2  s  .  c  o m
            return new TransactionTemplate(this.transactionManager, this.transactionAttribute)
                    .execute(new TransactionCallback<Boolean>() {
                        @Override
                        public Boolean doInTransaction(TransactionStatus status) {
                            ConnectionFactoryUtils.bindResourceToTransaction(
                                    new RabbitResourceHolder(consumer.getChannel(), false),
                                    getConnectionFactory(), true);
                            try {
                                return doReceiveAndExecute(consumer);
                            } catch (RuntimeException e) {
                                throw e;
                            } catch (Throwable e) { //NOSONAR
                                // ok to catch Throwable here because we re-throw it below
                                throw new WrappedTransactionException(e);
                            }
                        }
                    });
        } catch (WrappedTransactionException e) {
            throw e.getCause();
        }
    }

    return doReceiveAndExecute(consumer);

}

From source file:org.dswarm.graph.resources.GDMResource.java

@POST
@Path("/put")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response writeGDM(final InputStream inputStream, @Context final GraphDatabaseService database,
        @Context final HttpHeaders requestHeaders) throws DMPGraphException, IOException {

    LOG.debug("try to process GDM statements and write them into graph db");

    final String headers = readHeaders(requestHeaders);

    GDMResource.LOG.debug("try to process GDM statements and write them into graph db with\n{}", headers);

    if (inputStream == null) {

        final String message = "input stream for write to graph DB request is null";

        GDMResource.LOG.error(message);//www  .j  a  v a 2  s . c  o  m

        throw new DMPGraphException(message);
    }

    final BufferedInputStream bis = new BufferedInputStream(inputStream, 1024);

    final ModelParser modelParser = new ModelParser(bis);
    final Observable<Resource> model = modelParser.parse();

    LOG.debug("try to write GDM statements into graph db");

    final TransactionHandler tx = new Neo4jTransactionHandler(database);
    final NamespaceIndex namespaceIndex = new NamespaceIndex(database, tx);
    final GDMNeo4jProcessor processor = new SimpleGDMNeo4jProcessor(database, tx, namespaceIndex);

    try {

        final GDMHandler handler = new SimpleGDMNeo4jHandler(processor, true);
        final GDMParser parser = new GDMModelParser(model);
        parser.setGDMHandler(handler);
        final Observable<Boolean> processedResources = parser.parse();

        try {

            final Iterator<Boolean> iterator = processedResources.toBlocking().getIterator();

            if (!iterator.hasNext()) {

                LOG.debug("model contains no resources, i.e., nothing needs to be written to the DB");
            }

            while (iterator.hasNext()) {

                iterator.next();
            }
        } catch (final RuntimeException e) {

            throw new DMPGraphException(e.getMessage(), e.getCause());
        }

        handler.getHandler().closeTransaction();

        bis.close();
        inputStream.close();

        LOG.debug(
                "finished writing {} resources with {} GDM statements (added {} relationships, added {} nodes (resources + bnodes + literals), added {} literals) into graph db",
                parser.parsedResources(), handler.getHandler().getCountedStatements(),
                handler.getHandler().getRelationshipsAdded(), handler.getHandler().getNodesAdded(),
                handler.getHandler().getCountedLiterals());
    } catch (final Exception e) {

        processor.getProcessor().failTx();

        bis.close();
        inputStream.close();

        LOG.error("couldn't write GDM statements into graph db: {}", e.getMessage(), e);

        throw e;
    }

    return Response.ok().build();
}

From source file:com.datatorrent.lib.io.fs.AbstractFileOutputOperatorTest.java

@Test
public void validateNegativeMaxLengthTest() {
    ValidationTestApp validationTestApp = new ValidationTestApp(new File(testMeta.getDir()), -1L,
            new SingleHDFSByteExactlyOnceWriter());

    boolean error = false;

    try {//ww w. j  ava2 s . co m
        LocalMode.runApp(validationTestApp, 1);
    } catch (RuntimeException e) {
        if (e.getCause() instanceof ConstraintViolationException) {
            error = true;
        }
    }

    Assert.assertEquals("Max length validation not thrown with -1 max length", true, error);
}