Example usage for javax.servlet ServletException getRootCause

List of usage examples for javax.servlet ServletException getRootCause

Introduction

In this page you can find the example usage for javax.servlet ServletException getRootCause.

Prototype


public Throwable getRootCause() 

Source Link

Document

Returns the exception that caused this servlet exception.

Usage

From source file:com.netspective.sparx.navigate.NavigationPage.java

/**
 * Try to locate the error page that can handle a given exception. First, check if we have any registered pages
 * that handle the class of the exception, then check our ancestors. If we don't handle the given exception class
 * and neither do our ancestors, check the superclass of the exception in our list and our ancestors. Keep doing
 * the check until a navigation page is found. If a page is found the navigation context's error information will
 * be appropriately set./*from   w  w w.  java 2 s  . c o m*/
 *
 * @param t The exception that we would like to find a error page for
 *
 * @return True if we found a page, false if no page was found
 */
public boolean findErrorPage(NavigationContext nc, Throwable t) {
    if (t instanceof ServletException) {
        ServletException se = (ServletException) t;
        Throwable rootCause = se.getRootCause();
        if (rootCause != null) {
            if (findErrorPage(nc, rootCause))
                return true;
        }
    }

    // if we're dealing with a nested exception, check to see if one of the nested exceptions is something we
    // need to handle
    if (t instanceof NestableException) {
        NestableException ne = (NestableException) t;
        Throwable[] throwables = ne.getThrowables();
        for (int i = 0; i < throwables.length; i++) {
            Throwable nestedException = throwables[i];
            if (t.getClass() == nestedException.getClass()) // don't get stuck in an infinite loop
                continue;

            if (findErrorPage(nc, nestedException))
                return true;
        }
    }

    Class exceptionClass = t.getClass();
    while (exceptionClass != null) {
        for (int i = 0; i < errorPagesList.size(); i++) {
            NavigationErrorPage errorPage = (NavigationErrorPage) errorPagesList.get(i);
            if (errorPage.canHandle(t, false) || errorPage.canHandle(exceptionClass, false)) {
                nc.setErrorPageException(errorPage, t, exceptionClass);
                return true;
            }

            // check if we can handle of the interfaces of the current exception class
            Class[] interfaces = exceptionClass.getInterfaces();
            for (int intf = 0; intf < interfaces.length; intf++) {
                Class interfaceClass = interfaces[intf];
                if (errorPage.canHandle(interfaceClass, false)) {
                    nc.setErrorPageException(errorPage, t, interfaceClass);
                    return true;
                }
            }
        }

        exceptionClass = exceptionClass.getSuperclass();
        if (!Throwable.class.isAssignableFrom(exceptionClass))
            break;
    }

    NavigationPage parentPage = (NavigationPage) getParent();
    if (parentPage != null) {
        if (parentPage.findErrorPage(nc, t))
            return true;
    }

    // if we get to here, neither we nor our ancestors know how to handle this exception so plead ignorance
    return false;
}

From source file:edu.harvard.hul.ois.pds.ws.PDSWebService.java

/**
 * Process HTTP GET request./*from   w ww . j  av  a  2s .  c o m*/
