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:org.candlepin.client.CLIMain.java

protected void handleClientException(RuntimeException e, BaseCommand cmd) {
    L.error("Unable to execute cmd : " + cmd.getName(), e);
    if (e.getCause() != null) {
        if (e.getCause().getClass() == java.net.ConnectException.class) {
            System.out.println("Error connecting to " + config.getServerURL());
            return;
        }/* w  w w.j  a v  a  2  s  . co  m*/
    }
    System.err.println("Unable to execute " + cmd.getName() + " command.");
    if (StringUtils.isNotEmpty(e.getMessage())) {
        System.err.println("Reason: " + e.getMessage());
    }
}

From source file:org.sonar.api.config.AesCipherTest.java

@Test
public void decrypt_other_key() throws Exception {
    URL resource = getClass().getResource("/org/sonar/api/config/AesCipherTest/other_secret_key.txt");
    Settings settings = new Settings();
    settings.setProperty(CoreProperties.ENCRYPTION_SECRET_KEY_PATH,
            new File(resource.toURI()).getCanonicalPath());
    AesCipher cipher = new AesCipher(settings);

    try {// w w w .ja v a  2 s .  c  o  m
        // text encrypted with another key
        cipher.decrypt("9mx5Zq4JVyjeChTcVjEide4kWCwusFl7P2dSVXtg9IY=");
        fail();

    } catch (RuntimeException e) {
        assertThat(e.getCause(), is(BadPaddingException.class));
    }
}

From source file:org.obiba.opal.rest.client.magma.RestDatasource.java

@Override
public void initialise() {
    try {/*from   w  w  w  .  ja v  a2  s.c  o m*/
        super.initialise();
    } catch (RuntimeException e) {
        if (e.getCause() instanceof ConnectException) {
            log.error("Failed connecting to Opal server: {}", e.getMessage(), e);
        } else {
            log.error("Unexpected error while communicating with Opal server: {}", e.getMessage(), e);
        }
        throw new MagmaRuntimeException(e.getMessage(), e);
    }
}

From source file:org.opendaylight.controller.filtervalve.cors.jaxb.ParserTest.java

@Test
public void testConflictingClass() throws Exception {
    File xmlFile = new File(getClass().getResource("/conflicting-class.xml").getFile());
    assertThat(xmlFile.canRead(), is(true));
    String xmlFileContent = FileUtils.readFileToString(xmlFile);
    try {/*from   www  . j  a va  2  s. co m*/
        Parser.parse(xmlFileContent, "fileName");
        fail();
    } catch (RuntimeException e) {
        assertThat(e.getMessage(),
                containsString("Error while processing filter CorsFilter of context /restconf"));
        assertThat(e.getCause().getMessage(), containsString(
                "Conflict detected in template/filter filter-class definitions, filter name: CorsFilter"));
    }
}

From source file:com.proofpoint.http.server.TestHttpServerProvider.java

@Test
public void testHttpIsDisabled() throws Exception {
    config.setHttpEnabled(false);/*w  ww.  java  2s . co  m*/

    createServer();
    server.start();

    HttpClient client = new ApacheHttpClient(
            new HttpClientConfig().setConnectTimeout(new Duration(2.0, TimeUnit.SECONDS)));
    try {
        StatusResponse response = client.execute(
                prepareGet().setUri(httpServerInfo.getHttpUri().resolve("/")).build(),
                createStatusResponseHandler());

        if (response != null) { // TODO: this is a workaround for a bug in AHC (some race condition)
            fail("Expected connection refused, got response code: " + response.getStatusCode());
        }
    } catch (RuntimeException e) {
        assertTrue(e.getCause() instanceof ConnectException,
                e.getCause().getClass() + " instanceof ConnectException");
    }
}

From source file:org.apache.hadoop.hive.metastore.TUGIBasedProcessor.java

