Example usage for java.lang Throwable Throwable

List of usage examples for java.lang Throwable Throwable

Introduction

In this page you can find the example usage for java.lang Throwable Throwable.

Prototype

public Throwable(Throwable cause) 

Source Link

Document

Constructs a new throwable with the specified cause and a detail message of (cause==null ?

Usage

From source file:mobisocial.musubi.ui.fragments.FeedViewFragment.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (mFeedUri == null) {
        Throwable e = new Throwable("No uri when setting options menu");
        UsageMetrics.getUsageMetrics(mActivity).report(e);
        return;// w ww. ja  v a  2 s.  com
    }

    long id = Long.parseLong(mFeedUri.getLastPathSegment());
    FeedManager fm = new FeedManager(App.getDatabaseSource(mActivity));
    MFeed f = fm.lookupFeed(id);
    assert (f != null);
    if (f.type_ == MFeed.FeedType.EXPANDING) {
        inflater.inflate(R.menu.feed_group, menu);
    } else {
        inflater.inflate(R.menu.feed_fixed, menu);
    }
}

From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java

/**
 * Function used to wait for a service to be available.
 *
 * @param host/*w  w w .  ja v  a2  s  . c  o m*/
 * @param timeout
 * @param serviceLinks
 * @throws Throwable
 */
public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks)
        throws Throwable {
    final CountDownLatch latch = new CountDownLatch(serviceLinks.length);
    final Throwable error = new Throwable("Error: registerForAvailability returned errors");

    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                error.addSuppressed(throwable);
            }

            latch.countDown();
        }
    };
    host.registerForServiceAvailability(handler, serviceLinks);

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException(
                String.format("One or several of service(s) %s not available", Utils.toJson(serviceLinks)));
    }

    if (error.getSuppressed().length > 0) {
        throw error;
    }
}

From source file:com.seleniumtests.reporter.SeleniumTestsReporter.java

public void afterInvocation(final IInvokedMethod method, final ITestResult result) {
    Reporter.setCurrentTestResult(result);

    // Handle Soft CustomAssertion
    if (method.isTestMethod()) {
        final List<Throwable> verificationFailures = CustomAssertion.getVerificationFailures();

        final int size = verificationFailures.size();
        if (size == 0) {
            return;
        } else if (result.getStatus() == TestResult.FAILURE) {
            return;
        }//from  ww  w .  ja  va2s .  c o  m

        result.setStatus(TestResult.FAILURE);

        if (size == 1) {
            result.setThrowable(verificationFailures.get(0));
        } else {

            // create failure message with all failures and stack traces barring last failure)
            final StringBuilder failureMessage = new StringBuilder("!!! Many Test Failures (").append(size)
                    .append(")\n");
            for (int i = 0; i < size - 1; i++) {
                failureMessage.append("Failure ").append(i + 1).append(" of ").append(size).append("\n");

                final Throwable t = verificationFailures.get(i);
                final String fullStackTrace = Utils.stackTrace(t, false)[1];
                failureMessage.append(fullStackTrace).append("\n");
            }

            // final failure
            final Throwable last = verificationFailures.get(size - 1);
            failureMessage.append("Failure ").append(size).append(" of ").append(size).append(":n");
            failureMessage.append(last.toString());

            // set merged throwable
            final Throwable merged = new Throwable(failureMessage.toString());
            merged.setStackTrace(last.getStackTrace());

            result.setThrowable(merged);
        }
    }
}

From source file:org.alfresco.rad.test.AlfrescoTestRunner.java

/**
 * Call a remote Alfresco server and have the test run there.
 *
 * @param method   the test method to run
 * @param notifier//from w ww . j a  v a2 s  . co  m
 * @param desc
 */
