Example usage for java.lang Error printStackTrace

List of usage examples for java.lang Error printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.simbasecurity.core.saml.SAMLResponseHandlerImpl.java

@Override
public boolean isValid(String... requestId) {
    try {//from w w  w.  j a va2  s . c o m
        Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

        if (this.document == null) {
            throw new Exception("SAML Response is not loaded");
        }

        if (this.currentUrl == null || this.currentUrl.isEmpty()) {
            throw new Exception("The URL of the current host was not established");
        }

        // Check SAML version
        if (!rootElement.getAttribute("Version").equals("2.0")) {
            throw new Exception("Unsupported SAML Version.");
        }

        // Check ID in the response
        if (!rootElement.hasAttribute("ID")) {
            throw new Exception("Missing ID attribute on SAML Response.");
        }

        checkStatus();

        if (!this.validateNumAssertions()) {
            throw new Exception("SAML Response must contain 1 Assertion.");
        }

        NodeList signNodes = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        ArrayList<String> signedElements = new ArrayList<>();
        for (int i = 0; i < signNodes.getLength(); i++) {
            signedElements.add(signNodes.item(i).getParentNode().getLocalName());
        }
        if (!signedElements.isEmpty()) {
            if (!this.validateSignedElements(signedElements)) {
                throw new Exception("Found an unexpected Signature Element. SAML Response rejected");
            }
        }

        Document res = Utils.validateXML(this.document, "saml-schema-protocol-2.0.xsd");

        if (res == null) {
            throw new Exception("Invalid SAML Response. Not match the saml-schema-protocol-2.0.xsd");
        }

        if (rootElement.hasAttribute("InResponseTo")) {
            String responseInResponseTo = document.getDocumentElement().getAttribute("InResponseTo");
            if (requestId.length > 0 && responseInResponseTo.compareTo(requestId[0]) != 0) {
                throw new Exception("The InResponseTo of the Response: " + responseInResponseTo
                        + ", does not match the ID of the AuthNRequest sent by the SP: " + requestId[0]);
            }
        }

        // Validate Assertion timestamps
        if (!this.validateTimestamps()) {
            throw new Exception("Timing issues (please check your clock settings)");
        }

        // EncryptedAttributes are not supported
        NodeList encryptedAttributeNodes = this
                .queryAssertion("/saml:AttributeStatement/saml:EncryptedAttribute");
        if (encryptedAttributeNodes.getLength() > 0) {
            throw new Exception("There is an EncryptedAttribute in the Response and this SP not support them");
        }

        // Check destination
        //          TODO: lenneh: bktis: currentUrl is http:// and the destination is https://
        //            if (rootElement.hasAttribute("Destination")) {
        //                String destinationUrl = rootElement.getAttribute("Destination");
        //                if (destinationUrl != null) {
        //                    if (!destinationUrl.equals(currentUrl)) {
        //                        throw new Exception("The response was received at " + currentUrl + " instead of " + destinationUrl);
        //                    }
        //                }
        //            }

        // Check Audience
        //          TODO: lenneh: bktis: currentUrl is http:// and audienceUrl is https://
        //            Set<String> validAudiences = this.getAudiences();
        //
        //            if (validAudiences.isEmpty() || !this.audienceUrl.equals(currentUrl)) {
        //                throw new Exception(this.audienceUrl + " is not a valid audience for this Response");
        //            }

        // Check the issuers
        Set<String> issuers = this.getIssuers();
        for (String issuer : issuers) {
            if (issuer.isEmpty()) {
                throw new Exception("Invalid issuer in the Assertion/Response");
            }
        }

        // Check the session Expiration
        Calendar sessionExpiration = this.getSessionNotOnOrAfter();
        if (sessionExpiration != null) {
            if (now.equals(sessionExpiration) || now.after(sessionExpiration)) {
                throw new Exception(
                        "The attributes have expired, based on the SessionNotOnOrAfter of the AttributeStatement of this Response");
            }
        }

        // Check SubjectConfirmation, at least one SubjectConfirmation must be valid
        boolean validSubjectConfirmation = true;
        NodeList subjectConfirmationNodes = this.queryAssertion("/saml:Subject/saml:SubjectConfirmation");
        for (int i = 0; i < subjectConfirmationNodes.getLength(); i++) {
            Node scn = subjectConfirmationNodes.item(i);

            Node method = scn.getAttributes().getNamedItem("Method");
            if (method != null && !method.getNodeValue().equals(SAMLConstants.CM_BEARER)) {
                continue;
            }

            NodeList subjectConfirmationDataNodes = scn.getChildNodes();
            for (int c = 0; c < subjectConfirmationDataNodes.getLength(); c++) {

                Node subjectConfirmationData = subjectConfirmationDataNodes.item(c);
                if (subjectConfirmationData.getNodeType() == Node.ELEMENT_NODE
                        && subjectConfirmationData.getLocalName().equals("SubjectConfirmationData")) {

                    //                      TODO: lenneh: bktis: currentUrl is http:// and the recipient is https://
                    //                        Node recipient = subjectConfirmationData.getAttributes().getNamedItem("Recipient");
                    //                        if (recipient != null && !recipient.getNodeValue().equals(currentUrl)) {
                    //                            validSubjectConfirmation = false;
                    //                        }

                    Node notOnOrAfter = subjectConfirmationData.getAttributes().getNamedItem("NotOnOrAfter");
                    if (notOnOrAfter != null) {
                        Calendar noa = javax.xml.bind.DatatypeConverter
                                .parseDateTime(notOnOrAfter.getNodeValue());
                        if (now.equals(noa) || now.after(noa)) {
                            validSubjectConfirmation = false;
                        }
                    }

                    Node notBefore = subjectConfirmationData.getAttributes().getNamedItem("NotBefore");
                    if (notBefore != null) {
                        Calendar nb = javax.xml.bind.DatatypeConverter.parseDateTime(notBefore.getNodeValue());
                        if (now.before(nb)) {
                            validSubjectConfirmation = false;
                        }
                    }
                }
            }
        }
        if (!validSubjectConfirmation) {
            throw new Exception("A valid SubjectConfirmation was not found on this Response");
        }

        if (signedElements.isEmpty()) {
            throw new Exception("No Signature found. SAML Response rejected");
        } else {
            if (!Utils.validateSign(signNodes.item(0), certificate)) {
                throw new Exception("Signature validation failed. SAML Response rejected");
            }
        }
        return true;
    } catch (Error e) {
        error.append(e.getMessage());
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        error.append(e.getMessage());
        return false;
    }
}