*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, FileNotFoundException {

    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req);

    //Get parameters from the URL
    String sOp = req.getParameter("op");
    char op = 'f';
    if (sOp != null) {
        op = sOp.charAt(0);
    }

    String uri = req.getRequestURI();
    uri = uri.substring(1);
    String[] uriElements = uri.split("/");
    Integer id = null;
    String action = null;
    if (uriElements.length > 2) {
        action = uriElements[1];
        if (action.equalsIgnoreCase(API_SEARCH)) //go straight to fts
        {
            String docParam;
            if ((uriElements[2]).equalsIgnoreCase("global")) {
                docParam = "";
            } else {
                try {
                    id = new Integer(uriElements[2]);
                } catch (Exception e) {
                    printError(req, res, "Invalid DRS ID", null);
                    return;
                }
                docParam = "G=" + id + "&";
            }
            String format = "";
            format = req.getParameter("F");
            if (format != null) {
                format = "&F=" + format;
            } else {
                format = "&F=M";
            }
            String range = "";
            String advparams = "";
            range = req.getParameter("B");
            if (range != null) {
                range = "&B=" + range;
            } else {
                range = "";
            }
            String dataQualification = "";
            dataQualification = req.getParameter("D");
            if (dataQualification != null) {
                dataQualification = "&D=" + dataQualification;
            } else {
                dataQualification = "";
            }
            String contextScope = "";
            contextScope = req.getParameter("C");
            if (contextScope != null) {
                contextScope = "&C=" + contextScope;
            } else {
                contextScope = "";
            }
            String jumplistRefs = "";
            jumplistRefs = req.getParameter("J");
            if (jumplistRefs != null) {
                jumplistRefs = "&J=" + jumplistRefs;
            } else {
                jumplistRefs = "";
            }
            String lowerDate = "";
            lowerDate = req.getParameter("L");
            if (lowerDate != null) {
                lowerDate = "&L=" + lowerDate;
            } else {
                lowerDate = "";
            }
            String upperDate = "";
            upperDate = req.getParameter("U");
            if (upperDate != null) {
                upperDate = "&U=" + upperDate;
            } else {
                upperDate = "";
            }
            String resultsize = "";
            resultsize = req.getParameter("P");
            if (resultsize != null) {
                resultsize = "&P=" + resultsize;
            } else {
                resultsize = "";
            }
            advparams = resultsize + range + dataQualification + contextScope + jumplistRefs + lowerDate
                    + upperDate;

            //Log the search page request
            WebAppLogMessage message = new WebAppLogMessage(req, true);
            message.setContext("search");
            message.setMessage("Search Request: " + id);
            logger.info(message);
            String Query = req.getParameter("Q");
            if (Query == null) {
                Query = "";
            }
            try {
                String queryString = new String("?" + docParam + "Q=" + Query + format + advparams);
                wrapper.setAttribute("searchurl", ftsUrl + queryString);
                RequestDispatcher rd = req.getRequestDispatcher("/api-search.jsp?");
                rd.forward(req, res);
                //res.sendRedirect(ftsUrl+queryString);
                return;
            } catch (Exception e) {
                message = new WebAppLogMessage(req, true);
                message.setContext("main");
                Throwable root = e;
                if (e instanceof ServletException) {
                    ServletException se = (ServletException) e;
                    Throwable t = se.getRootCause();
                    if (t != null) {
                        logger.error(message, t);
                        root = t;
                    } else {
                        logger.error(message, se);
                    }
                } else {
                    logger.error(message, e);
                }
                printError(req, res, "PDS-WS Error", root);
            }

        }
        try {
            id = new Integer(uriElements[2]);
        } catch (Exception e) {
        }
    }
    if (id == null) {
        printError(req, res, "Invalid DRS ID", null);
        return;
    }

    String n = req.getParameter("n");
    if (n == null) {
        n = "1";
    } else if (n.equals("")) {
        printError(req, res, "Page not found", null);
        return;
    }
    //Set scaling factors. s overrides imagesize.  Image size select
    //boxes are based on S.
    String scale = req.getParameter("s");
    String imagesize = req.getParameter("imagesize");
    if (scale == null || !(scale.equals("2") || scale.equals("4") || scale.equals("6") || scale.equals("8"))) {
        if (imagesize != null && imagesize.equals("300")) {
            scale = "8";
        } else if (imagesize != null && imagesize.equals("600")) {
            scale = "6";
        } else if (imagesize != null && imagesize.equals("1200")) {
            scale = "4";
        } else if (imagesize != null && imagesize.equals("2400")) {
            scale = "2";
        } else {
            scale = "4";
        }
    }
    if (imagesize == null || !(imagesize.equals("300") || imagesize.equals("600") || imagesize.equals("1200")
            || imagesize.equals("2400"))) {
        if (scale.equals("2")) {
            imagesize = "2400";
        } else if (scale.equals("4")) {
            imagesize = "1200";
        } else if (scale.equals("6")) {
            imagesize = "600";
        } else if (scale.equals("8")) {
            imagesize = "300";
        }
    }
    String jp2Rotate = req.getParameter("rotation");
    if (jp2Rotate == null || jp2Rotate.equals("360") || jp2Rotate.equals("-360")) {
        jp2Rotate = "0";
    } else if (jp2Rotate.equals("-90")) {
        jp2Rotate = "270";
    }
    String jp2x = req.getParameter("jp2x");
    if (jp2x == null) {
        jp2x = "0";
    }
    String jp2y = req.getParameter("jp2y");
    if (jp2y == null) {
        jp2y = "0";
    }
    String jp2Res = req.getParameter("jp2Res");

    String bbx1 = req.getParameter("bbx1");
    if (bbx1 == null) {
        bbx1 = "0";
    }
    String bby1 = req.getParameter("bby1");
    if (bby1 == null) {
        bby1 = "0";
    }
    String bbx2 = req.getParameter("bbx2");
    if (bbx2 == null) {
        bbx2 = "0";
    }
    String bby2 = req.getParameter("bby2");
    if (bby2 == null) {
        bby2 = "0";
    }
    String printThumbnails = req.getParameter("printThumbnails");
    if (printThumbnails == null) {
        printThumbnails = "no";
    }
    wrapper.setAttribute("printThumbnails", printThumbnails);

    //cg debug
    System.out.println("debug1- imagesize: " + imagesize + " jp2Res: " + jp2Res + " scale: " + scale);

    String clickX = req.getParameter("thumbnail.x");
    if (clickX != null) {
        wrapper.setAttribute("clickX", clickX);
    } else {
        clickX = (String) wrapper.getAttribute("clickX");
    }
    String clickY = req.getParameter("thumbnail.y");
    if (clickX != null) {
        wrapper.setAttribute("clickY", clickY);
    } else {
        clickY = (String) wrapper.getAttribute("clickY");
    }
    //cg debug
    System.out.println("debug1- thumbnail.x: " + clickX);
    System.out.println("debug1- X: " + req.getParameter("x"));
    System.out.println("debug1- thumbnail.y: " + clickY);
    System.out.println("debug1- Y: " + req.getParameter("y"));

    /**********************************************************
     * Create new, or use existing Session
     **********************************************************/
    HttpSession session = req.getSession(true);

    PdsUserState pdsUser = (PdsUserState) session.getAttribute("PdsUser");
    CacheItem item = memcache.getObject(pdsUser.getMeta());
    InternalMets mets = item.getMets();

    //compare request header if-modified-since with METS DRS last modified
    //TODO This is temporarily disabled to allow crawlers access to updated
    // content that they may have already indexed
    /*
    Date metsLastModified = item.getLastModifiedDate();
    try {
       long header = req.getDateHeader("If-Modified-Since");
       if (header > 0) {
    Date headerDate = new Date(header);
    if (metsLastModified.before(headerDate)) {
       res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
       return;
    }
       }
    } catch (Exception e) {
       e.printStackTrace();
       // we just ignore this
    }
    */

    //Set the last modified response value
    //TODO Warning - this causes browsers to have problems refreshing the
    // navigation tree html.  Possibly this can be set for the content and
    // citation frames?
    //res.setDateHeader("Last-Modified", metsLastModified.getTime());

    /******************************************************************************
     *  Get the flags for if doing a page number (p) or sequence number(s) page find
     *  If p is null, look up sequence, if it is not null, look up with page number.
     * if getContentPage returns null, the page does not exist or an invalid number was
     * entered.
     ******************************************************************************/
    PageDiv pdiv = null;
    try {
        String pageMode = req.getParameter("P");
        if (pageMode == null || !pageMode.equals("p")) {
            pageMode = "s";
        }
        //if a page number search trim n
        if (pageMode.equals("p")) {
            n = n.replace(']', ' ');
            n = n.replace('[', ' ');
            n = n.trim();
        }
        pdiv = mets.getContentPage(n, pageMode);
        //if pdiv is a jpeg2000 and res is null then calculate default res value
        //SET DEFAULT SIZE IF RES NOT SET
        if (jp2Res == null && pdiv.getDefaultImageMimeType().equals("image/jp2")) {

            //judaica fix
            int maxJP2sz = getMaxJP2DisplaySize(pdiv.getDefaultImageID());
            if ((maxJP2sz > 300) && (maxJP2sz < 600)) {
                maxJP2sz = 300;
                scale = "8";
            } else if ((maxJP2sz > 600) && (maxJP2sz < 1200)) {
                maxJP2sz = 600;
                scale = "6";
            } else if ((maxJP2sz > 1200) && (maxJP2sz < 2400)) {
                maxJP2sz = 1200;
                scale = "4";
            } else if (maxJP2sz > 2400) {
                maxJP2sz = 2400;
                scale = "2";
            }
            String origImagesize = imagesize;
            if (Integer.parseInt(imagesize) > maxJP2sz) {
                imagesize = Integer.toString(maxJP2sz);
            }

            String filepath = getFilePath(pdiv.getDefaultImageID());
            Jpeg2000 jp2 = new Jpeg2000(new File(filepath));
            int newRes = jp2.findResolutionLevelContainedBy(Integer.parseInt(origImagesize),
                    Integer.parseInt(origImagesize));

            //convert Res to a scaling decimal
            if (newRes == 1)
                jp2Res = "1";
            else if (newRes == 2)
                jp2Res = ".5";
            else if (newRes == 3)
                jp2Res = ".25";
            else if (newRes == 4)
                jp2Res = ".125";
            else if (newRes == 5)
                jp2Res = ".0625";
            else if (newRes > 5) {
                jp2Res = "0.625";
            }
            //recalculate newRes if judaica maxres has changed
            //the actual imagesize
            if (!imagesize.equals(origImagesize)) {
                int oldImgsize = Integer.parseInt(origImagesize);
                int newImgsize = Integer.parseInt(imagesize);
                float factor = (oldImgsize / newImgsize) / 2;
                System.out.println("new factor: " + Double.toString(factor));
                jp2Res = Double.toString(Double.parseDouble(jp2Res) / factor);
            }

            //cg debug
            //System.out.println("debug2- newRes: " + newRes + " jp2Res is now: " + jp2Res + " scale: " + scale );
        }
        if (pdiv != null && pageMode.equals("p")) {
            n = String.valueOf(pdiv.getOrder());
            //to keep n in the address bar current, redirect to new URL with equivalent n value of page number
            res.sendRedirect(pdsUrl + "/view/" + id + "?n=" + n + "&s=" + scale
                    + (imagesize != null ? "&imagesize=" + imagesize : "")
                    + (jp2Res != null ? "&jp2Res=" + jp2Res : "")
                    + (jp2Rotate != null ? "&rotation=" + jp2Rotate : ""));
            return;
        }
    } catch (Exception e) {
        WebAppLogMessage message = new WebAppLogMessage();
        message.setContext("find page");
        message.setMessage("invalid page number");
        message.processSessionRequest(req);
        logger.error(message, e);
    }
    if (pdiv == null) {
        printError(req, res, "Page not found", null);
        return;
    }
    /**********************************************************
     *  Process appropriately based on the op variable.
     **********************************************************/
    try {
        /*************************
         * If image is a JP2 and this is not a frame request, figure
         * out x,y to create bounding box on thumbnail
         ***********************/
        if (pdiv.getDefaultImageMimeType().equals("image/jp2")
                && (op != OP_CITATION && op != OP_CONTENT && op != OP_NAVIGATION)) {

            //judaica fix
            int maxJP2size = getMaxJP2DisplaySize(pdiv.getDefaultImageID());
            if ((maxJP2size > 300) && (maxJP2size < 600)) {
                maxJP2size = 300;
                scale = "8";
            } else if ((maxJP2size > 600) && (maxJP2size < 1200)) {
                maxJP2size = 600;
                scale = "6";
            } else if ((maxJP2size > 1200) && (maxJP2size < 2400)) {
                maxJP2size = 1200;
                scale = "4";
            } else if (maxJP2size > 2400) {
                maxJP2size = 2400;
                scale = "2";
            }
            if (Integer.parseInt(imagesize) > maxJP2size) {
                imagesize = Integer.toString(maxJP2size);
            }
            String jp2Action = req.getParameter("action");
            if (jp2Action == null) {
                jp2Action = "noaction";
            }
            int vHeight = Integer.parseInt(imagesize);
            int vWidth = Integer.parseInt(imagesize);
            double imgres = Double.parseDouble(jp2Res);
            //int tWidth = Integer.parseInt(req.getParameter("thumbwidth"));
            //int tHeight = Integer.parseInt(req.getParameter("thumbheight"));
            String filepath = getFilePath(pdiv.getDefaultImageID());
            Coordinate dimension = new Coordinate();
            int x = Integer.parseInt(jp2x);
            int y = Integer.parseInt(jp2y);
            Jpeg2000 jp2 = new Jpeg2000(new File(filepath));

            //String clickX = req.getParameter("thumbnail.x");
            //String clickY = req.getParameter("thumbnail.y");
            int thumbX = -1;
            int thumbY = -1;
            if (clickX != null && clickY != null) {
                thumbX = Integer.parseInt(clickX);
                thumbY = Integer.parseInt(clickY);
            }
            if (jp2Action.equals("noaction")) {
                thumbX = 0;
                thumbY = 0;
            } else if (jp2Action.equals("jp2pan")) {
                x = thumbX;
                y = thumbY;
                //panThumbnail is passed thumbnail scale coordinates. It returns
                //thumbnail scale coordinates so the new X and Y do not need to be
                //extracted from the method return object
                dimension = UIUtil.panThumbnail(vHeight, vWidth, x, y, imgres, jp2, jp2Rotate);
            } else if (jp2Action.equals("jp2zoomin")) {
                dimension = UIUtil.zoom(vHeight, vWidth, x, y, imgres, jp2, true, jp2Rotate);
                Coordinate c = UIUtil.convertFullSizeCoordate(jp2, dimension.getX(), dimension.getY(), vWidth,
                        vHeight, imgres, jp2Rotate);
                thumbX = c.getX();
                thumbY = c.getY();
            } else if (jp2Action.equals("jp2zoomout")) {
                dimension = UIUtil.zoom(vHeight, vWidth, x, y, imgres, jp2, false, jp2Rotate);
                Coordinate c = UIUtil.convertFullSizeCoordate(jp2, dimension.getX(), dimension.getY(), vWidth,
                        vHeight, imgres, jp2Rotate);
                thumbX = c.getX();
                thumbY = c.getY();
            } else if (jp2Action.equals("jp2resize")) {
                String pres = req.getParameter("pres");
                double pvRes = Double.valueOf(pres);
                String previousWidth = req.getParameter("pvWidth");
                String previousHeight = req.getParameter("pvHeight");
                int pvWidth = Integer.parseInt(previousWidth);
                int pvHeight = Integer.parseInt(previousHeight);
                dimension = UIUtil.centerOnResize(vHeight, vWidth, pvHeight, pvWidth, pvRes, x, y, imgres, jp2,
                        jp2Rotate);
                Coordinate c = UIUtil.convertFullSizeCoordate(jp2, dimension.getX(), dimension.getY(), vWidth,
                        vHeight, imgres, jp2Rotate);
                thumbX = c.getX();
                thumbY = c.getY();
            } else if (jp2Action.equals("jp2rotate")) {
                dimension = UIUtil.panThumbnail(vHeight, vWidth, 0, 0, imgres, jp2, jp2Rotate);
                thumbX = 0;
                thumbY = 0;
            }

            jp2x = String.valueOf(dimension.getX());
            jp2y = String.valueOf(dimension.getY());
            req.setAttribute("jp2x", jp2x);
            req.setAttribute("jp2y", jp2y);

            //set up coordinates to draw bounding box on thumbnail
            CoordinatePair bbCoors = UIUtil.getBoundingBoxDimensions(jp2, imgres, vWidth, vHeight, thumbX,
                    thumbY, jp2Rotate);
            bbx1 = Integer.toString(bbCoors.getPoint1().getX());
            bby1 = Integer.toString(bbCoors.getPoint1().getY());
            bbx2 = Integer.toString(bbCoors.getPoint2().getX());
            bby2 = Integer.toString(bbCoors.getPoint2().getY());
        }

        wrapper.setAttribute("cite", mets.getCitationDiv());
        wrapper.setAttribute("pdiv", pdiv);
        /*if(action.equalsIgnoreCase(ACTION_VIEW) || action.equalsIgnoreCase(ACTION_VIEW_TEXT)) {
           int imageId = pdiv.getDefaultImageID();
             wrapper.setAttribute("lastPage",String.valueOf(mets.getCitationDiv().getLastPageNumber()));
             wrapper.setAttribute("imageId",String.valueOf(imageId));
             wrapper.setAttribute("id",id);
             wrapper.setAttribute("n",n);
             wrapper.setAttribute("s",scale);
             wrapper.setAttribute("mime",pdiv.getDefaultImageMimeType());
             wrapper.setAttribute("filepath",getFilePath(imageId));
             wrapper.setAttribute("idsUrl",idsUrl);
             wrapper.setAttribute("cache",cache);
             wrapper.setAttribute("cacheUrl",pdsUrl+cacheUrl);
             wrapper.setAttribute("jp2Rotate",jp2Rotate);
             wrapper.setAttribute("jp2Res",jp2Res);
             wrapper.setAttribute("jp2x",jp2x);
             wrapper.setAttribute("jp2y",jp2y);
             wrapper.setAttribute("imagesize",imagesize);
             wrapper.setAttribute("bbx1",bbx1);
             wrapper.setAttribute("bby1",bby1);
             wrapper.setAttribute("bbx2",bbx2);
             wrapper.setAttribute("bby2",bby2);
             wrapper.setAttribute("pdsUrl",pdsUrl);
             wrapper.setAttribute("ids",idsUrl);
             wrapper.setAttribute("action",action);
                
           if (op == OP_CITATION)   {
                                if( pdiv.getDefaultImageMimeType().equals("image/jp2") ) {
                                    //get max res for biling code
                                    wrapper.setAttribute("maxjp2res", Integer.toString(getMaxJP2DisplaySize(pdiv.getDefaultImageID())) );
                                }
              RequestDispatcher rd = req.getRequestDispatcher("/citation.jsp?");
              rd.forward(req,res);
           }
           else if (op == OP_CONTENT)   {
         //get paths of the ocr files
         ArrayList<String> ocrPaths = new ArrayList<String>();
         for(int i=0;i<pdiv.getOcrID().size();i++) {
            Integer ocr = (Integer) pdiv.getOcrID().get(i);
            ocrPaths.add(getFilePath(ocr.intValue()));
         }
         wrapper.setAttribute("ocrList",ocrPaths);
                
         //if image is a tiff, convert to gif
         if(pdiv.getDefaultImageMimeType().equals("image/tiff")) {
            String delv = cache + "/" + imageId + "-" + scale + ".gif";
          File file = new File (delv);
          if (!file.exists ()) {
             Runtime rt = Runtime.getRuntime();
             String tiffpath = getFilePath(imageId);
             String exec = giffy + " id=" + imageId + " path=" +
                tiffpath.substring(0,tiffpath.lastIndexOf("/")) + " scale=" + scale +
                " cache=" + cache;
             Process child = rt.exec (exec);
             child.waitFor();
             child.destroy();
          }
         }
         wrapper.setAttribute("caption",item.getImageCaption());
              RequestDispatcher rd = req.getRequestDispatcher("/content.jsp?");
              rd.forward(req,res);
                
           }
           else if (op == OP_NAVIGATION) {
              String treeIndex = req.getParameter("index");
              String treeAction = req.getParameter("treeaction");
                
              if (treeAction != null) {
          if (treeAction.equalsIgnoreCase("expand")) {
             pdsUser.setExpandedNodes(id,item.getAllNodesIndices());
          }
          else if (treeAction.equalsIgnoreCase("collapse")) {
             pdsUser.setExpandedNodes(id,new ArrayList<String>());
          }
              }
              if(treeIndex != null) {
          pdsUser.toggleNode(id,treeIndex);
              }
              wrapper.setAttribute("pdsUser",pdsUser);
                                wrapper.setAttribute("maxThumbnails", maxThumbnails);
              //wrapper.setAttribute("toggleIndex",toggleIndex);
              //wrapper.setAttribute("treeaction",treeAction);
              RequestDispatcher rd = req.getRequestDispatcher("/navigation.jsp?");
              rd.forward(req,res);
           }
           else {
              //Log the frameset request
            WebAppLogMessage message = new WebAppLogMessage(req, true);
            message.setContext("frameset");
            message.setMessage("Frameset Request: " + id);
            logger.info(message);
              RequestDispatcher rd = req.getRequestDispatcher("/frameset.jsp?");
              rd.forward(req,res);
           }
        }
        else if (action.equalsIgnoreCase(ACTION_CITE_INFO)) {
          WebAppLogMessage message = new WebAppLogMessage(req, true);
           message.setContext("fullcitation");
           message.setMessage("Full Citation: " + id + " Seq: " + n);
           logger.info(message);
         wrapper.setAttribute("cite",mets.getCitationDiv());
         wrapper.setAttribute("pdsUrl",pdsUrl);
         wrapper.setAttribute("id",id);
         wrapper.setAttribute("nStr", n+"");
                
         String repos = pdsUser.getMeta().getOwner();
         if (repos == null || repos.equals(""))
            repos = "Harvard University Library";
         String mainUrn =    pdsUser.getMeta().getUrn();
         String pageUrn = pdsUser.getMeta().getUrnFromList("?n=" +n);
           SimpleDateFormat sdf =
              new SimpleDateFormat("dd MMMM yyyy");
           String accDate =  sdf.format(new Date());
           wrapper.setAttribute("accDate", accDate);
         wrapper.setAttribute("repos", repos);
         wrapper.setAttribute("mainUrn", nrsUrl + "/" +mainUrn);
         wrapper.setAttribute("pageUrn", nrsUrl + "/" + pageUrn);
         StringBuffer sb = new StringBuffer("");
         getAllSectionLabels(mets.getCitationDiv(), Integer.parseInt(n), sb);
         sb.delete(0,2);
         wrapper.setAttribute("sectLabels", sb.toString());
         RequestDispatcher rd = req.getRequestDispatcher("/fullcitation.jsp?");
              rd.forward(req,res);
        }
        else if (action.equalsIgnoreCase(ACTION_SEARCH)) {
           //Log the search page request
        WebAppLogMessage message = new WebAppLogMessage(req, true);
        message.setContext("search");
        message.setMessage("Search Request: " + id);
        logger.info(message);
             wrapper.setAttribute("cite",mets.getCitationDiv());
             wrapper.setAttribute("ftsUrl",ftsUrl);
             wrapper.setAttribute("pdsUrl",pdsUrl);
             wrapper.setAttribute("id",id);
        RequestDispatcher rd = req.getRequestDispatcher("/search.jsp?");
           rd.forward(req,res);
        }
        else if (action.equalsIgnoreCase(ACTION_PRINTOPS)) {
        WebAppLogMessage message = new WebAppLogMessage(req, true);
        message.setContext("printops");
        message.setMessage("print options: " + id);
        logger.info(message);
             wrapper.setAttribute("pdsUrl",pdsUrl);
             wrapper.setAttribute("id",id);
             wrapper.setAttribute("n",n);
        RequestDispatcher rd = req.getRequestDispatcher("/printoptions.jsp?");
           rd.forward(req,res);
        }
        else if (action.equalsIgnoreCase(ACTION_PRINT)) {
                   
        }
        else if (action.equalsIgnoreCase(ACTION_LINKS)) {
        WebAppLogMessage message = new WebAppLogMessage(req, true);
        message.setContext("links");
        message.setMessage("display links: " + id);
        logger.info(message);
             wrapper.setAttribute("cite",mets.getCitationDiv());
             wrapper.setAttribute("id",id);
             wrapper.setAttribute("pdsUrl",pdsUrl);
        RequestDispatcher rd = req.getRequestDispatcher("/links.jsp?");
           rd.forward(req,res);
        }*/ //START API CALLS
        if (action.equalsIgnoreCase(API_VIEW) || action.equalsIgnoreCase(API_VIEW_TEXT)) { //main api function. shows ocr'd pages

            int imageId = pdiv.getDefaultImageID();
            wrapper.setAttribute("lastPage", String.valueOf(mets.getCitationDiv().getLastPageNumber()));
            wrapper.setAttribute("imageId", String.valueOf(imageId));
            wrapper.setAttribute("id", id);
            wrapper.setAttribute("n", n);
            wrapper.setAttribute("s", scale);
            wrapper.setAttribute("mime", pdiv.getDefaultImageMimeType());
            wrapper.setAttribute("filepath", getFilePath(imageId));
            wrapper.setAttribute("idsUrl", idsUrl);
            wrapper.setAttribute("cache", cache);
            wrapper.setAttribute("cacheUrl", pdsUrl + cacheUrl);
            wrapper.setAttribute("jp2Rotate", jp2Rotate);
            wrapper.setAttribute("jp2Res", jp2Res);
            wrapper.setAttribute("jp2x", jp2x);
            wrapper.setAttribute("jp2y", jp2y);
            wrapper.setAttribute("imagesize", imagesize);
            wrapper.setAttribute("bbx1", bbx1);
            wrapper.setAttribute("bby1", bby1);
            wrapper.setAttribute("bbx2", bbx2);
            wrapper.setAttribute("bby2", bby2);
            wrapper.setAttribute("pdsUrl", pdsUrl);
            wrapper.setAttribute("ids", idsUrl);
            wrapper.setAttribute("action", action);

            //get paths of the ocr files
            ArrayList<String> ocrPaths = new ArrayList<String>();
            for (int i = 0; i < pdiv.getOcrID().size(); i++) {
                Integer ocr = (Integer) pdiv.getOcrID().get(i);
                ocrPaths.add(getFilePath(ocr.intValue()));
            }
            wrapper.setAttribute("ocrList", ocrPaths);

            //if image is a tiff, convert to gif
            if (pdiv.getDefaultImageMimeType().equals("image/tiff")) {
                String delv = cache + "/" + imageId + "-" + scale + ".gif";
                File file = new File(delv);
                if (!file.exists()) {
                    Runtime rt = Runtime.getRuntime();
                    String tiffpath = getFilePath(imageId);
                    String exec = giffy + " id=" + imageId + " path="
                            + tiffpath.substring(0, tiffpath.lastIndexOf("/")) + " scale=" + scale + " cache="
                            + cache;
                    Process child = rt.exec(exec);
                    child.waitFor();
                    child.destroy();
                }
            }
            wrapper.setAttribute("caption", item.getImageCaption());
            RequestDispatcher rd = req.getRequestDispatcher("/api-content.jsp?");
            rd.forward(req, res);

        } else if (action.equalsIgnoreCase(API_LINKS)) {
            WebAppLogMessage message = new WebAppLogMessage(req, true);
            message.setContext("links");
            message.setMessage("display links: " + id);
            logger.info(message);
            wrapper.setAttribute("cite", mets.getCitationDiv());
            wrapper.setAttribute("id", id);
            wrapper.setAttribute("pdsUrl", pdsUrl);
            wrapper.setAttribute("n", n);
            RequestDispatcher rd = req.getRequestDispatcher("/api-links.jsp?");
            rd.forward(req, res);
        } else if (action.equalsIgnoreCase(API_CITE_INFO)) {
            WebAppLogMessage message = new WebAppLogMessage(req, true);
            message.setContext("fullcitation");
            message.setMessage("Full Citation: " + id + " Seq: " + n);
            logger.info(message);
            wrapper.setAttribute("cite", mets.getCitationDiv());
            wrapper.setAttribute("pdsUrl", pdsUrl);
            wrapper.setAttribute("id", id);
            wrapper.setAttribute("nStr", n + "");

            String repos = pdsUser.getMeta().getOwner();
            if (repos == null || repos.equals(""))
                repos = "Harvard University Library";
            String mainUrn = pdsUser.getMeta().getUrn();
            String pageUrn = pdsUser.getMeta().getUrnFromList("?n=" + n);
            SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");
            String accDate = sdf.format(new Date());
            wrapper.setAttribute("accDate", accDate);
            wrapper.setAttribute("repos", repos);
            wrapper.setAttribute("mainUrn", nrsUrl + "/" + mainUrn);
            wrapper.setAttribute("pageUrn", nrsUrl + "/" + pageUrn);
            StringBuffer sb = new StringBuffer("");
            getAllSectionLabels(mets.getCitationDiv(), Integer.parseInt(n), sb);
            sb.delete(0, 2);
            wrapper.setAttribute("sectLabels", sb.toString());
            RequestDispatcher rd = req.getRequestDispatcher("/api-fullcitation.jsp?");
            rd.forward(req, res);
        } else if (action.equalsIgnoreCase(API_DOC_TREE)) {
            String treeIndex = req.getParameter("index");
            String treeAction = req.getParameter("treeaction");

            /*if (treeAction != null)
            {
                if (treeAction.equalsIgnoreCase("expand")) {
                    pdsUser.setExpandedNodes(id,item.getAllNodesIndices());
            }
                else if (treeAction.equalsIgnoreCase("collapse")) {
            pdsUser.setExpandedNodes(id,new ArrayList<String>());
            }
            }
            if(treeIndex != null) {
                    pdsUser.toggleNode(id,treeIndex);
            }*/
            //expand the tree
            pdsUser.setExpandedNodes(id, item.getAllNodesIndices());
            wrapper.setAttribute("pdsUser", pdsUser);
            wrapper.setAttribute("pdsUrl", pdsUrl);
            wrapper.setAttribute("cacheUrl", pdsUrl + cacheUrl);
            wrapper.setAttribute("cache", cache);
            wrapper.setAttribute("id", id);
            wrapper.setAttribute("n", n);
            wrapper.setAttribute("s", scale);
            wrapper.setAttribute("action", "get");
            wrapper.setAttribute("idsUrl", idsUrl);
            wrapper.setAttribute("maxThumbnails", maxThumbnails);
            wrapper.setAttribute("jp2Rotate", jp2Rotate);
            wrapper.setAttribute("jp2x", jp2x);
            wrapper.setAttribute("jp2y", jp2y);
            wrapper.setAttribute("caption", item.getImageCaption());
            //wrapper.setAttribute("toggleIndex",toggleIndex);
            //wrapper.setAttribute("treeaction",treeAction);
            RequestDispatcher rd = req.getRequestDispatcher("/api-navigation.jsp?");
            rd.forward(req, res);
        } //todo?
        else if (action.equalsIgnoreCase(API_MAX_SECTIONS)) {

        } else if (action.equalsIgnoreCase(API_MAX_PAGES)) {

        } else if (action.equalsIgnoreCase(API_MAX_CHAPTERS)) {

        }

    } //END MAIN
    catch (Exception e) {
        WebAppLogMessage message = new WebAppLogMessage(req, true);
        message.setContext("main");
        Throwable root = e;
        if (e instanceof ServletException) {
            ServletException se = (ServletException) e;
            Throwable t = se.getRootCause();
            if (t != null) {
                logger.error(message, t);
                root = t;
            } else {
                logger.error(message, se);
            }
        } else {
            logger.error(message, e);
        }
        printError(req, res, "PDS-WS Error", root);
    }
}

