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.jajuk.base.TestDevice.java

/**
 * Test method for {@link org.jajuk.base.Device#refresh(boolean)}.
 *
 * @throws Exception the exception/* w w w . j  av  a2 s.co  m*/
 */
public void testRefreshBoolean() throws Exception {
    Device device = TestHelpers.getDevice();
    try {
        device.refresh(false, false, false, null);
    } catch (RuntimeException e) {
        // there can be a hidden HeadlessException here
        assertTrue(e.getCause().getMessage(), e.getCause() instanceof InvocationTargetException);
    }
    device.refresh(true, false, false, null);
}

From source file:org.jajuk.base.TestDevice.java

/**
 * Test method for {@link org.jajuk.base.Device#refresh(boolean, boolean)}.
 *
 * @throws Exception the exception/* w w  w  .j  a  va 2  s  .c  o m*/
 */
public void testRefreshBooleanBoolean() throws Exception {
    Device device = TestHelpers.getDevice();
    try {
        device.refresh(false, false, false, null);
    } catch (RuntimeException e) {
        // there can be a hidden HeadlessException here
        assertTrue(e.getCause().getMessage(), e.getCause() instanceof InvocationTargetException);
    }
    device.refresh(true, false, false, null);
}

From source file:org.everrest.websockets.client.WSClient.java

/**
 * Connect to remote server./*from   w w w  .j av  a2s .c o m*/
 *
 * @param timeout
 *         connection timeout value in seconds
 * @throws IOException
 *         if connection failed
 * @throws IllegalArgumentException
 *         if <code>timeout</code> zero or negative
 */
public synchronized void connect(long timeout) throws IOException {
    if (timeout < 1) {
        throw new IllegalArgumentException(String.format("Invalid timeout: %d", timeout));
    }

    if (connected) {
        throw new IOException("Already connected.");
    }

    try {
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    int port = target.getPort();
                    if (port == -1) {
                        port = 80;
                    }
                    socket = new Socket(target.getHost(), port);
                    in = socket.getInputStream();
                    out = socket.getOutputStream();
                    out.write(getHandshake());
                    validateResponseHeaders();
                    inputBuffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
                    connected = true;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).get(timeout, TimeUnit.SECONDS); // Wait for connection.
    } catch (InterruptedException e) {
        //
        throw new IOException(e.getMessage(), e);
    } catch (ExecutionException e) {
        // It is RuntimeException for sure.
        RuntimeException re = (RuntimeException) e.getCause();
        Throwable cause = re.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw re;
    } catch (TimeoutException e) {
        // Connection time out reached.
        throw new SocketTimeoutException("Connection timeout. ");
    } finally {
        if (!connected) {
            executor.shutdown();
        }
    }

    // Start reading from socket.
    executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                read();
            } catch (ConnectionException e) {
                LOG.error(e.getMessage(), e);
                onClose(e.status, e.getMessage());
            } catch (Exception e) {
                // All unexpected errors represents as protocol error, status: 1002.
                LOG.error(e.getMessage(), e);
                onClose(1002, e.getMessage());
            }
        }
    });

    // Notify listeners about connection open.
    onOpen();
}

From source file:org.fcrepo.http.api.FedoraLdp.java

/**
 * Update an object using SPARQL-UPDATE// w w  w .  j  av a 2 s. com
 *
 * @param requestBodyStream the request body stream
 * @return 201
 * @throws MalformedRdfException if malformed rdf exception occurred
 * @throws AccessDeniedException if exception updating property occurred
 * @throws IOException if IO exception occurred
 */