protected void callProxiedChild(FrameworkMethod method, RunNotifier notifier, Description desc) {
    notifier.fireTestStarted(desc);

    String className = method.getMethod().getDeclaringClass().getCanonicalName();
    String methodName = method.getName();
    if (null != methodName) {
        className += "#" + methodName;
    }

    // Login credentials for Alfresco Repo
    // TODO: Maybe configure credentials in props...
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
    provider.setCredentials(AuthScope.ANY, credentials);

    // Create HTTP Client with credentials
    CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    // Create the GET Request for the Web Script that will run the test
    String testWebScriptUrl = "/service/testing/test.xml?clazz=" + className.replace("#", "%23");
    //System.out.println("AlfrescoTestRunner: Invoking Web Script for test execution: " + testWebScriptUrl);
    HttpGet get = new HttpGet(getContextRoot(method) + testWebScriptUrl);

    try {
        // Send proxied request and read response
        HttpResponse resp = httpclient.execute(get);
        InputStream is = resp.getEntity().getContent();
        InputStreamReader ir = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(ir);
        String body = "";
        String line;
        while ((line = br.readLine()) != null) {
            body += line + "\n";
        }

        // Process response
        if (body.length() > 0) {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = null;
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new InputSource(new StringReader(body)));

            Element root = doc.getDocumentElement();
            NodeList results = root.getElementsByTagName("result");
            if (null != results && results.getLength() > 0) {
                String result = results.item(0).getFirstChild().getNodeValue();
                if (SUCCESS.equals(result)) {
                    notifier.fireTestFinished(desc);
                } else {
                    boolean failureFired = false;
                    NodeList throwableNodes = root.getElementsByTagName("throwable");
                    for (int tid = 0; tid < throwableNodes.getLength(); tid++) {
                        String throwableBody = null;
                        Object object = null;
                        Throwable throwable = null;
                        throwableBody = throwableNodes.item(tid).getFirstChild().getNodeValue();
                        if (null != throwableBody) {
                            try {
                                object = objectFromString(throwableBody);
                            } catch (ClassNotFoundException e) {
                            }
                            if (null != object && object instanceof Throwable) {
                                throwable = (Throwable) object;
                            }
                        }
                        if (null == throwable) {
                            throwable = new Throwable("Unable to process exception body: " + throwableBody);
                        }

                        notifier.fireTestFailure(new Failure(desc, throwable));
                        failureFired = true;
                    }
                    if (!failureFired) {
                        notifier.fireTestFailure(new Failure(desc, new Throwable(
                                "There was an error but we can't figure out what it was, sorry!")));
                    }
                }
            } else {
                notifier.fireTestFailure(new Failure(desc,
                        new Throwable("Unable to process response for proxied test request: " + body)));
            }
        } else {
            notifier.fireTestFailure(new Failure(desc, new Throwable(
                    "Attempt to proxy test into running Alfresco instance failed, no response received")));
        }
    } catch (IOException e) {
        notifier.fireTestFailure(new Failure(desc, e));
    } catch (ParserConfigurationException e) {
        notifier.fireTestFailure(new Failure(desc, e));
    } catch (SAXException e) {
        notifier.fireTestFailure(new Failure(desc, e));
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:it.geosolutions.geobatch.camel.JMSFlowManager.java

@InOut
public void process(Exchange exchange) throws Exception {

    if (LOGGER.isInfoEnabled())
        LOGGER.info("JMSFlowManager: will reply to ->" + exchange.getIn().getHeader("JMSReplyTo").toString());

    Message in = exchange.getIn();//from   w ww . ja  v a  2 s . c  o m
    JMSFlowResponse response = null;
    List<String> responses = null;

    try {
        JMSFlowRequest request = in.getBody(JMSFlowRequest.class);

        if (request == null) {
            throw new Throwable("Bad message type");
        } else {

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("JMSFlowManager: (" + exchange.getIn().getMessageId() + ") STARTING PROCESSING");
            }

            // do the work
            response = workOn(request);
        }
    } catch (Throwable t) {
        if (response != null) {
            responses = response.getResponses();
        } else {
            responses = new ArrayList<String>(1);
        }
        String message = "JMSFlowManager (" + exchange.getIn().getMessageId() + "): ERROR: " + t.getMessage();

        responses.add(message);

        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(message);
        }

        //TODO            // exchange.getIn().setFault(true);
        //TODO            // exchange.setException(t);

    } finally {
        // some error occurred in workOn()!
        if (response == null) {
            if (responses == null)
                responses = new ArrayList<String>(1);
            String message = "JMSFlowManager (" + exchange.getIn().getMessageId()
                    + "): Problem occurred during flow execution";
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(message);
            responses.add(message);
            response = new JMSFlowResponse(JMSFlowStatus.FAILURE, responses);
        }

        in.setBody(response, JMSFlowResponse.class);
        // exchange.setOut(in);//TODO check needed?
        if (LOGGER.isInfoEnabled())
            LOGGER.info("JMSFlowManager: Process ends for message ID:" + exchange.getIn().getMessageId());
    }
}

From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java

/**
 * Function used to wait for a service to be available.
 *
 * @param host/*from  ww w  .  ja  va 2s. c o m*/
 * @param timeout
 * @param serviceLinks
 * @throws Throwable
 */
public static void waitForServiceAvailability(ServiceHost host, long timeout, String... serviceLinks)
        throws Throwable {
    final CountDownLatch latch = new CountDownLatch(serviceLinks.length);
    final Throwable error = new Throwable("Error: registerForAvailability returned errors");

    Operation.CompletionHandler handler = new Operation.CompletionHandler() {
        @Override
        public void handle(Operation operation, Throwable throwable) {
            if (null != throwable) {
                error.addSuppressed(throwable);
            }

            latch.countDown();
        }
    };
    host.registerForServiceAvailability(handler, serviceLinks);

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw new TimeoutException(String.format("One or several of service(s) %s not available",
                Utils.toJson(false, false, serviceLinks)));
    }

    if (error.getSuppressed().length > 0) {
        throw error;
    }
}