From source file:org.ajax4jsf.webapp.BaseXMLFilter.java

/**
 * Perform filter chain with xml parsing and transformation. Subclasses must
 * implement concrete HTML to XML parsing, nesseasary transformations and
 * serialization.//from  w w  w  .  j av a 2  s  .  com
 * 
 * @param chain
 * @param httpServletRequest
 * @param httpServletResponse
 * @throws ServletException
 * @throws IOException
 */
protected void doXmlFilter(FilterChain chain, HttpServletRequest request, final HttpServletResponse response)
        throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("XML filter service start processing request");
    }
    FilterServletResponseWrapper servletResponseWrapper = getWrapper(response);
    // HACK - to avoid MyFaces <f:view> incompabilites and bypass
    // intermediaty filters
    // in chain, self-rendered region write directly to wrapper stored in
    // request-scope attribute.
    try {
        request.setAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE, servletResponseWrapper);
        chain.doFilter(request, servletResponseWrapper);

    } catch (ServletException e) {
        if (handleViewExpiredOnClient && (isViewExpired(e) || isViewExpired(e.getRootCause()))
                && isAjaxRequest(request)) {
            log.debug("ViewExpiredException in the filter chain - will be handled on the client", e);
            Writer output = resetResponse(response, servletResponseWrapper, "true");
            String message = Messages.getMessage(Messages.AJAX_VIEW_EXPIRED);
            response.setHeader(AJAX_EXPIRED, message);
            output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>" + "<meta name=\""
                    + AjaxContainerRenderer.AJAX_FLAG_HEADER + "\" content=\"true\" />" + "<meta name=\""
                    + AJAX_EXPIRED + "\" content=\"" + message + "\" />" + "</head></html>");
            output.flush();
            response.flushBuffer();
            return;
        } else {
            log.error("Exception in the filter chain", e);
            throw e;
        }
    } finally {
        request.removeAttribute(BaseFilter.RESPONSE_WRAPPER_ATTRIBUTE);
    }
    String viewId = (String) request.getAttribute(AjaxViewHandler.VIEW_ID_KEY);
    Node[] headEvents = (Node[]) request.getAttribute(AjaxContext.HEAD_EVENTS_PARAMETER);

    HtmlParser parser = null;
    // setup response
    // Redirect in AJAX request - convert to special response recognized by
    // client.
    String redirectLocation = servletResponseWrapper.getRedirectLocation();
    String characterEncoding = servletResponseWrapper.getCharacterEncoding();
    Writer output;
    if (null != redirectLocation) {
        if (isAjaxRequest(request)) {
            // Special handling of redirect - client-side script must
            // Check for response and perform redirect by window.location
            if (log.isDebugEnabled()) {
                log.debug("Create AJAX redirect response to url: " + redirectLocation);
            }
            output = resetResponse(response, servletResponseWrapper, "redirect");
            response.setHeader(AjaxContainerRenderer.AJAX_LOCATION_HEADER, redirectLocation);
            // For buggy XmlHttpRequest realisations repeat headers in
            // <meta>
            output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                    + "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>" + "<meta name=\""
                    + AjaxContainerRenderer.AJAX_FLAG_HEADER + "\" content=\"redirect\" />" + "<meta name=\""
                    + AjaxContainerRenderer.AJAX_LOCATION_HEADER + "\" content=\"" + redirectLocation + "\" />"
                    + "</head></html>");
            output.flush();
            response.flushBuffer();
        } else {
            response.sendRedirect(redirectLocation);
        }

        return;

    } else {
        if ("true".equals(servletResponseWrapper.getHeaders().get(AjaxContainerRenderer.AJAX_FLAG_HEADER))) {
            if (log.isDebugEnabled()) {
                log.debug("Process response to well-formed XML for AJAX XMLHttpRequest parser");
            }
            // Not caching AJAX request
            response.setHeader("Cache-Control", "no-cache, must-revalidate, max_age=0, no-store");
            response.setHeader("Expires", "0");
            response.setHeader("Pragma", "no-cache");
            // response.setCharacterEncoding(servletResponseWrapper
            // .getCharacterEncoding()); //
            // JSContentHandler.DEFAULT_ENCODING);
            // Set the content-type. For AJAX responses default encoding -
            // UTF8.
            // TODO - for null encoding, setup only Output encoding for
            // filter ?
            String outputEncoding = "UTF-8";
            String contentType = getMimetype() + ";charset=" + outputEncoding;
            response.setContentType(contentType);
            parser = getParser(getMimetype(), true, viewId);
            if (null == parser) {
                throw new ServletException(
                        Messages.getMessage(Messages.PARSER_NOT_INSTANTIATED_ERROR, contentType));
            }
            output = createOutputWriter(response, outputEncoding);
            parser.setDoctype(getPublicid());
            parser.setInputEncoding(characterEncoding);
            parser.setOutputEncoding(outputEncoding);
            parser.setViewState((String) request.getAttribute(AjaxViewHandler.SERIALIZED_STATE_KEY));
        } else {
            // setup conversion reules for output contentType, send directly
            // if content not
            // supported by tidy.
            String contentType = servletResponseWrapper.getContentType();
            String contentTypeCharset = contentType;
            if (log.isDebugEnabled()) {
                log.debug("create HTML/XML parser for content type: " + contentType);
            }
            // if(contentType == null){
            // contentType = request.getContentType();
            // }
            boolean forcenotrf = isForcenotrf();

            if (forcenotrf || !servletResponseWrapper.isError()) {
                if (forcenotrf || (headEvents != null && headEvents.length != 0)) {
                    if (contentTypeCharset != null) {
                        if (contentTypeCharset.indexOf("charset") < 0 && null != characterEncoding) {
                            contentTypeCharset += ";charset=" + characterEncoding;
                        }
                        parser = getParser(contentTypeCharset, false, viewId);
                        if (null == parser) {
                            if (log.isDebugEnabled()) {
                                log.debug(
                                        "Parser not have support for the such content type, send response as-is");
                            }
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("No resource inclusions detected, send response as-is");
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Servlet error occured, send response as-is");
                }
            }

            // null or unsupported content type
            if (null == parser) {
                try {
                    if (servletResponseWrapper.isUseWriter()) {
                        if (contentTypeCharset != null) {
                            response.setContentType(contentTypeCharset);
                        }

                        output = createOutputWriter(response, characterEncoding);
                        servletResponseWrapper.sendContent(output);
                    } else if (servletResponseWrapper.isUseStream()) {
                        if (contentType != null) {
                            response.setContentType(contentType);
                        }

                        ServletOutputStream out = response.getOutputStream();
                        servletResponseWrapper.sendContent(out);
                    }
                } finally {
                    // reuseWrapper(servletResponseWrapper);
                }

                return;
            }

            if (contentTypeCharset != null) {
                response.setContentType(contentTypeCharset);
            }

            output = createOutputWriter(response, characterEncoding);

            parser.setInputEncoding(characterEncoding);
            parser.setOutputEncoding(characterEncoding);
        }
    }

    try {
        // Setup scripts and styles
        parser.setHeadNodes(headEvents);
        // Process parsing.
        long startTimeMills = System.currentTimeMillis();
        servletResponseWrapper.parseContent(output, parser);
        if (log.isDebugEnabled()) {
            startTimeMills = System.currentTimeMillis() - startTimeMills;
            log.debug(Messages.getMessage(Messages.PARSING_TIME_INFO, "" + startTimeMills));
        }
    } catch (Exception e) {
        throw new ServletException(Messages.getMessage(Messages.JTIDY_PARSING_ERROR), e);
    } finally {
        reuseParser(parser);
    }
}

From source file:org.apache.ode.axis2.ODEAxis2Server.java

public void start() throws AxisFault {
    super.start();
    _ode = new ODEServer();
    _ode.txMgrCreatedCallback = txMgrCreatedCallback;
    try {/*  w  w  w .  j a  va2s . c o m*/
        _ode.init(odeRootDir, new ConfigurationContext(configContext.getAxisConfiguration()), config);
    } catch (ServletException e) {
        throw new RuntimeException(e.getRootCause());
    }
}

From source file:org.apache.tiles.servlet.context.ServletUtil.java

/**
 * Wraps a ServletException to create an IOException with the root cause if present.
 *
 * @param ex The exception to wrap./* w  w  w  .j  ava2 s  .c o  m*/
 * @param message The message of the exception.
 * @return The wrapped exception.
 * @since 2.1.1
 */
public static IOException wrapServletException(ServletException ex, String message) {
    IOException retValue;
    Throwable rootCause = ex.getRootCause();
    if (rootCause != null) {
        // Replace the ServletException with an IOException, with the root
        // cause of the first as the cause of the latter.
        retValue = new TilesIOException(message, rootCause);
    } else {
        retValue = new TilesIOException(message, ex);
    }

    return retValue;
}

From source file:org.codehaus.enunciate.modules.rest.RESTContentTypeRoutingController.java

/**
 * Redirects the request to the location of the specific content type.
 *
 * @param request The request.//from  ww w  .j a v  a  2s.co  m
 * @param response The response.
 * @return null
 */
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (getContentTypeSupport() != null) {
        String requestContext = request.getRequestURI().substring(request.getContextPath().length());
        Matcher matcher = replacePattern.matcher(requestContext);
        if (matcher.find()) {
            List<String> contentTypes = getContentTypesByPreference(request);

            for (String contentType : contentTypes) {
                String contentTypeId = lookupContentTypeId(contentType);
                if (contentTypeId != null) {
                    String redirect = matcher
                            .replaceFirst("/" + URLEncoder.encode(contentTypeId, "UTF-8") + "/");
                    RequestDispatcher dispatcher = request.getRequestDispatcher(redirect);
                    if (dispatcher != null) {
                        try {
                            dispatcher.forward(request, response);
                        } catch (ServletException e) {
                            if (e.getRootCause() instanceof Exception) {
                                throw (Exception) e.getRootCause();
                            } else {
                                throw e;
                            }
                        }
                        return null;
                    }
                }
            }
        }
    }

    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return null;

}