@PATCH
@Consumes({ contentTypeSPARQLUpdate })
@Timed
public Response updateSparql(@ContentLocation final InputStream requestBodyStream)
        throws IOException, MalformedRdfException, AccessDeniedException {

    if (null == requestBodyStream) {
        throw new BadRequestException("SPARQL-UPDATE requests must have content!");
    }

    if (resource() instanceof FedoraBinary) {
        throw new BadRequestException(resource() + " is not a valid object to receive a PATCH");
    }

    try {
        final String requestBody = IOUtils.toString(requestBodyStream);
        if (isBlank(requestBody)) {
            throw new BadRequestException("SPARQL-UPDATE requests must have content!");
        }

        evaluateRequestPreconditions(request, servletResponse, resource(), session);

        final RdfStream resourceTriples;

        if (resource().isNew()) {
            resourceTriples = new DefaultRdfStream(asNode(resource()));
        } else {
            resourceTriples = getResourceTriples();
        }

        LOGGER.info("PATCH for '{}'", externalPath);
        patchResourcewithSparql(resource(), requestBody, resourceTriples);

        session.save();

        addCacheControlHeaders(servletResponse, resource(), session);

        return noContent().build();
    } catch (final IllegalArgumentException iae) {
        throw new BadRequestException(iae.getMessage());
    } catch (final RuntimeException ex) {
        final Throwable cause = ex.getCause();
        if (cause instanceof PathNotFoundException) {
            // the sparql update referred to a repository resource that doesn't exist
            throw new BadRequestException(cause.getMessage());
        }
        throw ex;
    } catch (final RepositoryException e) {
        if (e instanceof AccessDeniedException) {
            throw new AccessDeniedException(e.getMessage());
        }
        throw new RepositoryRuntimeException(e);
    }
}

From source file:de.unioninvestment.eai.portal.portlet.crud.domain.model.AbstractDataContainer.java

public void replaceFilters(List<Filter> newFilters, boolean removeDurable, boolean forceReplace) {
    List<Filter> replacementFilters = newFilters;
    if (!removeDurable) {
        replacementFilters = collectDurableFilters(filterList);
        replacementFilters.addAll(newFilters);
    }/*from w w  w  . j  a va 2  s .c om*/
    if (forceReplace || !replacementFilters.equals(filterList)) {
        if (shouldFilterNothing(replacementFilters)) {
            replaceVaadinFilters(asList((Filter) new Nothing()));
        } else {
            try {
                replaceVaadinFilters(replacementFilters);
            } catch (RuntimeException e) {
                if (e.getCause() instanceof SQLTimeoutException) {
                    applyNothingFilter(removeDurable);
                    throw new BusinessException("portlet.crud.warn.searchQueryTimeout");
                } else {
                    throw e;
                }
            }
        }
        filterList = replacementFilters;
    }
}

From source file:net.dv8tion.jda.core.entities.impl.JDAImpl.java

public void verifyToken() throws LoginException, RateLimitedException {
    RestAction<JSONObject> login = new RestAction<JSONObject>(this, Route.Self.GET_SELF.compile()) {
        @Override//from  ww  w. j  av  a 2s.  c om
        protected void handleResponse(Response response, Request<JSONObject> request) {
            if (response.isOk())
                request.onSuccess(response.getObject());
            else if (response.isRateLimit())
                request.onFailure(new RateLimitedException(request.getRoute(), response.retryAfter));
            else if (response.code == 401)
                request.onSuccess(null);
            else
                request.onFailure(new LoginException(
                        "When verifying the authenticity of the provided token, Discord returned an unknown response:\n"
                                + response.toString()));
        }
    };

    JSONObject userResponse;
    try {
        userResponse = login.complete(false);
    } catch (RuntimeException e) {
        //We check if the LoginException is masked inside of a ExecutionException which is masked inside of the RuntimeException
        Throwable ex = e.getCause() != null ? e.getCause().getCause() : null;
        if (ex instanceof LoginException)
            throw (LoginException) ex;
        else
            throw e;
    }

    if (userResponse != null) {
        verifyToken(userResponse);
    } else {
        //If we received a null return for userResponse, then that means we hit a 401.
        // 401 occurs we attempt to access the users/@me endpoint with the wrong token prefix.
        // e.g: If we use a Client token and prefix it with "Bot ", or use a bot token and don't prefix it.
        // It also occurs when we attempt to access the endpoint with an invalid token.
        //The code below already knows that something is wrong with the token. We want to determine if it is invalid
        // or if the developer attempted to login with a token using the wrong AccountType.

        //If we attempted to login as a Bot, remove the "Bot " prefix and set the Requester to be a client.
        if (getAccountType() == AccountType.BOT) {
            token = token.replace("Bot ", "");
            requester = new Requester(this, AccountType.CLIENT);
        } else //If we attempted to login as a Client, prepend the "Bot " prefix and set the Requester to be a Bot
        {
            token = "Bot " + token;
            requester = new Requester(this, AccountType.BOT);
        }

        try {
            //Now that we have reversed the AccountTypes, attempt to get User info again.
            userResponse = login.complete(false);
        } catch (RuntimeException e) {
            //We check if the LoginException is masked inside of a ExecutionException which is masked inside of the RuntimeException
            Throwable ex = e.getCause() != null ? e.getCause().getCause() : null;
            if (ex instanceof LoginException)
                throw (LoginException) ex;
            else
                throw e;
        }

        //If the response isn't null (thus it didn't 401) send it to the secondary verify method to determine
        // which account type the developer wrongly attempted to login as
        if (userResponse != null)
            verifyToken(userResponse);
        else //We 401'd again. This is an invalid token
            throw new LoginException("The provided token is invalid!");
    }
}

