Example usage for java.lang IllegalStateException getCause

List of usage examples for java.lang IllegalStateException getCause

Introduction

In this page you can find the example usage for java.lang IllegalStateException 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:cherry.foundation.mail.MailDataHandlerImplTest.java

@Test
public void testTemplateEvaluationFalse() {
    MailDataHandler handler = create("name", "from@addr", null, null, null, null, "param=${model.param}",
            "param is ${model.param}", VelocityMode.MOCK_FALSE);
    Model model = new Model();
    model.setParam("PARAM");
    try {/*from w  ww  . j  a  va2 s .  c  o  m*/
        handler.createMailData("name", "to@addr", model);
        fail("Exception must be thrown");
    } catch (IllegalStateException ex) {
        assertNull(ex.getCause());
    }
}

From source file:org.sonar.server.db.ResultSetIteratorTest.java

@Test
public void fail_to_read_row() throws Exception {
    dbTester.prepareDbUnit(getClass(), "feed.xml");

    PreparedStatement stmt = connection.prepareStatement("select * from fake order by id");
    FailIterator iterator = new FailIterator(stmt);

    assertThat(iterator.hasNext()).isTrue();
    try {//from ww  w.  j a  v a 2 s.  c om
        iterator.next();
        fail();
    } catch (IllegalStateException e) {
        assertThat(e.getCause()).isInstanceOf(SQLException.class);
    }
    iterator.close();
}

From source file:org.t2framework.commons.util.LazyLoadingReference.java

public void test_exception() throws Exception {
        final Exception e = new Exception();
        LazyLoadingReference<String> target = new LazyLoadingReference<String>(
                new LazyLoadingReference.Factory<String>() {
                    public String create() throws Exception {
                        throw e;
                    }/*from  w ww.  j a  v a2 s  .  co m*/
                });
        try {
            target.get();
            fail();
        } catch (IllegalStateException t) {
            assertNotNull(t.getCause());
            assertTrue(t.getCause().getClass() == Exception.class);
            assertEquals(e, t.getCause());
        }
    }

From source file:org.etk.entity.engine.plugins.transaction.TransactionUtil.java

/** Rolls back transaction in the current thread IF transactions are available */
public static void rollback(Throwable causeThrowable) throws GenericTransactionException {
    UserTransaction ut = TransactionFactory.getUserTransaction();

    if (ut != null) {
        try {//from w  ww  .j a  v a 2 s  .co  m
            int status = ut.getStatus();
            logger.debug("[TransactionUtil.rollback] current status : " + getTransactionStateString(status));

            if (status != STATUS_NO_TRANSACTION) {
                // if (Debug.infoOn()) Thread.dumpStack();
                if (causeThrowable == null && logger.isInfoEnabled()) {
                    Exception newE = new Exception("Stack Trace");
                    logger.error("[TransactionUtil.rollback]");
                }

                // clear out the stamps to keep it clean
                clearTransactionStamps();
                // clear out the stack too
                clearTransactionBeginStack();
                clearSetRollbackOnlyCause();

                ut.rollback();
                logger.info("[TransactionUtil.rollback] transaction rolled back");
            } else {
                logger.warn(
                        "[TransactionUtil.rollback] transaction not rolled back, status is STATUS_NO_TRANSACTION");
            }
        } catch (IllegalStateException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not rollback transaction, IllegalStateException exception: " + t.toString(), t);
        } catch (SystemException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "System error, could not rollback transaction: " + t.toString(), t);
        }
    } else {
        logger.info("[TransactionUtil.rollback] No UserTransaction, transaction not rolled back");
    }
}

From source file:org.etk.entity.engine.plugins.transaction.TransactionUtil.java

/**
 * Makes a rollback the only possible outcome of the transaction in the
 * current thread IF transactions are available
 */// w w  w .j a v a  2 s. c o m