@SuppressWarnings("unchecked")
@Override/*from   w w w.  ja  v  a  2s .c om*/
public boolean process(final TProtocol in, final TProtocol out) throws TException {
    setIpAddress(in);

    final TMessage msg = in.readMessageBegin();
    final ProcessFunction<Iface, ? extends TBase> fn = functions.get(msg.name);
    if (fn == null) {
        TProtocolUtil.skip(in, TType.STRUCT);
        in.readMessageEnd();
        TApplicationException x = new TApplicationException(TApplicationException.UNKNOWN_METHOD,
                "Invalid method name: '" + msg.name + "'");
        out.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid));
        x.write(out);
        out.writeMessageEnd();
        out.getTransport().flush();
        return true;
    }
    TUGIContainingTransport ugiTrans = (TUGIContainingTransport) in.getTransport();
    // Store ugi in transport if the rpc is set_ugi
    if (msg.name.equalsIgnoreCase("set_ugi")) {
        try {
            handleSetUGI(ugiTrans, (set_ugi<Iface>) fn, msg, in, out);
        } catch (TException e) {
            throw e;
        } catch (Exception e) {
            throw new TException(e.getCause());
        }
        return true;
    }
    UserGroupInformation clientUgi = ugiTrans.getClientUGI();
    if (null == clientUgi) {
        // At this point, transport must contain client ugi, if it doesn't then its an old client.
        fn.process(msg.seqid, in, out, iface);
        return true;
    } else { // Found ugi, perform doAs().
        PrivilegedExceptionAction<Void> pvea = new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() {
                try {
                    fn.process(msg.seqid, in, out, iface);
                    return null;
                } catch (TException te) {
                    throw new RuntimeException(te);
                }
            }
        };
        try {
            clientUgi.doAs(pvea);
            return true;
        } catch (RuntimeException rte) {
            if (rte.getCause() instanceof TException) {
                throw (TException) rte.getCause();
            }
            throw rte;
        } catch (InterruptedException ie) {
            throw new RuntimeException(ie); // unexpected!
        } catch (IOException ioe) {
            throw new RuntimeException(ioe); // unexpected!
        } finally {
            try {
                FileSystem.closeAllForUGI(clientUgi);
            } catch (IOException e) {
                LOG.error("Could not clean up file-system handles for UGI: " + clientUgi, e);
            }
        }
    }
}

From source file:org.commonjava.cartographer.graph.spi.neo4j.FileNeo4jConnectionFactory.java

@Override
public synchronized RelationshipGraphConnection openConnection(final String workspaceId, final boolean create)
        throws RelationshipGraphConnectionException {
    final File db = new File(dbBaseDirectory, workspaceId);
    if (!db.exists()) {
        if (!create) {
            throw new RelationshipGraphConnectionException("Workspace does not exist: %s.", workspaceId);
        } else if (!db.mkdirs()) {
            throw new RelationshipGraphConnectionException(
                    "Failed to create workspace directory for: %s. (dir: %s)", workspaceId, db);
        }//from   w  ww. j  a  v a2s. com
        //
        //            try
        //            {
        //                Thread.sleep( 20 );
        //            }
        //            catch ( final InterruptedException e )
        //            {
        //                Thread.currentThread()
        //                      .interrupt();
        //                return null;
        //            }
    }

    FileNeo4JGraphConnection conn = openConnections.get(workspaceId);
    if (conn == null || !conn.isOpen()) {
        conn = null;
        int attempt = 0;

        while (conn == null) {
            attempt++;
            try {
                conn = new FileNeo4JGraphConnection(workspaceId, db, useShutdownHook, storageBatchSize, this);
            } catch (RuntimeException ex) {
                if (ex.getCause() instanceof LifecycleException
                        && ex.getCause().getCause() instanceof StoreLockException
                        && ex.getCause().getCause().getCause() instanceof OverlappingFileLockException
                        && attempt < 3) {
                    logger.warn("Tried to connect to DB which is not closed (yet). {} Retrying in 5s.",
                            ex.toString());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ez) {
                        logger.error("The wait delay was interrupted.", ex);
                    }
                } else {
                    throw ex;
                }
            }
        }

        openConnections.put(workspaceId, conn);
    }

    return conn;
}

From source file:org.intermine.web.logic.session.SessionMethods.java

/**
 * Executes an action and call a callback when it completes successfully. If the
 * query fails for some reason, this method returns false and ActionErrors are set on the
 * request.//from  w w w  . ja  v  a2  s  .c om
 *
 * @param session   the http session
 * @param resources message resources
 * @param qid       the query id
 * @param action    the action/query to perform in a new thread
 * @param completionCallBack sets the method to call when the action successfully completes
 * @return  true if query ran successfully, false if an error occured
 * @throws  Exception if getting results info from paged results fails
 */
