Example usage for java.lang IllegalStateException toString

List of usage examples for java.lang IllegalStateException toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.onehippo.cms7.brokenlinks.BrokenLinksCheckingJob.java

private void checkBrokenLinks(final Session session, final CheckExternalBrokenLinksConfig config)
        throws RepositoryException {
    final WorkflowManager workflowManager = ((HippoWorkspace) session.getWorkspace()).getWorkflowManager();

    final LinkChecker linkChecker = new LinkChecker(config, session);
    log.info("Checking broken external links, configuration: ", config);
    // For the xpath query below, do not include a path constraint to begin with, like
    // /jcr:root/content/documents as this results in much less efficient queries
    String xpath = "//element(*,hippostd:html)";
    QueryResult result = session.getWorkspace().getQueryManager().createQuery(xpath, Query.XPATH).execute();
    NodeIterator hippostdHtmlNodes = result.getNodes();

    // the key of the links map is the uuid of the handle node
    Map<String, Set<Link>> linksByHandleUUID = new HashMap<String, Set<Link>>();
    // the unique links by URL
    Map<String, Link> linksByURL = new HashMap<String, Link>();

    long start = System.currentTimeMillis();
    int count = 0;
    int totalLinksCount = 0;
    while (hippostdHtmlNodes.hasNext()) {
        try {/*w  w  w .j  av a2  s . com*/
            Node hippostdHtml = hippostdHtmlNodes.nextNode();

            if (!hippostdHtml.getPath().startsWith(config.getStartPath())) {
                // skip paths that do not start with the path we want to scan below
                continue;
            }

            // we need to group the links per handle because all hippostd:content
            // fields below a handle store their broken links directly below the handle
            Node handleNode = getHandleNode(hippostdHtml);

            if (handleNode == null) {
                // could not find handle for hippostd:html node. Skip it
                continue;
            }

            String handleUUID = handleNode.getIdentifier();
            // hippostd:content is a mandatory property so no need to check for existence
            String content = hippostdHtml.getProperty("hippostd:content").getString();

            try {
                Set<Link> linksForHandle = linksByHandleUUID.get(handleUUID);
                count++;

                final List<String> links = PlainTextLinksExtractor.getLinks(content);
                totalLinksCount += links.size();
                for (String url : links) {

                    if (isExcludedURL(config, url)) {
                        log.info("The URL is excluded while broken links checking in '{}': {}",
                                hippostdHtml.getPath(), url);
                        continue;
                    }

                    if (linksForHandle == null) {
                        linksForHandle = new HashSet<>();
                        linksByHandleUUID.put(handleUUID, linksForHandle);
                    }

                    Link alreadyPresent = linksByURL.get(url);

                    if (alreadyPresent == null) {
                        String sourceNodeIdentifier = hippostdHtml.getIdentifier();
                        Link link = new Link(url, sourceNodeIdentifier);

                        if (StringUtils.startsWithIgnoreCase(url, "http:")
                                || StringUtils.startsWithIgnoreCase(url, "https:")) {
                            linksByURL.put(url, link);
                        } else {
                            linksByURL.put(sourceNodeIdentifier + "/" + url, link);
                        }

                        log.debug("Adding to test for handle with '{}' the url '{}'", handleUUID, url);
                        linksForHandle.add(link);
                    } else {
                        log.debug("Adding to test for handle with '{}' the url '{}'", handleUUID, url);
                        linksForHandle.add(alreadyPresent);
                    }
                }
            } catch (IllegalStateException e) {
                log.warn("Unable to get link from hippostd:html for node '{}'", hippostdHtml.getPath());
            }
        } catch (RepositoryException e) {
            log.warn(
                    "RepositoryException for hippostd:html node from search result. Skip and continue with next");
        }
    }
    long scanningTook = (System.currentTimeMillis() - start);
    log.info("Finished scanning all hippostd:html nodes for external links in {} seconds.",
            String.valueOf((scanningTook / 1000.0)));
    log.info("In total {}  hippostd:html nodes were scanned.", String.valueOf(count));
    log.info("In total {} handles have links", linksByHandleUUID.size());
    log.info("In total there are {} unique links", linksByURL.size());
    log.info("In total there were {} links scanned", totalLinksCount);
    log.info("Starting scanning for external links that are broken");

    start = System.currentTimeMillis();
    // this set keeps track of scanned links to avoid needless double scanning

    // Now first check all external links whether they are available : The linkChecker runs multi-threaded thus
    // to utilize the multi-threading best, it is best to scan all Links combined, not just the ones for a single handle
    linkChecker.run(linksByURL.values());
    linkChecker.shutdown();

    log.info("Finished testing availability of all URLs. Tested '{}' URLs in {} seconds.",
            String.valueOf(linksByURL.size()), String.valueOf((scanningTook / 1000.0)));

    for (Map.Entry<String, Set<Link>> entry : linksByHandleUUID.entrySet()) {

        // all links belong to one document, so we can safely collect and process them at once:
        Collection<Link> brokenLinks = new ArrayList<Link>();
        for (Link link : entry.getValue()) {
            if (link.isBroken()) {
                brokenLinks.add(link);
            }
        }
        // the key in the Map contains the handleUUID
        try {
            Node handleNode = session.getNodeByIdentifier(entry.getKey());
            if (!brokenLinks.isEmpty() || handleNode.isNodeType(NodeType.BROKENLINKS_MIXIN)) {
                // need to get the document below the handle to be able to get the workflow
                Node doc;
                try {
                    doc = handleNode.getNode(handleNode.getName());
                } catch (PathNotFoundException e) {
                    log.warn("could not find document below handle '{}'. SKip", handleNode.getPath());
                    continue;
                }
                try {
                    Workflow reportWorkflow = workflowManager.getWorkflow("brokenlinks", new Document(doc));
                    if (reportWorkflow instanceof ReportBrokenLinksWorkflow) {
                        ((ReportBrokenLinksWorkflow) reportWorkflow).reportBrokenLinks(brokenLinks);
                    }
                } catch (WorkflowException e) {
                    if (log.isDebugEnabled()) {
                        log.warn(
                                "WorkflowException exception while trying to write link report to handle with uuid '"
                                        + entry.getKey() + "'",
                                e);
                    } else {
                        log.warn(
                                "WorkflowException exception while trying to write link report to handle with uuid '{}' : {}",
                                entry.getKey(), e.toString());
                    }
                } catch (RepositoryException e) {
                    if (log.isDebugEnabled()) {
                        log.warn("Repository exception while trying to write link report to handle with uuid '"
                                + entry.getKey() + "'", e);
                    } else {
                        log.warn(
                                "Repository exception while trying to write link report to handle with uuid '{}' : {}",
                                entry.getKey(), e.toString());
                    }
                } catch (RemoteException e) {
                    if (log.isDebugEnabled()) {
                        log.warn("Repository exception while trying to write link report to handle with uuid '"
                                + entry.getKey() + "'", e);
                    } else {
                        log.warn(
                                "Repository exception while trying to write link report to handle with uuid '{}' : {}",
                                entry.getKey(), e.toString());
                    }
                }

            }
        } catch (ItemNotFoundException e) {
            if (log.isDebugEnabled()) {
                log.warn(
                        "ItemNotFoundException exception while trying to create link report to handle with uuid '"
                                + entry.getKey() + "'",
                        e);
            } else {
                log.warn(
                        "ItemNotFoundException exception while trying to create link report to handle with uuid '{}' : {}",
                        entry.getKey(), e.toString());
            }
        } catch (RepositoryException e) {
            if (log.isDebugEnabled()) {
                log.warn(
                        "RepositoryException exception while trying to create link report to handle with uuid '"
                                + entry.getKey() + "'",
                        e);
            } else {
                log.warn(
                        "RepositoryException exception while trying to create link report to handle with uuid '{}' : {}",
                        entry.getKey(), e.toString());
            }
        }

    }

}