From source file:org.dspace.app.webui.jsptag.LayoutTag.java

public int doEndTag() throws JspException {
    // Context objects
    ServletRequest request = pageContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
    ServletConfig config = pageContext.getServletConfig();

    // header file
    String header = templatePath + "header-default.jsp";

    // Choose default style unless one is specified
    if (style != null) {
        header = templatePath + "header-" + style.toLowerCase() + ".jsp";
    }//from  www .j av a 2s.  c o  m

    if (sidebar != null) {
        request.setAttribute("dspace.layout.sidebar", sidebar);
    }

    // Now include the header
    try {
        // Set headers to prevent browser caching, if appropriate
        if ((noCache != null) && noCache.equalsIgnoreCase("true")) {
            response.addDateHeader("expires", 1);
            response.addHeader("Pragma", "no-cache");
            response.addHeader("Cache-control", "no-store");
        }

        // Ensure the HTTP header will declare that UTF-8 is used
        // in the response.
        response.setContentType("text/html; charset=UTF-8");

        RequestDispatcher rd = config.getServletContext().getRequestDispatcher(header);

        rd.include(request, response);

        //pageContext.getOut().write(getBodyContent().getString());
        getBodyContent().writeOut(pageContext.getOut());
    } catch (IOException ioe) {
        throw new JspException("Got IOException: " + ioe);
    } catch (ServletException se) {
        log.warn("Exception", se.getRootCause());
        throw new JspException("Got ServletException: " + se);
    }

    // Footer file to use
    String footer = templatePath + "footer-default.jsp";

    // Choose default flavour unless one is specified
    if (style != null) {
        footer = templatePath + "footer-" + style.toLowerCase() + ".jsp";
    }

    try {
        // Ensure body is included before footer
        pageContext.getOut().flush();

        RequestDispatcher rd = config.getServletContext().getRequestDispatcher(footer);

        rd.include(request, response);
    } catch (ServletException se) {
        throw new JspException("Got ServletException: " + se);
    } catch (IOException ioe) {
        throw new JspException("Got IOException: " + ioe);
    }

    style = null;
    title = null;
    sidebar = null;
    navbar = null;
    locbar = null;
    parentTitle = null;
    parentLink = null;
    noCache = null;
    feedData = null;
    return EVAL_PAGE;
}

