Example usage for java.lang Error getMessage

List of usage examples for java.lang Error getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:semlink.apps.uvig.Generator.java

/**
 * Executes a method in the {@link uvi.Sweeper} class based on a node tag name
 * (i.e. 'VNCLASS') and a 'start' or 'end' flag.  Each of the methods in Sweeper,
 * startVNCLASS, endVNCLASS, startMEMBERS, endMEMBERS, etc., produce HTML code.
 * This method just calls the right method based on the current node being
 * processed by {@link uvi.Generator#processNode(Node)}.
 *
 * @param which either the value 'start' or 'end', the string to prepend to the
 *        tag name when locating the method in {@link uvi.Sweeper}
 * @param n the node whose tag name should be located in the Sweeper methods
 * @see uvi.Sweeper/*  w w w . jav a2  s. c om*/
 */
private static void executeHTMLMethod(String fileName, String which, Node n) {

    // Verify flag is a valid token.
    if (!which.equals("start") && !which.equals("end")) {
        eprintln("ERROR: Invalid \"which\" parameter.  Possible values are \"start\" and \"end\".");
        return;
    }

    // Use the appropriate reflection methods to execute the desired method.
    try {
        Class<?>[] classes = { Node.class };

        Method m = Sweeper.class.getDeclaredMethod(which + n.getNodeName(), classes);

        Object[] args = { n };

        m.invoke(null, args);
    } catch (NoSuchMethodException nsme) {
        // Do nothing - this is not an error condition.  It merely means the developer has not
        // specified any action for this node at this point (i.e. 'start' or 'end').
    } catch (SecurityException se) {
        eprintln("ERROR: [" + fileName + "; Security/refl] " + se.getMessage() + ".");
    } catch (Exception e) {
        e.printStackTrace();
        eprintln("ERROR: [" + fileName + "; Generic/refl] " + e.getMessage() + ".");
    } catch (Error err) {
        eprintln("ERROR: [" + fileName + "; Generic/refl-err] " + err.getMessage() + ".");
    }
}

From source file:edu.umass.cs.gigapaxos.PaxosInstanceStateMachine.java