public static void setRollbackOnly(String causeMessage, Throwable causeThrowable)
        throws GenericTransactionException {
    UserTransaction ut = TransactionFactory.getUserTransaction();
    if (ut != null) {
        try {
            int status = ut.getStatus();
            logger.debug(
                    "[TransactionUtil.setRollbackOnly] current code : " + getTransactionStateString(status));

            if (status != STATUS_NO_TRANSACTION) {
                if (status != STATUS_MARKED_ROLLBACK) {
                    if (logger.isWarnEnabled()) {
                        logger.warn(
                                "[TransactionUtil.setRollbackOnly] Calling transaction setRollbackOnly; this stack trace shows where this is happening:",
                                new Exception(causeMessage));
                    }
                    ut.setRollbackOnly();
                    setSetRollbackOnlyCause(causeMessage, causeThrowable);
                } else {
                    logger.info(
                            "[TransactionUtil.setRollbackOnly] transaction rollback only not set, rollback only is already set.");
                }
            } else {
                logger.warn(
                        "[TransactionUtil.setRollbackOnly] transaction rollback only not set, status is STATUS_NO_TRANSACTION");
            }
        } catch (IllegalStateException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "Could not set rollback only on transaction, IllegalStateException exception: "
                            + t.toString(),
                    t);
        } catch (SystemException e) {
            Throwable t = e.getCause() == null ? e : e.getCause();
            throw new GenericTransactionException(
                    "System error, could not set rollback only on transaction: " + t.toString(), t);
        }
    } else {
        logger.info("[TransactionUtil.setRollbackOnly] No UserTransaction, transaction rollback only not set");
    }
}

From source file:com.puppycrawl.tools.checkstyle.utils.CommonUtilsTest.java

@Test
public void testGetNonExistingConstructor() {
    try {//ww w  .j  a va 2 s .  c  om
        CommonUtils.getConstructor(Math.class);
        fail();
    } catch (IllegalStateException expected) {
        assertSame(NoSuchMethodException.class, expected.getCause().getClass());
    }
}

From source file:com.puppycrawl.tools.checkstyle.utils.CommonUtilsTest.java

@SuppressWarnings("rawtypes")
@Test/*from w  w w . ja  v  a 2s. c o  m*/
public void testInvokeConstructorThatFails() throws NoSuchMethodException {
    Constructor<Dictionary> constructor = Dictionary.class.getConstructor();

    try {
        CommonUtils.invokeConstructor(constructor);
        fail();
    } catch (IllegalStateException expected) {
        assertSame(InstantiationException.class, expected.getCause().getClass());
    }
}

From source file:org.apache.tinkerpop.gremlin.hadoop.process.computer.giraph.GiraphGraphComputer.java

@Override
public int run(final String[] args) {
    this.giraphConfiguration.setBoolean(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES,
            this.persist.equals(Persist.EDGES));
    try {/*ww w . jav a2 s  . c o  m*/
        // it is possible to run graph computer without a vertex program (and thus, only map reduce jobs if they exist)
        if (null != this.vertexProgram) {
            // a way to verify in Giraph whether the traversal will go over the wire or not
            try {
                VertexProgram.createVertexProgram(this.hadoopGraph,
                        ConfUtil.makeApacheConfiguration(this.giraphConfiguration));
            } catch (IllegalStateException e) {
                if (e.getCause() instanceof NumberFormatException)
                    throw new NotSerializableException(
                            "The provided traversal is not serializable and thus, can not be distributed across the cluster");
            }
            // prepare the giraph vertex-centric computing job
            final GiraphJob job = new GiraphJob(this.giraphConfiguration,
                    Constants.GREMLIN_HADOOP_GIRAPH_JOB_PREFIX + this.vertexProgram);
            // handle input paths (if any)
            if (FileInputFormat.class.isAssignableFrom(this.giraphConfiguration
                    .getClass(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT, InputFormat.class))) {
                final Path inputPath = new Path(
                        this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_INPUT_LOCATION));
                if (!FileSystem.get(this.giraphConfiguration).exists(inputPath)) // TODO: what about when the input is not a file input?
                    throw new IllegalArgumentException("The provided input path does not exist: " + inputPath);
                FileInputFormat.setInputPaths(job.getInternalJob(), inputPath);
            }
            // handle output paths
            final Path outputPath = new Path(
                    this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION) + "/"
                            + Constants.HIDDEN_G);
            FileOutputFormat.setOutputPath(job.getInternalJob(), outputPath);
            job.getInternalJob().setJarByClass(GiraphGraphComputer.class);
            this.logger.info(Constants.GREMLIN_HADOOP_GIRAPH_JOB_PREFIX + this.vertexProgram);
            // execute the job and wait until it completes (if it fails, throw an exception)
            if (!job.run(true))
                throw new IllegalStateException(
                        "The GiraphGraphComputer job failed -- aborting all subsequent MapReduce jobs"); // how do I get the exception that occured?
            // add vertex program memory values to the return memory
            for (final String key : this.vertexProgram.getMemoryComputeKeys()) {
                final Path path = new Path(
                        this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION) + "/" + key);
                final ObjectWritableIterator iterator = new ObjectWritableIterator(this.giraphConfiguration,
                        path);
                if (iterator.hasNext()) {
                    this.memory.set(key, iterator.next().getValue());
                }
                FileSystem.get(this.giraphConfiguration).delete(path, true);
            }
            final Path path = new Path(this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION)
                    + "/" + Constants.HIDDEN_ITERATION);
            this.memory.setIteration(
                    (Integer) new ObjectWritableIterator(this.giraphConfiguration, path).next().getValue());
            FileSystem.get(this.giraphConfiguration).delete(path, true);
        }
        // do map reduce jobs
        this.giraphConfiguration.setBoolean(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT_HAS_EDGES,
                this.giraphConfiguration.getBoolean(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES,
                        true));
        for (final MapReduce mapReduce : this.mapReducers) {
            this.memory.addMapReduceMemoryKey(mapReduce);
            MapReduceHelper.executeMapReduceJob(mapReduce, this.memory, this.giraphConfiguration);
        }

        // if no persistence, delete the map reduce output
        if (this.persist.equals(Persist.NOTHING)) {
            final Path outputPath = new Path(
                    this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION) + "/"
                            + Constants.HIDDEN_G);
            if (FileSystem.get(this.giraphConfiguration).exists(outputPath)) // TODO: what about when the output is not a file output?
                FileSystem.get(this.giraphConfiguration).delete(outputPath, true);
        }
    } catch (final Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    return 0;
}