From source file:org.jahia.admin.users.ManageGroups.java

/**
 * Forward the servlet request and servlet response objects, using the request
 * dispatcher (from the ServletContext). Note: please be careful, use only
 * context relative path.//from  www .  j a  va 2  s  .co m
 *
 * @param request
 * @param response
 * @param session
 * @param target   context-relative path.
 * @throws IOException
 * @throws ServletException
 */
private void doRedirect(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        String target) throws IOException, ServletException {
    try {
        request.setAttribute("currentSiteBean", jahiaSite);

        // check null warning msg
        if (request.getAttribute("warningMsg") == null) {
            request.setAttribute("warningMsg", "");
        }

        // check null jsp bottom message, and fill in if necessary...
        if (request.getAttribute("msg") == null) {
            request.setAttribute("msg", Jahia.COPYRIGHT);
        }

        if (request.getAttribute("focus") == null) {
            request.setAttribute("focus", "-none-");
        }

        // check null configuration step title, and fill in if necessary...
        if (request.getAttribute("title") == null) {
            request.setAttribute("title", "Manage Groups");
        }

        // redirect!
        JahiaAdministration.doRedirect(request, response, session, target);

    } catch (IOException ie) {
        logger.error("Error ", ie);
    } catch (ServletException se) {
        logger.error("Error ", se);
        if (se.getRootCause() != null) {
            logger.error("Error root cause", se.getRootCause());
        }
    }
}