private MessagingTask[] handleAccept(AcceptPacket accept) {
    this.paxosManager.heardFrom(accept.ballot.coordinatorID); // FD
    RequestInstrumenter.received(accept, accept.sender, this.getMyID());

    // if(!accept.hasRequestValue())
    // DelayProfiler.updateCount("C_DIGESTED_ACCEPTS_RCVD",
    // accept.batchSize()+1);

    AcceptPacket copy = accept;/*w w w  .j  a  v a  2  s . c o  m*/
    if (DIGEST_REQUESTS && !accept.hasRequestValue() && (accept = this.paxosManager.match(accept)) == null) {
        log.log(Level.FINE, "{0} received unmatched accept ",
                new Object[] { this, copy.getSummary(log.isLoggable(Level.FINE)) });
        // if(this.paxosState.getSlot() - copy.slot > 0)
        // DelayProfiler.updateCount("C_EXECD_ACCEPTS_RCVD",
        // copy.batchSize()+1);
        return new MessagingTask[0];
    } else
        log.log(Level.FINER, "{0} received matching accept ", new Object[] { this, accept.getSummary() });

    // DelayProfiler.updateCount("C_ACCEPTS_RCVD", accept.batchSize()+1);
    assert (accept.hasRequestValue());

    if (instrument(10))
        DelayProfiler.updateMovAvg("#batched", accept.batchSize() + 1);
    if ((this.paxosState.getAccept(accept.slot) == null) && (this.paxosState.getSlot() - accept.slot <= 0))
        this.paxosManager.incrOutstanding(accept.addDebugInfoDeep("a")); // stats

    if (EXECUTE_UPON_ACCEPT) { // only for testing
        PaxosInstanceStateMachine.execute(this, getPaxosManager(), this.getApp(), accept, false);
        if (Util.oneIn(10))
            log.info(DelayProfiler.getStats());
        // return null;
    }

    // have acceptor handle accept
    Ballot ballot = null;
    PValuePacket prev = this.paxosState.getAccept(accept.slot);
    try {
        ballot = !EXECUTE_UPON_ACCEPT ? this.paxosState.acceptAndUpdateBallot(accept, this.getMyID())
                : this.paxosState.getBallot();
    } catch (Error e) {
        log.severe(this + " : " + e.getMessage());
        Util.suicide(e.getMessage());
    }
    if (ballot == null)
        return null; // can happen only if acceptor is stopped.

    this.garbageCollectAccepted(accept.getMedianCheckpointedSlot());
    if (accept.isRecovery())
        return null; // recovery ACCEPTS do not need any reply

    AcceptReplyPacket acceptReply = new AcceptReplyPacket(this.getMyID(), ballot, accept.slot,
            GC_MAJORITY_EXECUTED ? this.paxosState.getSlot() - 1
                    : lastCheckpointSlot(this.paxosState.getSlot() - 1, accept.getPaxosID()),
            accept.requestID);

    // no logging if NACking anyway
    AcceptPacket toLog = (accept.ballot.compareTo(ballot) >= 0
            // no logging if already garbage collected or previously accepted
            && accept.slot - this.paxosState.getGCSlot() > 0
            && (prev == null || prev.ballot.compareTo(accept.ballot) < 0)) ? accept : null;

    MessagingTask acceptReplyTask = accept.isRecovery() ? new LogMessagingTask(toLog)
            : toLog != null ? new LogMessagingTask(accept.sender, acceptReply, toLog)
                    : new MessagingTask(accept.sender, acceptReply);
    RequestInstrumenter.sent(acceptReply, this.getMyID(), accept.sender);

    // might release some meta-commits
    PValuePacket reconstructedDecision = this.paxosState.reconstructDecision(accept.slot);
    MessagingTask commitTask = reconstructedDecision != null
            ? this.handleCommittedRequest(reconstructedDecision)
            : null;

    MessagingTask[] mtasks = { acceptReplyTask, commitTask };

    return mtasks;
}

From source file:gda.data.scan.datawriter.NexusDataWriter.java

/**
 * Create the next file. First increment the file number and then try and get a NeXus file handle from
 * {@link NexusFileFactory}./*  ww  w . j a  va  2s . com*/
 * @throws Exception 
 */
public void createNextFile() throws Exception {
    try {
        if (file != null) {
            try {
                file.flush();
                file.finalize();
            } catch (Throwable et) {
                String error = "Error closing NeXus file.";
                logger.error(error, et);
                terminalPrinter.print(error);
                terminalPrinter.print(et.getMessage());
            }
        }

        // set the entry name
        // this.entryName = "scan_" + run;
        this.entryName = "entry1";

        // construct filename
        if (nexusFileNameTemplate != null) {
            nexusFileName = String.format(nexusFileNameTemplate, scanNumber);
        } else if (LocalProperties.check(GDA_NEXUS_BEAMLINE_PREFIX)) {
            nexusFileName = beamline + "-" + scanNumber + ".nxs";
        } else {
            nexusFileName = Long.toString(scanNumber) + ".nxs";
        }

        if (!dataDir.endsWith(File.separator)) {
            dataDir += File.separator;
        }

        nexusFileUrl = dataDir + nexusFileName;

        // Check to see if the file(s) already exists!
        if (new File(nexusFileUrl).exists()) {
            throw new Exception("The file " + nexusFileUrl + " already exists.");
        }

        // create nexus file and return handle
        file = createFile();

        // If we have been return a null file reference then there was
        // some problem creating the file.
        if (file == null) {
            throw new Exception();
        }

        // Print informational message to console.
        String msg = "Writing data to file (NeXus): " + nexusFileUrl;
        logger.info(msg);
        terminalPrinter.print(msg);
        if (createSrsFile) {
            msg = "Also creating file (txt): " + srsFile.fileUrl;
            logger.info(msg);
            terminalPrinter.print(msg);
        }
    } catch (Error ex) {
        String error = "Failed to create file (" + nexusFileUrl;
        if (createSrsFile) {
            error += " or " + srsFile.fileUrl;
        }
        error += ")";
        error += ". Nexus binary library was not found. Inform Data Acquisition.";
        logger.error(error, ex);
        if (terminalPrinter != null) {
            terminalPrinter.print(error);
            terminalPrinter.print(ex.getMessage());
        }
        throw ex;
    } catch (Exception ex) {
        String error = "Failed to create file (" + nexusFileUrl;
        if (createSrsFile) {
            error += " or " + srsFile.fileUrl;
        }
        error += ")";
        logger.error(error, ex);
        if (terminalPrinter != null) {
            terminalPrinter.print(error);
            terminalPrinter.print(ex.getMessage());
        }
        throw ex;
    }

}