From source file:org.apache.openjpa.jdbc.kernel.TableJDBCSeq.java

protected Object currentInternal(JDBCStore store, ClassMapping mapping) throws Exception {
    if (current == null) {
        CurrentSequenceRunnable runnable = new CurrentSequenceRunnable(store, mapping);
        try {/*from w  w  w .java  2s .  c  o m*/
            if (suspendInJTA()) {
                // NotSupportedException is wrapped in a StoreException by
                // the caller.
                _conf.getManagedRuntimeInstance().doNonTransactionalWork(runnable);
            } else {
                runnable.run();
            }
        } catch (RuntimeException re) {
            throw (Exception) (re.getCause() == null ? re : re.getCause());
        }
    }
    return super.currentInternal(store, mapping);
}

From source file:org.apache.openjpa.jdbc.kernel.TableJDBCSeq.java

/**
 * Updates the max available sequence value.
 *//*ww w  .j  av a2 s .c  om*/
private void allocateSequence(JDBCStore store, ClassMapping mapping, Status stat, int alloc,
        boolean updateStatSeq) throws SQLException {
    Runnable runnable = new AllocateSequenceRunnable(store, mapping, stat, alloc, updateStatSeq);
    try {
        if (suspendInJTA()) {
            // NotSupportedException is wrapped in a StoreException by
            // the caller.
            try {
                _conf.getManagedRuntimeInstance().doNonTransactionalWork(runnable);
            } catch (NotSupportedException nse) {
                SQLException sqlEx = new SQLException(nse.getLocalizedMessage());
                sqlEx.initCause(nse);
                throw sqlEx;
            }
        } else {
            runnable.run();
        }
    } catch (RuntimeException re) {
        Throwable e = re.getCause();
        if (e instanceof SQLException)
            throw (SQLException) e;
        else
            throw re;
    }
}

From source file:org.fuin.utils4j.Utils4JTest.java

/**
 * @testng.test/*from   w w w . jav  a 2s. c  o  m*/
 */
public final void testCreateInstanceClassNotFound() {
    try {
        Utils4J.createInstance("x.y.Z");
        Assert.fail();
    } catch (final RuntimeException ex) {
        Assert.assertTrue(ex.getCause() instanceof ClassNotFoundException);
    }
}

From source file:org.fuin.utils4j.Utils4JTest.java

/**
 * @testng.test/*from ww w  .j a va2s.com*/
 */
public final void testCreateInstanceInstantiationProblem() {
    try {
        Utils4J.createInstance(Cancelable.class.getName());
        Assert.fail();
    } catch (final RuntimeException ex) {
        Assert.assertTrue(ex.getCause() instanceof InstantiationException);
    }
}