From source file:org.jahia.admin.users.ManageUsers.java

/**
 * Forward the servlet request and servlet response objects, using the request
 * dispatcher (from the ServletContext). Note: please be careful, use only
 * context relative path.//from   ww w.  j a  v a2 s  .com
 *
 * @param       request             servlet request.
 * @param       response            servlet response.
 * @param       session             Servlet session for the current user.
 * @param       target              target, context-relative path.
 * @exception   IOException         an I/O exception occured during the process.
 * @exception   ServletException    a servlet exception occured during the process.
 */
private void doRedirect(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        String target) throws IOException, ServletException {
    try {
        // check null warning msg
        if (request.getAttribute("warningMsg") == null) {
            request.setAttribute("warningMsg", "");
        }

        // check null jsp bottom message, and fill in if necessary...
        if (request.getAttribute("msg") == null) {
            request.setAttribute("msg", Jahia.COPYRIGHT);
        }

        // check null configuration step title, and fill in if necessary...
        if (request.getAttribute("title") == null) {
            request.setAttribute("title", "Manage Users");
        }

        // redirect!
        JahiaAdministration.doRedirect(request, response, session, target);

    } catch (IOException ie) {
        logger.error("Error ", ie);
    } catch (ServletException se) {
        logger.error("Error ", se);
        if (se.getRootCause() != null) {
            logger.error("Error root cause", se.getRootCause());
        }
    }
}