From source file:hudson.util.Graph.java

/**
 * Renders a graph.//  ww w  .  j a  v a2 s  . c om
 */
public void doPng(StaplerRequest req, StaplerResponse rsp) throws IOException {
    if (req.checkIfModified(timestamp, rsp))
        return;

    try {
        BufferedImage image = render(req, null);
        rsp.setContentType("image/png");
        ServletOutputStream os = rsp.getOutputStream();
        ImageIO.write(image, "PNG", os);
        os.close();
    } catch (Error e) {
        /* OpenJDK on ARM produces an error like this in case of headless error
        Caused by: java.lang.Error: Probable fatal error:No fonts found.
                at sun.font.FontManager.getDefaultPhysicalFont(FontManager.java:1088)
                at sun.font.FontManager.initialiseDeferredFont(FontManager.java:967)
                at sun.font.CompositeFont.doDeferredInitialisation(CompositeFont.java:254)
                at sun.font.CompositeFont.getSlotFont(CompositeFont.java:334)
                at sun.font.CompositeStrike.getStrikeForSlot(CompositeStrike.java:77)
                at sun.font.CompositeStrike.getFontMetrics(CompositeStrike.java:93)
                at sun.font.Font2D.getFontMetrics(Font2D.java:387)
                at java.awt.Font.defaultLineMetrics(Font.java:2082)
                at java.awt.Font.getLineMetrics(Font.java:2152)
                at org.jfree.chart.axis.NumberAxis.estimateMaximumTickLabelHeight(NumberAxis.java:974)
                at org.jfree.chart.axis.NumberAxis.selectVerticalAutoTickUnit(NumberAxis.java:1104)
                at org.jfree.chart.axis.NumberAxis.selectAutoTickUnit(NumberAxis.java:1048)
                at org.jfree.chart.axis.NumberAxis.refreshTicksVertical(NumberAxis.java:1249)
                at org.jfree.chart.axis.NumberAxis.refreshTicks(NumberAxis.java:1149)
                at org.jfree.chart.axis.ValueAxis.reserveSpace(ValueAxis.java:788)
                at org.jfree.chart.plot.CategoryPlot.calculateRangeAxisSpace(CategoryPlot.java:2650)
                at org.jfree.chart.plot.CategoryPlot.calculateAxisSpace(CategoryPlot.java:2669)
                at org.jfree.chart.plot.CategoryPlot.draw(CategoryPlot.java:2716)
                at org.jfree.chart.JFreeChart.draw(JFreeChart.java:1222)
                at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1396)
                at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1376)
                at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1361)
                at hudson.util.ChartUtil.generateGraph(ChartUtil.java:116)
                at hudson.util.ChartUtil.generateGraph(ChartUtil.java:99)
                at hudson.tasks.test.AbstractTestResultAction.doPng(AbstractTestResultAction.java:196)
                at hudson.tasks.test.TestResultProjectAction.doTrend(TestResultProjectAction.java:97)
                ... 37 more
         */
        if (e.getMessage().contains("Probable fatal error:No fonts found")) {
            rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
            return;
        }
        throw e; // otherwise let the caller deal with it
    } catch (HeadlessException e) {
        // not available. send out error message
        rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
    }
}