From source file:org.apache.xmlrpc.WebServer.java

/**
 * Listens for client requests until stopped.  Call {@link
 * #start()} to invoke this method, and {@link #shutdown()} to
 * break out of it.//from   ww w. j  av  a  2 s.c o m
 *
 * @throws RuntimeException Generally caused by either an
 * <code>UnknownHostException</code> or <code>BindException</code>
 * with the vanilla web server.
 *
 * @see #start()
 * @see #shutdown()
 */
public void run() {
    try {
        while (listener != null) {
            try {
                Socket socket = serverSocket.accept();
                try {
                    socket.setTcpNoDelay(true);
                } catch (SocketException socketOptEx) {
                    System.err.println(socketOptEx);
                }

                if (allowConnection(socket)) {
                    Runner runner = getRunner();
                    runner.handle(socket);
                } else {
                    socket.close();
                }
            } catch (InterruptedIOException checkState) {
                // Timeout while waiting for a client (from
                // SO_TIMEOUT)...try again if still listening.
            } catch (Exception ex) {
                System.err.println("Exception in XML-RPC listener loop (" + ex + ").");
                if (XmlRpc.debug) {
                    ex.printStackTrace();
                }
            } catch (Error err) {
                System.err.println("Error in XML-RPC listener loop (" + err + ").");
                err.printStackTrace();
            }
        }
    } catch (Exception exception) {
        System.err.println("Error accepting XML-RPC connections (" + exception + ").");
        if (XmlRpc.debug) {
            exception.printStackTrace();
        }
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
                if (XmlRpc.debug) {
                    System.out.print("Closed XML-RPC server socket");
                }
                serverSocket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Shutdown our Runner-based threads
        if (runners != null) {
            ThreadGroup g = runners;
            runners = null;
            try {
                g.interrupt();
            } catch (Exception e) {
                System.err.println(e);
                e.printStackTrace();
            }
        }
    }
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * //w  w w  .j a va2s . c o m
 * creatAlbumArt
 * 
 *********************************/
public Bitmap createAlbumArt(String artistName, String albumName, Bitmap bm) {
    String fileName = ((RockPlayer) context).FILEX_ALBUM_ART_PATH + validateFileName(artistName) + " - "
            + validateFileName(albumName) + FILEX_FILENAME_EXTENSION;
    validateFileName(fileName);
    File albumArtFile = new File(fileName);

    try {
        /*
         * Set file output
         */

        albumArtFile.createNewFile();
        FileOutputStream albumArtFileStream = new FileOutputStream(albumArtFile);

        /*
          * Rescale/Crop the Bitmap
          */
        int MAX_SIZE = 480;
        float scaleFactor = (float) Math.max(1.0f,
                Math.min((float) bm.getWidth() / (float) MAX_SIZE, (float) bm.getHeight() / (float) MAX_SIZE));
        Log.i("CREATE", "" + scaleFactor);
        Bitmap albumArtBitmap = Bitmap.createScaledBitmap(bm,
                (int) Math.round((float) bm.getWidth() / scaleFactor),
                (int) Math.round((float) bm.getHeight() / scaleFactor), false);

        if (albumArtBitmap != null) {
            int dimension = Math.min(480, Math.min(albumArtBitmap.getHeight(), albumArtBitmap.getWidth()));
            Bitmap albumArtBitmapRescaled = Bitmap.createBitmap(albumArtBitmap,
                    (int) Math.floor((albumArtBitmap.getWidth() - dimension) / 2),
                    (int) Math.floor((albumArtBitmap.getHeight() - dimension) / 2), (int) dimension,
                    (int) dimension);

            FileOutputStream rescaledAlbumArtFileStream;
            rescaledAlbumArtFileStream = new FileOutputStream(albumArtFile);
            albumArtBitmapRescaled.compress(Bitmap.CompressFormat.JPEG, 96, rescaledAlbumArtFileStream);
            rescaledAlbumArtFileStream.close();
            if (albumArtBitmapRescaled != null)
                albumArtBitmapRescaled.recycle();

        } else {
            albumArtFile.delete();
        }
        if (albumArtBitmap != null)
            albumArtBitmap.recycle();
        return albumArtBitmap;
    } catch (Exception e) {
        e.printStackTrace();
        albumArtFile.delete();
        return null;
    } catch (Error err) {
        err.printStackTrace();
        return null;
    }

}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*******************************
 * /* w  ww  .j  ava2  s.  c  o m*/
 * createSmallAlbumArt
 * 
 *******************************/
public void createSmallAlbumArt(String artistName, String albumName, boolean force) {
    /*
     * If small art already exists just return
     */
    String smallArtFileName = ((RockPlayer) context).FILEX_SMALL_ALBUM_ART_PATH + validateFileName(artistName)
            + " - " + validateFileName(albumName) + FILEX_FILENAME_EXTENSION;
    Log.i("CREATE", smallArtFileName);
    File smallAlbumArtFile = new File(smallArtFileName);
    if (!force && smallAlbumArtFile.exists() && smallAlbumArtFile.length() > 0) {
        return;
    }

    /*
     * Get path for existing Album art
     */
    String albumArtPath = getAlbumArtPath(artistName, albumName);

    /*
     * If album has art file create the small thumb from it 
     * otherwise do it from the cdcover resource
     */
    Bitmap smallBitmap = null;
    if (albumArtPath != null) {
        try {
            Log.i("SCALEBM", albumArtPath);
            //            BitmapFactory.Options opts = new BitmapFactory.Options();
            //            opts.inJustDecodeBounds = true;
            //            Bitmap bmTmp = BitmapFactory.decodeFile(albumArtPath, opts);
            //            Log.i("DBG", ""+opts.outWidth+" "+opts.outHeight);
            //            bmTmp.recycle();

            FileInputStream albumArtPathStream = new FileInputStream(albumArtPath);
            Bitmap bm = BitmapFactory.decodeStream(albumArtPathStream);
            smallBitmap = Bitmap.createScaledBitmap(bm, 120, 120, false);
            albumArtPathStream.close();
            bm.recycle();
        } catch (Exception e) {
            // TODO: failed to get from library
            //          show error
            //smallBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.albumart_mp_unknown);
            e.printStackTrace();
        } catch (Error err) {
            err.printStackTrace();
        }
    } else {
        //smallBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.albumart_mp_unknown);
        return;
    }

    try {
        if (smallAlbumArtFile != null)
            smallAlbumArtFile.createNewFile();
        else
            Log.i("DBG", "smallAlbumArtFile is null ?????");

        FileOutputStream smallAlbumArtFileStream = null;

        if (smallAlbumArtFile != null)
            smallAlbumArtFileStream = new FileOutputStream(smallAlbumArtFile);
        else
            Log.i("DBG", "smallAlbumArtFile is null ?????");

        if (smallBitmap != null && smallAlbumArtFileStream != null)
            smallBitmap.compress(Bitmap.CompressFormat.JPEG, 90, smallAlbumArtFileStream);
        else
            Log.i("DBG", "smallBitmap or smallAlbumArtFileStream is null ?????");

        if (smallAlbumArtFileStream != null)
            smallAlbumArtFileStream.close();
        else
            Log.i("DBG", "smallAlbumArtFileStream is null ?????");

        if (smallBitmap != null)
            smallBitmap.recycle();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * //w  ww.j  a  v a  2s .  com
 * creatAlbumArt
 * 
 *********************************/
public Bitmap createAlbumArt(String artistName, String albumName, String albumArtURL) {
    String fileName = ((RockPlayer) context).FILEX_ALBUM_ART_PATH + validateFileName(artistName) + " - "
            + validateFileName(albumName) + FILEX_FILENAME_EXTENSION;
    validateFileName(fileName);
    File albumArtFile = new File(fileName);
    try {
        /*
         * Retreive Album
         */

        albumArtFile.createNewFile();
        FileOutputStream albumArtFileStream = new FileOutputStream(albumArtFile);

        /*
         * retreive URL
         */
        BasicHttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        //      DefaultedHttpParams params = new DefaultedHttpParams(httpClient.getParams(),
        //            httpClient.getParams());
        //      httpClient.setParams(params);
        HttpGet httpGet = new HttpGet(albumArtURL);
        HttpResponse response;
        HttpEntity entity;
        InputStream albumArtURLStream = null;

        response = httpClient.execute(httpGet);
        entity = response.getEntity();
        //         BufferedReader in = 
        //            new BufferedReader(new InputStreamReader(
        //                  entity.getContent()));
        albumArtURLStream = entity.getContent();

        //      URL albumArt = new URL(albumArtURL);
        //      InputStream albumArtURLStream = albumArt.openStream();

        byte buf[] = new byte[1024];
        int len;
        while ((len = albumArtURLStream.read(buf)) >= 0)
            albumArtFileStream.write(buf, 0, len);

        albumArtFileStream.close();
        albumArtURLStream.close();

        /*
         * Rescale/Crop the Bitmap
         */
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        Bitmap albumArtBitmap = BitmapFactory.decodeFile(fileName, opts);
        if (opts.outHeight < 320 || opts.outWidth < 320)
            return null;
        int MAX_DIM = 460;
        int sampling = 1;
        if (Math.min(opts.outWidth, opts.outHeight) > MAX_DIM) {
            sampling = (int) Math.floor(Math.min(opts.outWidth, opts.outHeight) / MAX_DIM);
        }
        opts.inSampleSize = sampling;
        opts.inJustDecodeBounds = false;
        FileInputStream fileNameStream = new FileInputStream(fileName);
        albumArtBitmap = BitmapFactory.decodeStream(fileNameStream, null, opts);
        fileNameStream.close();

        if (albumArtBitmap != null) {
            int dimension = Math.min(480, Math.min(albumArtBitmap.getHeight(), albumArtBitmap.getWidth()));
            Bitmap albumArtBitmapRescaled = Bitmap.createBitmap(albumArtBitmap,
                    (int) Math.floor((albumArtBitmap.getWidth() - dimension) / 2),
                    (int) Math.floor((albumArtBitmap.getHeight() - dimension) / 2), (int) dimension,
                    (int) dimension);

            FileOutputStream rescaledAlbumArtFileStream;
            rescaledAlbumArtFileStream = new FileOutputStream(albumArtFile);
            albumArtBitmapRescaled.compress(Bitmap.CompressFormat.JPEG, 96, rescaledAlbumArtFileStream);
            rescaledAlbumArtFileStream.close();
            if (albumArtBitmapRescaled != null)
                albumArtBitmapRescaled.recycle();

        } else {
            albumArtFile.delete();
        }
        if (albumArtBitmap != null)
            albumArtBitmap.recycle();
        return albumArtBitmap;
    } catch (Exception e) {
        e.printStackTrace();
        albumArtFile.delete();
        return null;
    } catch (Error err) {
        err.printStackTrace();
        return null;
    }
}

From source file:edu.umass.cs.reconfiguration.ActiveReplica.java

/**
 * Will spawn FetchEpochFinalState to fetch the final state of the previous
 * epoch if one existed, else will locally create the current epoch with an
 * empty initial state./*from  w w w.  j a v  a2s  .c o m*/
 * 
 * @param event
 * @param ptasks
 * @return Messaging task, typically null as we spawn a protocol task to
 *         fetch the previous epoch's final state.
 */
public GenericMessagingTask<NodeIDType, ?>[] handleStartEpoch(StartEpoch<NodeIDType> event,
        ProtocolTask<NodeIDType, ReconfigurationPacket.PacketType, String>[] ptasks) {
    StartEpoch<NodeIDType> startEpoch = ((StartEpoch<NodeIDType>) event);
    this.logEvent(event, Level.FINE);
    AckStartEpoch<NodeIDType> ackStart = new AckStartEpoch<NodeIDType>(startEpoch.getSender(),
            startEpoch.getServiceName(), startEpoch.getEpochNumber(), getMyID());
    GenericMessagingTask<NodeIDType, ?>[] mtasks = (new GenericMessagingTask<NodeIDType, AckStartEpoch<NodeIDType>>(
            startEpoch.getSender(), ackStart)).toArray();
    // send positive ack even if app has moved on
    if (this.alreadyMovedOn(startEpoch)) {
        log.log(Level.FINE, "{0} sending to {1}: {2} as paxos group has already moved on to version {3}",
                new Object[] { this, startEpoch.getSender(), ackStart.getSummary(),
                        this.appCoordinator.getEpoch(startEpoch.getServiceName()) });
        return mtasks;
    }
    // else
    if (startEpoch.isPassive()) {
        // do nothing
        return null;
    }
    // if no previous group, create replica group with empty state
    else if (startEpoch.noPrevEpochGroup()) {
        boolean created = false;
        try {
            // createReplicaGroup is a local operation (but may fail)
            created = startEpoch.isBatchedCreate() ? this.batchedCreate(startEpoch)
                    : this.appCoordinator.createReplicaGroup(startEpoch.getServiceName(),
                            startEpoch.getEpochNumber(), startEpoch.getInitialState(),
                            startEpoch.getCurEpochGroup());
        } catch (Error e) {
            log.severe(this + " received null state in non-passive startEpoch " + startEpoch);
            e.printStackTrace();
        }
        // the creation above will throw an exception if it fails
        assert (created && startEpoch.getCurEpochGroup()
                .equals(this.appCoordinator.getReplicaGroup(startEpoch.getServiceName()))) : this
                        + " unable to get replica group right after creation for startEpoch "
                        + startEpoch.getSummary() + ": created=" + created + "; startEpoch.getCurEpochGroup()="
                        + startEpoch.getCurEpochGroup() + "; this.appCoordinator.getReplicaGroup="
                        + this.appCoordinator.getReplicaGroup(startEpoch.getServiceName());
        log.log(Level.FINE, "{0} sending to {1}: {2}",
                new Object[] { this, startEpoch.getSender(), ackStart.getSummary() });

        return mtasks; // and also send positive ack
    }

    /* Else request previous epoch state using a threshold protocoltask. We
     * spawn WaitEpochFinalState as opposed to simply returning it in
     * ptasks[0] as otherwise we could end up creating tasks with duplicate
     * keys. */
    this.spawnWaitEpochFinalState(startEpoch);
    return null; // no messaging if asynchronously fetching state
}

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. jav  a  2s .  co m
            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();
                }
            }
        }
    }

}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * Initialize this SocketCreator.//from  w ww  .j a v  a  2s .co m
 * <p>
 * Caller must synchronize on the SocketCreator instance.
 */