From source file:org.opencms.main.OpenCmsCore.java

/**
 * This method performs the error handling for OpenCms.<p>
 *
 * @param cms the current cms context, might be null !
 * @param req the client request/* www .jav a2s  .  c  o m*/
 * @param res the client response
 * @param t the exception that occurred
 */
private void errorHandling(CmsObject cms, HttpServletRequest req, HttpServletResponse res, Throwable t) {

    // remove the controller attribute from the request
    CmsFlexController.removeController(req);

    boolean canWrite = (!res.isCommitted() && !res.containsHeader("Location"));
    int status = -1;
    boolean isGuest = true;

    if (t instanceof ServletException) {
        ServletException s = (ServletException) t;
        if (s.getRootCause() != null) {
            t = s.getRootCause();
        }
    } else if (t instanceof CmsSecurityException) {
        // access error - display login dialog
        if (canWrite) {
            try {
                m_authorizationHandler.requestAuthorization(req, res, getLoginFormURL(req, res));
            } catch (IOException ioe) {
                // there is nothing we can do about this
            }
            return;
        }
    } else if (t instanceof CmsDbEntryNotFoundException) {
        // user or group does not exist
        status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
        isGuest = false;
    } else if (t instanceof CmsVfsResourceNotFoundException) {
        // file not found - display 404 error.
        status = HttpServletResponse.SC_NOT_FOUND;
    } else if (t instanceof CmsException) {
        if (t.getCause() != null) {
            t = t.getCause();
        }
        LOG.error(t.getLocalizedMessage(), t);
    } else {
        LOG.error(t.getLocalizedMessage(), t);
    }

    if (status < 1) {
        // error code not set - set "internal server error" (500)
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    res.setStatus(status);

    try {
        if ((cms != null) && (cms.getRequestContext().getCurrentUser() != null)) {
            isGuest = isGuest && (cms.getRequestContext().getCurrentUser().isGuestUser()
                    || cms.userInGroup(cms.getRequestContext().getCurrentUser().getName(),
                            OpenCms.getDefaultUsers().getGroupGuests()));
        }
    } catch (CmsException e) {
        // result is false
        LOG.error(e.getLocalizedMessage(), e);
    }

    if (canWrite) {
        res.setContentType("text/html");
        CmsRequestUtil.setNoCacheHeaders(res);
        if (!isGuest && (cms != null) && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
            try {
                res.setStatus(HttpServletResponse.SC_OK);
                res.getWriter().print(createErrorBox(t, req, cms));
            } catch (IOException e) {
                // can be ignored
                LOG.error(e.getLocalizedMessage(), e);
            }
        } else {
            try {
                res.sendError(status, t.toString());
            } catch (IOException e) {
                // can be ignored
                LOG.error(e.getLocalizedMessage(), e);
            }
        }
    }
}