public static boolean runQuery(final HttpSession session, final MessageResources resources, final String qid,
        final Action action, final CompletionCallBack completionCallBack) throws Exception {
    final InterMineAPI im = getInterMineAPI(session);
    final ObjectStore os = im.getObjectStore();

    final ObjectStoreInterMineImpl ios;
    if (os instanceof ObjectStoreInterMineImpl) {
        ios = (ObjectStoreInterMineImpl) os;
    } else {
        ios = null;
    }
    Map<String, QueryMonitor> queries = getRunningQueries(session);
    QueryMonitor monitor = queries.get(qid);
    // A reference to this runnable is used as a token for registering
    // a cancelling the running query

    RunQueryThread runnable = new RunQueryThread() {
        @Override
        public void run() {
            try {

                // Register request id for query on this thread
                // We do this before setting r
                if (ios != null) {
                    LOG.debug("Registering request id " + this);
                    ios.registerRequestId(this);
                }

                // call this so that if an exception occurs we notice now rather than in the
                // JSP code
                try {
                    action.process();
                } catch (IndexOutOfBoundsException err) {
                    // no results - ignore
                    // we don't call size() first to avoid this exception because that could be
                    // very slow on a large results set
                } catch (RuntimeException e) {
                    if (e.getCause() instanceof ObjectStoreException) {
                        throw (ObjectStoreException) e.getCause();
                    }
                    throw e;
                }
            } catch (ObjectStoreException e) {
                // put stack trace in the log
                LOG.error("Exception", e);

                String key = (e instanceof ObjectStoreQueryDurationException)
                        ? "errors.query.estimatetimetoolong"
                        : "errors.query.objectstoreerror";
                recordError(resources.getMessage(key), session);

                error = true;
            } catch (Throwable err) {
                StringWriter sw = new StringWriter();
                err.printStackTrace(new PrintWriter(sw));
                recordError(sw.toString(), session);
                LOG.error("Exception", err);
                error = true;
            } finally {
                try {
                    LOG.debug("Deregistering request id " + this);
                    ((ObjectStoreInterMineImpl) os).deregisterRequestId(this);
                } catch (ObjectStoreException e1) {
                    LOG.error("Exception", e1);
                    error = true;
                }
            }
        }
    };
    Thread thread = null;
    thread = new Thread(runnable);
    thread.start();

    while (thread.isAlive()) {
        Thread.sleep(1000);
        if (monitor != null) {
            boolean cancelled = monitor.shouldCancelQuery();
            if (cancelled && ios != null) {
                LOG.debug("Cancelling request " + runnable);
                ios.cancelRequest(runnable);
                monitor.queryCancelled();
                return false;
            }
        }
    }

    if (runnable.isError()) {
        if (monitor != null) {
            monitor.queryCancelledWithError();
        }
        return false;
    }

    if (completionCallBack != null) {
        completionCallBack.complete();
    }

    if (monitor != null) {
        monitor.queryCompleted();
    }

    return true;
}

From source file:com.ns.retailmgr.controller.exception.RestControllerExceptionHandler.java

protected ResponseEntity<Object> handleRunTimeException(RuntimeException ex, HttpHeaders headers,
        HttpStatus status, WebRequest request) {
    status = HttpStatus.INTERNAL_SERVER_ERROR;
    Throwable mostSpecificCause = ex.getCause();
    RestErrorMessage RestErrorMessage;/*from  w w  w  . j ava 2s.  c om*/
    if (mostSpecificCause != null) {
        String exceptionName = mostSpecificCause.getClass().getName();
        String message = mostSpecificCause.getMessage();
        RestErrorMessage = new RestErrorMessage(exceptionName, message);
    } else {
        RestErrorMessage = new RestErrorMessage(ex.getMessage());
    }
    return new ResponseEntity(RestErrorMessage, headers, status);
}

From source file:com.gisgraphy.webapp.action.DisplayStreetAction.java

@Override
public String execute() throws Exception {
    try {//from   w w  w.j ava 2  s.c  o m
        if (StringUtils.isEmpty(gid)) {
            errorRef = ERROR_REF_REQUIRED_FEATURE_ID;
            return ERROR;
        }
        if (!isNumeric(gid)) {
            errorRef = ERROR_REF_NON_NUMERIC_FEATUREID;
            return ERROR;
        }
        result = openStreetMapDao.getByGid(Long.valueOf(gid));
        if (result == null) {
            errorRef = ERROR_REF_NORESULT;
            return ERROR;
        } else {
            this.shape = retrieveShape(result.getGid());
        }
    } catch (RuntimeException e) {
        if (e.getCause() != null) {
            logger.warn("An error occured during search : " + e.getCause().getMessage());
        } else {
            logger.warn("An error occured during search : " + e.getMessage());
        }
        this.errorRef = ERROR_REF_GENERAL_ERROR;
        this.errorMessage = e.getMessage();
        return ERROR;
    }
    return SUCCESS;
}