From source file:edu.umn.msi.tropix.common.logging.ExceptionUtilsTest.java

@Test(groups = "unit")
public void convert() {
    final IOException ioException = new FileNotFoundException();

    final RuntimeException re = ExceptionUtils.convertException(ioException, RuntimeException.class);
    assert re.getCause().equals(ioException);
    final IllegalStateException ie = ExceptionUtils.convertException(ioException, "Moo",
            IllegalStateException.class);
    assert ie.getCause().equals(ioException) && ie.getMessage().equals("Moo");
    final FileNotFoundException fe = ExceptionUtils.convertException(ioException, FileNotFoundException.class);
    assert fe == ioException;

    ExceptionUtils.ExceptionConversionException ee = null;
    try {//ww  w  .jav  a  2s  .c  o m
        ExceptionUtils.convertException(new Throwable(), NullPointerException.class);
    } catch (final ExceptionUtils.ExceptionConversionException iee) {
        ee = iee;
    }
    assert ee != null;
}

From source file:org.datacleaner.util.http.CASMonitorHttpClient.java

@Override
public HttpResponse execute(final HttpUriRequest request) throws Exception {
    // enable cookies
    final CookieStore cookieStore = new BasicCookieStore();
    final HttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    _httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    final String ticketGrantingTicket;
    try {/* w  w  w . j ava  2 s  . co m*/
        ticketGrantingTicket = _ticketGrantingTicketRef.get();
    } catch (IllegalStateException e) {
        if (e.getCause() instanceof SSLPeerUnverifiedException) {
            // Unverified SSL peer exceptions needs to be rethrown
            // specifically, since they can be caught and the user may
            // decide to remove certificate checks.
            throw (SSLPeerUnverifiedException) e.getCause();
        }
        throw e;
    }

    final String ticket = getTicket(_requestedService, _casRestServiceUrl, ticketGrantingTicket, context);
    logger.debug("Got a service ticket: {}", ticketGrantingTicket);
    logger.debug("Cookies 2: {}", cookieStore.getCookies());

    // now we request the spring security CAS check service, this will set
    // cookies on the client.
    final HttpGet cookieRequest = new HttpGet(_requestedService + "?ticket=" + ticket);
    final HttpResponse cookieResponse = executeHttpRequest(cookieRequest, context);
    EntityUtils.consume(cookieResponse.getEntity());
    cookieRequest.releaseConnection();
    logger.debug("Cookies 3: {}", cookieStore.getCookies());

    final HttpResponse result = executeHttpRequest(request, context);
    logger.debug("Cookies 4: {}", cookieStore.getCookies());

    return result;
}