From source file:org.ow2.clif.jenkins.chart.AbstractChart.java

public void doPng(File rootDir, StaplerRequest req, StaplerResponse rsp) throws IOException {

    File imageFile = getImageFile(rootDir);

    try {/*  ww w  . java2  s.  c o  m*/
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        rsp.setContentType("image/png");
        ServletOutputStream os = rsp.getOutputStream();
        ImageIO.write(bufferedImage, "PNG", os);
        os.close();
    } catch (Error e) {
        /* OpenJDK on ARM produces an error like this in case of headless error
             Caused by: java.lang.Error: Probable fatal error:No fonts found.
                   at sun.font.FontManager.getDefaultPhysicalFont(FontManager.java:1088)
                   at sun.font.FontManager.initialiseDeferredFont(FontManager.java:967)
                   at sun.font.CompositeFont.doDeferredInitialisation(CompositeFont.java:254)
                   at sun.font.CompositeFont.getSlotFont(CompositeFont.java:334)
                   at sun.font.CompositeStrike.getStrikeForSlot(CompositeStrike.java:77)
                   at sun.font.CompositeStrike.getFontMetrics(CompositeStrike.java:93)
                   at sun.font.Font2D.getFontMetrics(Font2D.java:387)
                   at java.awt.Font.defaultLineMetrics(Font.java:2082)
                   at java.awt.Font.getLineMetrics(Font.java:2152)
                   at org.jfree.chart.axis.NumberAxis.estimateMaximumTickLabelHeight(NumberAxis.java:974)
                   at org.jfree.chart.axis.NumberAxis.selectVerticalAutoTickUnit(NumberAxis.java:1104)
                   at org.jfree.chart.axis.NumberAxis.selectAutoTickUnit(NumberAxis.java:1048)
                   at org.jfree.chart.axis.NumberAxis.refreshTicksVertical(NumberAxis.java:1249)
                   at org.jfree.chart.axis.NumberAxis.refreshTicks(NumberAxis.java:1149)
                   at org.jfree.chart.axis.ValueAxis.reserveSpace(ValueAxis.java:788)
                   at org.jfree.chart.plot.CategoryPlot.calculateRangeAxisSpace(CategoryPlot.java:2650)
                   at org.jfree.chart.plot.CategoryPlot.calculateAxisSpace(CategoryPlot.java:2669)
                   at org.jfree.chart.plot.CategoryPlot.draw(CategoryPlot.java:2716)
                   at org.jfree.chart.JFreeChart.draw(JFreeChart.java:1222)
                   at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1396)
                   at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1376)
                   at org.jfree.chart.JFreeChart.createBufferedImage(JFreeChart.java:1361)
                   at hudson.util.ChartUtil.generateGraph(ChartUtil.java:116)
                   at hudson.util.ChartUtil.generateGraph(ChartUtil.java:99)
                   at hudson.tasks.test.AbstractTestResultAction.doPng(AbstractTestResultAction.java:196)
                   at hudson.tasks.test.TestResultProjectAction.doTrend(TestResultProjectAction.java:97)
                   ... 37 more
           */
        if (e.getMessage().contains("Probable fatal error:No fonts found")) {
            rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
            return;
        }
        throw e; // otherwise let the caller deal with it
    } catch (HeadlessException e) {
        // not available. send out error message
        rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
    }

}

From source file:com.amazonaws.mws.MarketplaceWebServiceClient.java