@SuppressWarnings("hiding")
private void initialize() {
    try {
        // set p2p values...
        if (SecurableCommunicationChannel.CLUSTER.equals(sslConfig.getSecuredCommunicationChannel())) {
            if (this.sslConfig.isEnabled()) {
                System.setProperty("p2p.useSSL", "true");
                System.setProperty("p2p.oldIO", "true");
                System.setProperty("p2p.nodirectBuffers", "true");
            } else {
                System.setProperty("p2p.useSSL", "false");
            }
        }

        try {
            if (this.sslConfig.isEnabled() && sslContext == null) {
                sslContext = createAndConfigureSSLContext();
                SSLContext.setDefault(sslContext);
            }
        } catch (Exception e) {
            throw new GemFireConfigException("Error configuring GemFire ssl ", e);
        }

        // make sure TCPConduit picks up p2p properties...
        org.apache.geode.internal.tcp.TCPConduit.init();

        initializeClientSocketFactory();
        this.ready = true;
    } catch (VirtualMachineError err) {
        SystemFailure.initiateFailure(err);
        // If this ever returns, rethrow the error. We're poisoned
        // now, so don't let this thread continue.
        throw err;
    } catch (Error t) {
        // Whenever you catch Error or Throwable, you must also
        // catch VirtualMachineError (see above). However, there is
        // _still_ a possibility that you are dealing with a cascading
        // error condition, so you also need to check to see if the JVM
        // is still usable:
        SystemFailure.checkFailure();
        t.printStackTrace();
        throw t;
    } catch (RuntimeException re) {
        re.printStackTrace();
        throw re;
    }
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 * Called by transactors after committing.
 *//* w w  w  . ja  va  2s  . c  om*/
protected void fireNodeChangeEvent(List inserted, List updated, List deleted, List parents) {
    int l = listeners.size();

    for (int i = 0; i < l; i++) {
        try {
            ((NodeChangeListener) listeners.get(i)).nodesChanged(inserted, updated, deleted, parents);
        } catch (Error e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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

private byte[] getJournaledMessage(String logfile, long offset, int length, RandomAccessFile raf)
        throws IOException {
    assert (logfile != null);
    if (!new File(logfile).exists())
        return null;
    boolean locallyOpened = false;
    if (raf == null) {
        locallyOpened = true;//from   w ww  .  j a  va  2s. c om
        raf = new RandomAccessFile(logfile, "r");
    }
    boolean error = false;
    String msg = null;
    byte[] buf = null;
    try {
        raf.seek(offset);
        assert (raf.length() > offset) : this + " " + raf.length() + " <= " + offset + " while reading logfile "
                + logfile;
        int readLength = raf.readInt();
        try {
            assert (readLength == length) : this + " : " + readLength + " != " + length;
        } catch (Error e) {
            error = true;
            log.severe(this + ": " + e);
            e.printStackTrace();
        }
        int bufLength = length;
        buf = new byte[bufLength];
        raf.readFully(buf);
        if (JOURNAL_COMPRESSION)
            buf = inflate(buf);
        msg = new String(buf, CHARSET);
    } catch (IOException | Error e) {
        log.log(Level.INFO, "{0} incurred IOException while retrieving journaled message {1}:{2}",
                new Object[] { this, logfile, offset + ":" + length });
        e.printStackTrace();
        if (locallyOpened)
            raf.close();
        throw e;
    }
    log.log(error ? Level.INFO : Level.FINEST, "{0} returning journaled message from {1}:{2} = [{3}]",
            new Object[] { this, logfile, offset + ":" + length, msg });
    return buf;// msg;
}