From source file:org.ireland.jnetty.webapp.ErrorPageManager.java

public void sendServletErrorImpl(Throwable e, ServletRequest req, ServletResponse res) throws IOException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    Throwable rootExn = e;//from w  w  w.  j  av a  2 s  .  c o m
    Throwable errorPageExn = null;
    LineMap lineMap = null;

    try {
        response.reset();
    } catch (IllegalStateException e1) {
    }

    if (req.isAsyncStarted()) {
        AsyncContext async = req.getAsyncContext();

        if (async != null)
            async.complete();
    }

    if (response instanceof HttpServletResponseImpl) {
        HttpServletResponseImpl resFacade = (HttpServletResponseImpl) response;
        resFacade.killCache();
        resFacade.setNoCache(true);
    }

    if (rootExn instanceof ClientDisconnectException)
        throw (ClientDisconnectException) rootExn;

    String location = null;

    String title = "500 Servlet Exception";
    boolean isBadRequest = false;
    boolean doStackTrace = true;
    boolean isCompileException = false;
    boolean isServletException = false;
    Throwable compileException = null;
    String lineMessage = null;

    boolean lookupErrorPage = true;

    while (true) {
        if (rootExn instanceof LineMapException)
            lineMap = ((LineMapException) rootExn).getLineMap();

        if (lookupErrorPage) {
            errorPageExn = rootExn;
        }

        if (rootExn instanceof DisplayableException) {
            doStackTrace = false;
            isCompileException = true;
            if (compileException == null)
                compileException = rootExn;
        } else if (rootExn instanceof CompileException) {
            doStackTrace = false;
            isCompileException = true;

            if (compileException == null) // ! isLineCompileException)
                compileException = rootExn;
        } else if (rootExn instanceof LineException) {
            if (lineMessage == null)
                lineMessage = rootExn.getMessage();
        }

        if (rootExn instanceof BadRequestException) {
            isBadRequest = true;
        }

        if (rootExn instanceof OutOfMemoryError) {
            String msg = "TcpSocketLink OutOfMemory";

            ShutdownSystem.shutdownOutOfMemory(msg);
        }

        if (location != null || !lookupErrorPage) {
        } else if (rootExn instanceof LineMapException && rootExn instanceof ServletException
                && !(rootExn instanceof LineCompileException) && rootExn.getCause() != null) {
            // hack to deal with JSP wrapping
        } else if (!isServletException) {
            // SRV.9.9.2 Servlet 2.4
            // location = getErrorPage(rootExn, ServletException.class);
            location = getErrorPage(rootExn);
            isServletException = true;
        } else {
            location = getErrorPage(rootExn);
            lookupErrorPage = false;
        }

        if (location != null)
            lookupErrorPage = false;

        if (isBadRequest)
            break;

        Throwable cause = null;
        if (rootExn instanceof ServletException && !(rootExn instanceof LineCompileException))
            cause = ((ServletException) rootExn).getRootCause();
        else {
            lookupErrorPage = false;
            cause = rootExn.getCause();
        }

        if (cause != null)
            rootExn = cause;
        else {
            break;
        }
    }

    if (location == null && lookupErrorPage) {
        location = getErrorPage(rootExn);
    }

    if (location == null)
        location = getErrorPage(500);

    if (isBadRequest) {
        // server/05a0, server/0532

        if (rootExn instanceof CompileException)
            title = rootExn.getMessage();
        else
            title = String.valueOf(rootExn);

        doStackTrace = false;
        isBadRequest = true;

        if (request instanceof CauchoRequest)
            ((CauchoRequest) request).killKeepalive("bad request: " + rootExn);

        response.resetBuffer();

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

        /*
         * if (location == null) log.warn(e.toString());
         */
    } else if (rootExn instanceof UnavailableException) {
        UnavailableException unAvail = (UnavailableException) rootExn;

        if (unAvail.isPermanent()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            title = "404 Not Found";

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_NOT_FOUND);
        } else {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            title = "503 Unavailable";

            if (unAvail.getUnavailableSeconds() > 0)
                response.setIntHeader("Retry-After", unAvail.getUnavailableSeconds());

            if (location == null)
                location = getErrorPage(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (location == null)
        location = _defaultLocation;

    if (log.isTraceEnabled())
        log.trace(e.toString(), e);
    else if (isCompileException) {
        if (isBadRequest)
            log.trace(BadRequestException.class.getSimpleName() + ": " + compileException.getMessage());
        else
            log.trace(compileException.getMessage());
    } else if (!doStackTrace)
        log.trace(rootExn.toString());
    else
        log.trace(e.toString(), e);

    if (location != null) {
        if (errorPageExn == null)
            errorPageExn = rootExn;

        request.setAttribute(JSP_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, errorPageExn);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION_TYPE, errorPageExn.getClass());
        if (request instanceof HttpServletRequest)
            request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI,
                    ((HttpServletRequest) request).getRequestURI());

        String servletName = getServletName(request);

        if (servletName != null)
            request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, servletName);

        request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(500));
        request.setAttribute(RequestDispatcher.ERROR_MESSAGE, errorPageExn.getMessage());

        try {
            RequestDispatcher disp = null;
            // can't use filters because of error pages due to filters
            // or security.

            WebApp webApp = getWebApp();

            if (webApp != null)
                disp = webApp.getRequestDispatcher(location);
            else if (_host != null)
                disp = _host.getWebAppContainer().getRequestDispatcher(location);

            if (disp != null) {
                ((RequestDispatcherImpl) disp).error(request, response);
                return;
            }
        } catch (Throwable e1) {
            log.info(e1.toString(), e1);
            rootExn = e1;
        }
    }

    response.setContentType("text/html");

    String encoding = CharacterEncoding.getLocalEncoding();

    if (encoding != null)
        response.setCharacterEncoding(encoding);
    else {
        Locale locale = Locale.getDefault();
        if (!"ISO-8859-1".equals(Encoding.getMimeName(locale)))
            response.setLocale(Locale.getDefault());
        else
            response.setCharacterEncoding("utf-8");
    }

    PrintWriter out;

    try {
        out = response.getWriter();
    } catch (IllegalStateException e1) {
        log.trace(e1.toString(), e1);

        out = new PrintWriter(new OutputStreamWriter(response.getOutputStream()));
    }

    if (isDevelopmentModeErrorPage()) {
        out.println("<html>");
        if (!response.isCommitted())
            out.println("<head><title>" + escapeHtml(title) + "</title></head>");
        out.println("<body>");
        out.println("<h1>" + escapeHtml(title) + "</h1>");

        out.println("<code><pre>");

        if (debug && !CurrentTime.isTest())
            doStackTrace = true;

        if (doStackTrace) {
            out.println("<script language='javascript' type='text/javascript'>");
            out.println("function show() { document.getElementById('trace').style.display = ''; }");
            out.println("</script>");
            out.print("<a style=\"text-decoration\" href=\"javascript:show();\">[show]</a> ");
        }

        if (compileException instanceof DisplayableException) {
            // ioc/0000
            // XXX: dispExn.print doesn't normalize user.name
            // dispExn.print(out);
            out.println(escapeHtml(compileException.getMessage()));
        } else if (compileException != null)
            out.println(escapeHtml(compileException.getMessage()));
        else
            out.println(escapeHtml(rootExn.toString()));

        if (doStackTrace) {
            out.println("<span id=\"trace\" style=\"display:none\">");
            printStackTrace(out, lineMessage, e, rootExn, lineMap);
            out.println("</span>");
        }

        /*
         * if (doStackTrace || debug) { printStackTrace(out, lineMessage, e, rootExn, lineMap); }
         */

        out.println("</pre></code>");

        printVersion(out);

        out.println("</body></html>");
    } else { // non-development mode
        out.println("<html>");
        out.println("<title>Server Error</title>");
        out.println("<body>");
        out.println("<h1>Server Error</h1>");
        out.println("<p>The server is temporarily unavailable due to an");
        out.println("internal error.  Please notify the system administrator");
        out.println("of this problem.</p>");

        out.println("<pre><code>");
        out.println("Date: " + QDate.formatISO8601(CurrentTime.getCurrentTime()));

        out.println("</code></pre>");

        printVersion(out);

        out.println("</body></html>");
    }

    String userAgent = request.getHeader("User-Agent");

    if (userAgent != null && userAgent.indexOf("MSIE") >= 0) {
        out.print(MSIE_PADDING);
    }

    out.close();
}