@SuppressWarnings("serial")
private <T, U> T invoke(Class<T> clazz, Map<String, String> parameters, U request)
        throws MarketplaceWebServiceException {

    String actionName = parameters.get("Action");
    T response = null;//  w ww . ja v  a 2s.  c  om
    String responseBodyString = null;
    ResponseHeaderMetadata responseHeaderMetadata = null;
    Method responseHeaderMetadataSetter = null;

    HttpPost method = null;

    try {

        responseHeaderMetadataSetter = clazz.getMethod("setResponseHeaderMetadata",
                ResponseHeaderMetadata.class);

        if (!config.isSetServiceURL()) {
            throw new MarketplaceWebServiceException(
                    "Missing serviceUrl configuration value. You may obtain a list of valid MWS URLs by consulting the MWS Developer's Guide, or reviewing the sample code published along side this library.",
                    -1, "InvalidServiceUrl", "Sender", null, null, null) {
            };
        }
        // SubmitFeed will be the only MWS API function that will stream requests to the server.
        if (request instanceof SubmitFeedRequest) {

            // For SubmitFeed, HTTP body is reserved for the Feed Content and the function parameters 
            // are contained within the HTTP header
            SubmitFeedRequest sfr = (SubmitFeedRequest) request;

            method = new HttpPost(config.getServiceURL() + "?" + getSubmitFeedUrlParameters(parameters));

            method.setEntity(new InputStreamEntity(sfr.getFeedContent(), -1));

            /* Set content type and encoding - encoding and charset are ignored right now because
             * octet-stream is the only supported transport of MWS feeds. */
            method.addHeader(new BasicHeader("Content-Type", sfr.getContentType().toString()));

        } else {
            method = new HttpPost(config.getServiceURL());
            log.debug("Adding required parameters...");
            addRequiredParametersToRequest(method, parameters);

            /* Set content type and encoding */
            log.debug("Setting content-type to application/x-www-form-urlencoded; charset="
                    + DEFAULT_ENCODING.toLowerCase());
            method.addHeader(new BasicHeader("Content-Type",
                    "application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase()));

            log.debug("Done adding additional required parameters. Parameters now: " + parameters);
        }

        for (Header head : defaultHeaders) {
            method.addHeader(head);
        }

    } catch (Throwable t) {
        throw new MarketplaceWebServiceException(t);
    }

    int status = -1;

    log.debug("Invoking" + actionName + " request. Current parameters: " + parameters);
    try {
        boolean shouldRetry = true;
        int retries = 0;
        do {
            log.debug("Sending Request to host:  " + config.getServiceURL());

            try {

                /* Submit request */
                HttpResponse postResponse;
                postResponse = httpClient.execute(method, httpContext);
                status = postResponse.getStatusLine().getStatusCode();

                responseHeaderMetadata = getResponseHeaderMetadata(postResponse);

                // GetFeedSubmissionResult and GetReport will be the only MWS API functions that will stream
                // server responses.
                boolean isStreamingResponse = (request instanceof GetFeedSubmissionResultRequest
                        || request instanceof GetReportRequest);

                if (!isStreamingResponse) {
                    // SubmitFeed
                    responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent());
                    assert (responseBodyString != null);
                }

                /* Successful response. Attempting to unmarshal into the <Action>Response type */
                if (status == HttpStatus.SC_OK && responseBodyString != null) {
                    shouldRetry = false;
                    log.debug("Received Response. Status: " + status + ". " + "Response Body: "
                            + responseBodyString);

                    log.debug("Attempting to unmarshal into the " + actionName + "Response type...");
                    response = clazz.cast(getUnmarshaller()
                            .unmarshal(new StreamSource(new StringReader(responseBodyString))));
                    responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata);

                    log.debug("Unmarshalled response into " + actionName + "Response type.");

                } else if (status == HttpStatus.SC_OK && isStreamingResponse) {

                    Method outputStreamGetter = null;
                    for (Method m : request.getClass().getMethods()) {
                        if (m.getName().matches("get.+OutputStream$")) {
                            outputStreamGetter = m;
                        }
                    }

                    OutputStream originalOs = (OutputStream) outputStreamGetter.invoke(request, new Object[0]);

                    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
                    DigestOutputStream os = new DigestOutputStream(originalOs, messageDigest);

                    // Streaming-response-as-unnamed-body responses from MWS
                    // must carry the generated unique request id as a HTTP
                    // header (x-amz-request-id) as it cannot be passed in a
                    // wrapper to the XML response.
                    String requestIdFromHeader = null;
                    {
                        requestIdFromHeader = getFirstHeader(postResponse, "x-amz-request-id").getValue();

                        // Avoid use of the JDK-1.6-only isEmpty() call.
                        if (requestIdFromHeader == null || requestIdFromHeader.length() == 0) {
                            throw new MarketplaceWebServiceException(
                                    "no request id returned in the x-amz-request-id HTTP header "
                                            + "for a streaming response call - please contact Amazon");
                        }
                    }

                    String returnedContentMD5 = null;

                    returnedContentMD5 = getFirstHeader(postResponse, "Content-MD5").getValue();

                    copyResponseToOutputStream(postResponse.getEntity().getContent(), os);

                    // Streaming-response-as-unnamed-body responses from MWS
                    // must also carry a Content-MD5 header and it must
                    // match the calculated MD5 for the body.
                    String calculatedContentMD5 = new String(Base64.encodeBase64(messageDigest.digest()),
                            "UTF-8");
                    if (!calculatedContentMD5.equals(returnedContentMD5)) {
                        throw new MarketplaceWebServiceException(
                                "Content-MD5 HTTP header transmitted by MWS (" + returnedContentMD5 + ") "
                                        + "does not match the calculated MD5 (" + calculatedContentMD5 + ") "
                                        + "in request id " + requestIdFromHeader + " - please contact Amazon");
                    }

                    response = clazz.newInstance();
                    responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata);
                    if (clazz == GetFeedSubmissionResultResponse.class) {
                        GetFeedSubmissionResultResponse r = (GetFeedSubmissionResultResponse) response;
                        r.setGetFeedSubmissionResultResult(
                                new GetFeedSubmissionResultResult(returnedContentMD5));
                        r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader));
                    } else if (clazz == GetReportResponse.class) {
                        GetReportResponse r = (GetReportResponse) response;
                        r.setGetReportResult(new GetReportResult(returnedContentMD5));
                        r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader));
                    } else {
                        throw new MarketplaceWebServiceException("unexpected streaming-response class "
                                + clazz.getName() + " - please contact Amazon");
                    }

                    shouldRetry = false;
                    log.debug("Received streaming response.");

                } else { /* Unsucessful response. Attempting to unmarshall into ErrorResponse  type */

                    if (isStreamingResponse) {
                        // Response body contains error message.
                        responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent());
                    }

                    log.debug("Received Response. Status: " + status + ".");

                    if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR && !(request instanceof SubmitFeedRequest)
                            && pauseIfRetryNeeded(++retries)) {
                        shouldRetry = true;
                    } else {
                        log.debug("Attempting to unmarshal into the ErrorResponse type...");
                        ErrorResponse errorResponse = (ErrorResponse) getUnmarshaller()
                                .unmarshal(new StreamSource(new StringReader(responseBodyString)));

                        log.debug("Unmarshalled response into the ErrorResponse type.");

                        com.amazonaws.mws.model.Error error = errorResponse.getError().get(0);

                        if (status == HttpStatus.SC_SERVICE_UNAVAILABLE
                                && !(error.getCode().equals("RequestThrottled"))
                                && !(request instanceof SubmitFeedRequest) && pauseIfRetryNeeded(++retries)) {
                            shouldRetry = true;
                        } else {
                            shouldRetry = false;
                            throw new MarketplaceWebServiceException((((request instanceof SubmitFeedRequest)
                                    && (error.getType().equals("Receiver"))) ? error.getMessage()
                                            + " [Cannot retry SubmitFeed request: must reset InputStream to retry.]"
                                            : error.getMessage()),
                                    status, error.getCode(), error.getType(), errorResponse.getRequestId(),
                                    errorResponse.toXML(), responseHeaderMetadata);
                        }
                    }
                }
            } catch (JAXBException je) {
                /* Response cannot be unmarshalled neither as <Action>Response or ErrorResponse types.
                Checking for other possible errors. */

                log.debug("Caught JAXBException", je);
                log.debug("Response cannot be unmarshalled neither as " + actionName
                        + "Response or ErrorResponse types." + "Checking for other possible errors.");

                MarketplaceWebServiceException awse = processErrors(responseBodyString, status,
                        responseHeaderMetadata);

                throw awse;

            } catch (IOException ioe) {
                log.error("Caught IOException exception", ioe);
                if (config.isSetProxyHost() && config.isSetProxyPort()
                        && ioe instanceof javax.net.ssl.SSLPeerUnverifiedException) {
                    String error = "\n*****\n* Perhaps you are attempting to use https protocol to communicate with the proxy that does not support it.\n* If so either enable https on the proxy, or configure the client to use http communications with the proxy.\n* See  MarketplaceWebServiceClientConfig.setProxyProtocol for details.\n*****";
                    log.error(error);
                }
                throw new MarketplaceWebServiceException("Internal Error", ioe);
            } catch (Exception e) {
                log.error("Caught Exception", e);
                throw new MarketplaceWebServiceException(e);
            } finally {
                method.releaseConnection();
            }
        } while (shouldRetry);

    } catch (MarketplaceWebServiceException se) {
        log.error("Caught MarketplaceWebServiceException", se);
        throw se;

    } catch (Throwable t) {
        log.error("Caught Exception", t);
        throw new MarketplaceWebServiceException(t);
    }
    return response;
}

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