From source file:org.apache.ode.bpel.elang.xpath20.runtime.XPath20ExpressionRuntime.java

public Node evaluateNode(OExpression cexp, EvaluationContext ctx) throws FaultException, EvaluationException {
    List retVal = evaluate(cexp, ctx);
    if (retVal.size() == 0 || retVal.size() > 1) {
        StringBuffer msg = new StringBuffer(
                (retVal.size() == 0) ? "No results for expression: '" : "Multiple results for expression: '");
        if (cexp instanceof OXPath10Expression) {
            msg.append(((OXPath10Expression) cexp).xpath);
        } else {/*from   w ww .j a v a 2 s  .com*/
            msg.append(cexp.toString());
        }
        msg.append('\'');
        if (ctx.getRootNode() != null) {
            msg.append(" against '");
            msg.append(DOMUtils.domToString(ctx.getRootNode()));
            msg.append('\'');
        }

        if (retVal.size() == 0)
            throw new FaultException(cexp.getOwner().constants.qnSelectionFailure, msg.toString(),
                    new Throwable("ignoreMissingFromData"));
        if (retVal.size() > 1)
            throw new FaultException(cexp.getOwner().constants.qnSelectionFailure, msg.toString());
    }
    return (Node) retVal.get(0);
}

From source file:gov.nih.nci.integration.caaers.invoker.CaAERSAdverseEventServiceInvocationStrategy.java

private void handleErrorResponse(ServiceResponse response, ServiceInvocationResult result) {
    final List<WsError> wserrors = response.getWsError();
    WsError error = null;/*ww  w  .j  a va2  s . co  m*/
    IntegrationException ie = null;

    if (wserrors == null || wserrors.isEmpty()) {
        ie = new IntegrationException(IntegrationError._1053, new Throwable(response.getMessage()), // NOPMD
                response.getMessage());
    } else {
        error = wserrors.get(0);
        ie = new IntegrationException(IntegrationError._1053, new Throwable(error.getException()), error // NOPMD
                .getErrorDesc());
    }

    result.setInvocationException(ie);
}

From source file:org.echocat.redprecursor.annotations.ParametersPassesExpressionUnitTest.java

@Test
public void testThrowMessageForEmptyMessageOnViolation() throws Exception {
    final ParametersPassesExpression annotation = proxyAnnotation(ParametersPassesExpression.class, "value",
            "myExpression", "messageOnViolation", "");
    final MethodCall<ParametersPassesExpressionUnitTest> methodCall = toMethodCall(
            ParametersPassesExpressionUnitTest.class, this, "test", "a", 1, "b", 2);
    try {//  w ww .j ava  2  s .c  om
        new Evaluator().throwMessageFor(annotation, methodCall, null);
        fail("Exception missing");
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(), is("Expression not passed: " + annotation.value()));
        assertThat(e.getCause(), nullValue());
    }
    final Throwable cause = new Throwable("myCause");
    try {
        new Evaluator().throwMessageFor(annotation, methodCall, cause);
        fail("Exception missing");
    } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(), is("Expression not passed: " + annotation.value()));
        assertThat(e.getCause(), is(cause));
    }
}

From source file:com.amazonaws.services.kinesis.multilang.StreamingRecordProcessorTest.java

@Test
public void initFailsTest() throws InterruptedException, ExecutionException {
    Answer<StatusMessage> answer = new Answer<StatusMessage>() {

        /*//w  ww . j av  a  2 s. c  o  m
         * This bad message will cause shutdown to not attempt to send a message. i.e. avoid encountering an
         * exception.
         */
        StatusMessage[] answers = new StatusMessage[] { new StatusMessage("Bad"),
                new StatusMessage(ProcessRecordsMessage.ACTION),
                new StatusMessage(ProcessRecordsMessage.ACTION), new StatusMessage(ShutdownMessage.ACTION) };

        int callCount = 0;

        @Override
        public StatusMessage answer(InvocationOnMock invocation) throws Throwable {
            if (callCount < answers.length) {
                return answers[callCount++];
            } else {
                throw new Throwable("Too many calls to getNextStatusMessage");
            }
        }
    };

    phases(answer);

    Mockito.verify(messageWriter, Mockito.times(1)).writeInitializeMessage(shardId);
    Mockito.verify(messageWriter, Mockito.times(2)).writeProcessRecordsMessage(Mockito.anyList());
    Mockito.verify(messageWriter, Mockito.times(0)).writeShutdownMessage(ShutdownReason.ZOMBIE);
    Assert.assertEquals(1, systemExitCount);
}