protected void generatePanel(final VelocityEngine ve, final IResultMap map, final StringBuffer res,
        final String style, final ISuite suite, final ITestContext ctx, final boolean envt) {

    final Collection<ITestNGMethod> methodSet = getMethodSet(map);

    for (final ITestNGMethod method : methodSet) {

        final boolean methodIsValid;
        if (envt) {
            methodIsValid = Arrays.asList(method.getGroups()).contains("envt");
        } else {/*w  w  w  . j a v  a 2 s .c om*/
            methodIsValid = !Arrays.asList(method.getGroups()).contains("envt");
        }

        if (methodIsValid) {

            final Collection<ITestResult> resultSet = getResultSet(map, method);
            String content;
            for (final ITestResult ans : resultSet) {
                final StringBuffer contentBuffer = new StringBuffer();
                String testName = "";
                if (ans.getMethod().getXmlTest() != null) {
                    testName = ans.getMethod().getXmlTest().getName();
                } else {
                    try {
                        testName = ans.getTestContext().getCurrentXmlTest().getName();
                    } catch (final Exception ex) {
                        ex.printStackTrace();
                        continue;
                    } catch (final Error e) {
                        e.printStackTrace();
                        continue;
                    }
                }

                final SeleniumTestsContext testLevelContext = SeleniumTestsContextManager
                        .getTestLevelContext(testName);
                if (testLevelContext != null) {
                    final String appURL = testLevelContext.getAppURL();
                    String browser = testLevelContext.getWebRunBrowser();

                    final String app = testLevelContext.getApp();
                    final String appPackage = testLevelContext.getAppPackage();
                    final String appActivity = testLevelContext.getAppActivity();
                    final String testType = testLevelContext.getTestType();

                    if (browser != null) {
                        browser = browser.replace("*", "");
                    }

                    final String browserVersion = (String) testLevelContext.getAttribute("browserVersion");
                    if (browserVersion != null) {
                        browser = browser + browserVersion;
                    }

                    // Log URL for web test and app info for app test
                    if (testType.equalsIgnoreCase(TestType.WEB.getTestType())) {
                        contentBuffer.append("<div><i>App URL:  <b>" + appURL + "</b>, Browser: <b>" + browser
                                + "</b></i></div>");
                    } else if (testType.equalsIgnoreCase(TestType.APP.getTestType())) {

                        // Either app Or app package and app activity is specified to run test on app
                        if (StringUtils.isNotBlank(app)) {
                            contentBuffer.append("<div><i>App:  <b>" + app + "</b></i></div>");
                        } else if (StringUtils.isNotBlank(appPackage)) {
                            contentBuffer.append("<div><i>App Package: <b>" + appPackage
                                    + "</b>, App Activity:  <b>" + appActivity + "</b></i></div>");
                        }
                    } else if (testType.equalsIgnoreCase(TestType.NON_GUI.getTestType())) {
                        contentBuffer.append("<div><i></i></div>");

                    } else {
                        contentBuffer.append("<div><i>Invalid Test Type</i></div>");
                    }
                }

                final Object[] parameters = ans.getParameters();
                final List<String> msgs = Reporter.getOutput(ans);

                final boolean hasReporterOutput = msgs.size() > 0;
                final Throwable exception = ans.getThrowable();
                final boolean hasThrowable = exception != null;
                if (hasReporterOutput || hasThrowable) {
                    contentBuffer.append("<div class='leftContent' style='float: left; width: 100%;'>");
                    contentBuffer.append("<h4><a href='javascript:void(0);' class='testloglnk'>Test Steps "
                            + (style.equals("passed") ? "[+]" : "[ - ]") + "</a></h4>");
                    contentBuffer.append("<div class='testlog' "
                            + (style.equals("passed") ? "style='display:none'" : "") + ">");
                    contentBuffer.append("<ol>");
                    for (final String line : msgs) {
                        final ElaborateLog logLine = new ElaborateLog(line, outputDirectory);
                        String htmllog;
                        if (logLine.getHref() != null) {
                            htmllog = "<a href='" + logLine.getHref() + "' title='" + logLine.getLocation()
                                    + "' >" + logLine.getMsg() + "</a>";
                        } else {
                            htmllog = logLine.getMsg();
                        }

                        htmllog = htmllog.replaceAll("@@lt@@", "<").replace("^^greaterThan^^", ">");
                        contentBuffer.append(htmllog);
                        if (!htmllog.contains("<br>")) {
                            contentBuffer.append("<br/>");
                        }
                    }

                    contentBuffer.append("</ol>");

                    String lastLine = "";
                    for (int lastIdx = msgs.size() - 1; lastIdx >= 0; lastIdx--) {
                        lastLine = msgs.get(lastIdx).replaceAll("@@lt@@", "<").replace("^^greaterThan^^", ">");
                        if (lastLine.indexOf(">screenshot</a>") != -1) {
                            break;
                        }
                    }

                    if (hasThrowable) {
                        generateExceptionReport(exception, method, contentBuffer, lastLine);
                    }

                    contentBuffer.append("</div></div>");
                }

                final String treeId = "tree" + m_treeId;
                m_treeId++;
                if (ans.getStatus() == 3) {
                    contentBuffer.append("<br>method skipped, because of its dependencies :<br>");
                    takeCareOfDirectDependencies(suite, method, 0, ctx, treeId, contentBuffer);
                }

                contentBuffer.append("<div class='clear_both'></div>");
                content = contentBuffer.toString();

                try {
                    final Template t = ve.getTemplate("/templates/report.part.singleTest.html");
                    final VelocityContext context = new VelocityContext();
                    context.put("status", style);

                    final String javadoc = getJavadocComments(method);
                    final String desc = method.getDescription();

                    String toDisplay = "neither javadoc nor description for this method.";
                    if (!"".equals(javadoc) && javadoc != null) {
                        toDisplay = javadoc;
                    } else if (!"".equals(desc) && desc != null) {
                        toDisplay = desc;
                    }

                    final String methodSignature = StringUtility.constructMethodSignature(method.getMethod(),
                            parameters);
                    if (methodSignature.length() > 500) {
                        context.put("methodName", methodSignature.substring(0, 500) + "...");
                    } else {
                        context.put("methodName", methodSignature);
                    }

                    context.put("desc", toDisplay.replaceAll("\r\n\r\n", "\r\n").replaceAll("\n\n", "\n"));
                    context.put("content", content);
                    context.put("time",
                            "Time: " + ((ans.getEndMillis() - ans.getStartMillis()) / 1000) + "sec.");

                    final StringWriter writer = new StringWriter();
                    t.merge(context, writer);
                    res.append(writer.toString());
                } catch (final Exception e) {
                    logger.error("Exception creating a singleTest." + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }

}