Example usage for javax.servlet RequestDispatcher forward

List of usage examples for javax.servlet RequestDispatcher forward

Introduction

In this page you can find the example usage for javax.servlet RequestDispatcher forward.

Prototype

public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException;

Source Link

Document

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

Usage

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

/**
 * Main method for handling the logic and content of the page. Generally, a navigation page is broken into
 * several sections: header, metadata, body, and footer. If there are no forwards/redirects configured, the page
 * sections are handled by calling the following methods: <code>handlePageMetaData()</code>, <code>handlePageHeader()</code>,
 * <code>handlePageBody()</code>, and <code>handlePageFooter()</code> methods.
 *
 * @param writer Writer object to write the page output to
 * @param nc     current navigation context
 */// www  .  ja v a 2 s  .  com
public void handlePage(Writer writer, NavigationContext nc) throws ServletException, IOException {
    Flags flags = (Flags) nc.getActiveState().getFlags();

    enterPage(nc);
    if (getBodyType().getValueIndex() == NavigationPageBodyType.FORWARD) {
        // if we're forwarding to another resource we don't want to put anything into the response otherwise
        // there will be an illegal state exception -- so, we don't create headers, footers, etc because that's
        // the user's responsibility in the forwarded resource.

        String forwardUrl = getForward().getTextValue(nc);
        ServletRequest req = nc.getRequest();
        RequestDispatcher rd = req.getRequestDispatcher(forwardUrl);
        req.setAttribute(REQATTRNAME_NAVIGATION_CONTEXT, nc);
        rd.forward(req, nc.getResponse());
        req.removeAttribute(REQATTRNAME_NAVIGATION_CONTEXT);
    } else if (bodyAffectsNavigationContext(nc)) {
        // render the body first and let it modify the navigation context
        StringWriter body = new StringWriter();
        boolean hasError = false;
        try {
            handlePageBody(body, nc);
        } catch (Exception e) {
            getLog().error("Error occurred while handling the page.", e);
            if (!findErrorPage(nc, e))
                nc.setErrorPageException(getOwner().getDefaultErrorPage(), e, e.getClass());
            nc.getErrorPage().handlePageBody(writer, nc);
            hasError = true;
        }

        if (!hasError && !nc.isRedirected()) {
            if (flags.flagIsSet(Flags.HANDLE_META_DATA))
                handlePageMetaData(writer, nc);
            if (flags.flagIsSet(Flags.HANDLE_HEADER))
                handlePageHeader(writer, nc);
            writer.write(body.getBuffer().toString());
            if (flags.flagIsSet(Flags.HANDLE_FOOTER))
                handlePageFooter(writer, nc);
        }

        // try and do an early GC if possible
        body = null;
    } else {
        if (flags.flagIsSet(Flags.HANDLE_META_DATA))
            handlePageMetaData(writer, nc);
        if (flags.flagIsSet(Flags.HANDLE_HEADER))
            handlePageHeader(writer, nc);
        try {
            handlePageBody(writer, nc);
        } catch (Exception e) {
            getLog().error("Error occurred while handling the page.", e);
            if (!findErrorPage(nc, e))
                nc.setErrorPageException(getOwner().getDefaultErrorPage(), e, e.getClass());
            nc.getErrorPage().handlePageBody(writer, nc);
        }
        if (flags.flagIsSet(Flags.HANDLE_FOOTER))
            handlePageFooter(writer, nc);
    }
    exitPage(nc);
}

From source file:org.apache.struts2.dispatcher.ServletDispatcherResult.java

/**
 * Dispatches to the given location. Does its forward via a RequestDispatcher. If the
 * dispatch fails a 404 error will be sent back in the http response.
 *
 * @param finalLocation the location to dispatch to.
 * @param invocation    the execution state of the action
 * @throws Exception if an error occurs. If the dispatch fails the error will go back via the
 *                   HTTP request./*  w ww  .j a v  a  2  s.c  om*/
 */
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Forwarding to location " + finalLocation);
    }

    PageContext pageContext = ServletActionContext.getPageContext();

    if (pageContext != null) {
        pageContext.include(finalLocation);
    } else {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

        //add parameters passed on the location to #parameters
        // see WW-2120
        if (StringUtils.isNotEmpty(finalLocation) && finalLocation.indexOf("?") > 0) {
            String queryString = finalLocation.substring(finalLocation.indexOf("?") + 1);
            Map<String, Object> parameters = getParameters(invocation);
            Map<String, Object> queryParams = urlHelper.parseQueryString(queryString, true);
            if (queryParams != null && !queryParams.isEmpty())
                parameters.putAll(queryParams);
        }

        // if the view doesn't exist, let's do a 404
        if (dispatcher == null) {
            response.sendError(404, "result '" + finalLocation + "' not found");
            return;
        }

        //if we are inside an action tag, we always need to do an include
        Boolean insideActionTag = (Boolean) ObjectUtils
                .defaultIfNull(request.getAttribute(StrutsStatics.STRUTS_ACTION_TAG_INVOCATION), Boolean.FALSE);

        // If we're included, then include the view
        // Otherwise do forward
        // This allow the page to, for example, set content type
        if (!insideActionTag && !response.isCommitted()
                && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
            request.setAttribute("struts.view_uri", finalLocation);
            request.setAttribute("struts.request_uri", request.getRequestURI());

            dispatcher.forward(request, response);
        } else {
            dispatcher.include(request, response);
        }
    }
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo;//from www . j  av a  2s  .c o m
    Enumeration<String> reqRanges = null;
    boolean included = request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null;
    if (included) {
        pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
        if (pathInfo == null) {
            pathInfo = request.getPathInfo();
        }
    } else {
        pathInfo = request.getPathInfo();

        // Is this a Range request?
        reqRanges = request.getHeaders(HeaderFramework.RANGE);
        if (!hasDefinedRange(reqRanges)) {
            reqRanges = null;
        }
    }

    String pathInContext = pathInfo == null ? "/" : pathInfo; // this is the path of the resource in _resourceBase (= path within htroot respective htDocs)
    boolean endsWithSlash = pathInContext.endsWith(URIUtil.SLASH);

    // Find the resource 
    Resource resource = null;

    try {

        // Look for a class resource
        boolean hasClass = false;
        if (reqRanges == null && !endsWithSlash) {
            final int p = pathInContext.lastIndexOf('.');
            if (p >= 0) {
                String pathofClass = pathInContext.substring(0, p) + ".class";
                Resource classresource = _resourceBase.addPath(pathofClass);
                // Does a class resource exist?
                if (classresource != null && classresource.exists() && !classresource.isDirectory()) {
                    hasClass = true;
                }
            }
        }

        // find resource
        resource = getResource(pathInContext);

        if (!hasClass && (resource == null || !resource.exists()) && !pathInContext.contains("..")) {
            // try to get this in the alternative htDocsPath
            resource = Resource.newResource(new File(_htDocsPath, pathInContext));
        }

        if (ConcurrentLog.isFine("FILEHANDLER")) {
            ConcurrentLog.fine("FILEHANDLER",
                    "YaCyDefaultServlet: uri=" + request.getRequestURI() + " resource=" + resource);
        }

        // Handle resource
        if (!hasClass && (resource == null || !resource.exists())) {
            if (included) {
                throw new FileNotFoundException("!" + pathInContext);
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else if (!resource.isDirectory()) {
            if (endsWithSlash && pathInContext.length() > 1) {
                String q = request.getQueryString();
                pathInContext = pathInContext.substring(0, pathInContext.length() - 1);
                if (q != null && q.length() != 0) {
                    pathInContext += "?" + q;
                }
                response.sendRedirect(response
                        .encodeRedirectURL(URIUtil.addPaths(_servletContext.getContextPath(), pathInContext)));
            } else {
                if (hasClass) { // this is a YaCy servlet, handle the template
                    handleTemplate(pathInfo, request, response);
                } else {
                    if (included || passConditionalHeaders(request, response, resource)) {
                        sendData(request, response, included, resource, reqRanges);
                    }
                }
            }
        } else { // resource is directory
            String welcome;

            if (!endsWithSlash) {
                StringBuffer buf = request.getRequestURL();
                synchronized (buf) {
                    int param = buf.lastIndexOf(";");
                    if (param < 0) {
                        buf.append('/');
                    } else {
                        buf.insert(param, '/');
                    }
                    String q = request.getQueryString();
                    if (q != null && q.length() != 0) {
                        buf.append('?');
                        buf.append(q);
                    }
                    response.setContentLength(0);
                    response.sendRedirect(response.encodeRedirectURL(buf.toString()));
                }
            } // else look for a welcome file
            else if (null != (welcome = getWelcomeFile(pathInContext))) {
                ConcurrentLog.fine("FILEHANDLER", "welcome={}" + welcome);

                // Forward to the index
                RequestDispatcher dispatcher = request.getRequestDispatcher(welcome);
                if (dispatcher != null) {
                    if (included) {
                        dispatcher.include(request, response);
                    } else {
                        dispatcher.forward(request, response);
                    }
                }
            } else {
                if (included || passConditionalHeaders(request, response, resource)) {
                    sendDirectory(request, response, resource, pathInContext);
                }
            }
        }
    } catch (IllegalArgumentException e) {
        ConcurrentLog.logException(e);
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    } finally {
        if (resource != null) {
            resource.close();
        }
    }
}

From source file:br.bireme.web.AuthenticationServlet.java

/**
 * Processes requests for both HTTP//from   ww w . j a  v  a  2s . c  om
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding(CODEC);

    final String username = request.getParameter("email");
    final String password = request.getParameter("password");
    final String lang = request.getParameter("lang");
    final ServletContext context = getServletContext();
    final HttpSession session = request.getSession();
    final ResourceBundle messages = Tools.getMessages(lang);

    boolean isAccountsWorking = true;
    RequestDispatcher dispatcher;

    session.removeAttribute("collCenter");
    session.removeAttribute("user");

    if (isAccountsWorking) {
        if ((username == null) || (username.isEmpty()) || (password == null) || (password.isEmpty())) {
            response.sendRedirect(
                    "index.jsp?lang=" + lang + "&errMsg=" + messages.getString("login_is_required"));
            return;
        }

        try {
            final Authentication auth = new Authentication(context.getInitParameter("accounts_host"));
            final JSONObject user = auth.getUser(username, password);
            Set<String> centerIds = auth.getCenterIds(user);

            //if (auth.isAuthenticated(user) && (centerIds != null)) {
            if (auth.isAuthenticated(user)) {
                if (centerIds == null) {
                    centerIds = new HashSet<String>();
                }
                centerIds.add(auth.getColCenter(user)); // cc may not belong to a net (it not appear in centerIds)

                session.setAttribute("user", username); // Login user.
                session.setAttribute("centerIds", centerIds);
                dispatcher = context.getRequestDispatcher("/CenterFilterServlet?lang=" + lang);
            } else {
                session.removeAttribute("user");
                session.removeAttribute("centerIds");
                dispatcher = context.getRequestDispatcher(
                        "/index.jsp?lang=" + lang + "&errMsg=" + messages.getString("authentication_failed"));
            }
            dispatcher.forward(request, response);
        } catch (Exception ex) {
            dispatcher = context.getRequestDispatcher("/index.jsp?lang=" + lang + "&errMsg="
                    + messages.getString("exception_found") + "<br/><br/>" + ex.getMessage());
            dispatcher.forward(request, response);
        }
    } else {
        final Set<String> ccs = new HashSet<String>();
        ccs.add("PE1.1");
        ccs.add("BR1.1");
        dispatcher = context.getRequestDispatcher("/CenterFilterServlet?lang=" + lang);
        session.setAttribute("user", username); // Login user.
        session.setAttribute("centerIds", ccs);
        dispatcher.forward(request, response);
    }
}

From source file:it.classhidra.core.controller.bsController.java

public static void execRedirect(i_stream currentStream, redirects currentStreamRedirect, String id_action,
        ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)
        throws bsControllerException, ServletException, UnavailableException {
    if (currentStream == null || currentStreamRedirect == null)
        return;/*  ww w.j av a  2  s . c om*/
    currentStream.onPreRedirect(currentStreamRedirect, id_action);
    RequestDispatcher rd = currentStream.redirect(servletContext, currentStreamRedirect, id_action);
    currentStream.onPostRedirect(rd);

    if (rd == null)
        throw new bsControllerException("Controller generic redirect error. Stream: ["
                + currentStream.get_infostream().getName() + "] ", request, iStub.log_ERROR);
    else {
        try {

            String id_rtype = (String) request.getAttribute(CONST_ID_REQUEST_TYPE);
            if (id_rtype == null)
                id_rtype = CONST_REQUEST_TYPE_FORWARD;

            if (id_rtype.equals(CONST_REQUEST_TYPE_FORWARD)) {
                if (!response.isCommitted())
                    rd.forward(request, response);
                else
                    rd.include(request, response);
            } else {
                rd.include(request, response);
            }

        } catch (Exception e) {
            throw new bsControllerException("Controller generic redirect error. Action: ["
                    + currentStream.get_infostream().getName() + "] ->" + e.toString(), request,
                    iStub.log_ERROR);
        }
    }

}

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

/**
 * Process HTTP GET request.//from   w  w  w .  j ava2 s . com
*/
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.apache.struts2.result.ServletDispatcherResult.java

/**
 * Dispatches to the given location. Does its forward via a RequestDispatcher. If the
 * dispatch fails a 404 error will be sent back in the http response.
 *
 * @param finalLocation the location to dispatch to.
 * @param invocation    the execution state of the action
 * @throws Exception if an error occurs. If the dispatch fails the error will go back via the
 *                   HTTP request./* w w w.  j  ava2s  .c  om*/
 */
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    LOG.debug("Forwarding to location: {}", finalLocation);

    PageContext pageContext = ServletActionContext.getPageContext();

    if (pageContext != null) {
        pageContext.include(finalLocation);
    } else {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

        //add parameters passed on the location to #parameters
        // see WW-2120
        if (StringUtils.isNotEmpty(finalLocation) && finalLocation.indexOf("?") > 0) {
            String queryString = finalLocation.substring(finalLocation.indexOf("?") + 1);
            HttpParameters parameters = getParameters(invocation);
            Map<String, Object> queryParams = urlHelper.parseQueryString(queryString, true);
            if (queryParams != null && !queryParams.isEmpty()) {
                parameters = HttpParameters.create(queryParams).withParent(parameters).build();
                invocation.getInvocationContext().setParameters(parameters);
                // put to extraContext, see Dispatcher#createContextMap
                invocation.getInvocationContext().getContextMap().put("parameters", parameters);
            }
        }

        // if the view doesn't exist, let's do a 404
        if (dispatcher == null) {
            LOG.warn("Location {} not found!", finalLocation);
            response.sendError(404, "result '" + finalLocation + "' not found");
            return;
        }

        //if we are inside an action tag, we always need to do an include
        Boolean insideActionTag = (Boolean) ObjectUtils
                .defaultIfNull(request.getAttribute(StrutsStatics.STRUTS_ACTION_TAG_INVOCATION), Boolean.FALSE);

        // If we're included, then include the view
        // Otherwise do forward
        // This allow the page to, for example, set content type
        if (!insideActionTag && !response.isCommitted()
                && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
            request.setAttribute("struts.view_uri", finalLocation);
            request.setAttribute("struts.request_uri", request.getRequestURI());

            dispatcher.forward(request, response);
        } else {
            dispatcher.include(request, response);
        }
    }
}

From source file:com.logiclander.jaasmine.authentication.http.JaasLoginFilter.java

/**
 * This implementation will filter requests for credentials and determine if
 * processing of the FilterChain can proceed.  Filtering occurs as follows:
 * <OL>/*  w  w w. j  a va  2s .  c om*/
 *  <LI>If the request is not an HttpServletRequest and the response is not
 * an HttpServletResponse, continue processing the filter chain (this almost
 * never happens)</LI>
 *  <LI>The HttpSession is checked for an attribute named
 * {@link AuthenticationService#SUBJECT_KEY
 * AuthenticationService.SUBJECT_KEY}</LI>
 *  <LI>If found, then processing the filter chain continues.</LI>
 *  <LI>If not found, then the request is checked for the {@code username}
 * and {@code password} parameters.  If these parameters are present, then
 * the SimpleAuthenticationService's login method is invoked with those
 * credentials.</LI>
 *  <LI>If a Subject is returned, it is saved to the HttpSession with the
 * key from above.</LI>
 * </OL>
 * When the login is successful, the ServletRequest is wrapped in a
 * {@link JaasmineHttpServletRequest}.  If it is unsuccessful, this filter
 * will send the request to a login processor as follows:
 * <OL>
 *  <LI>If {@code loginPath} is set, dispatch the request to that resource.
 * </LI>
 *  <LI>If (@code loginRedirect} is set, redirect the request to that URL.
 * </LI>
 *  <LI>Dispatch to {@code loginServletName} if neither of the above are
 * set./LI>
 * </OL>
 *
 * @param request the ServletRequest
 * @param response the ServletResponse
 * @param chain the FilterChain
 * @throws IOException if an I/O error occurs in the FilterChain
 * @throws ServletException if a processing error occurs in the FilterChain
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("%s: entering doFilter", filterName));
    }

    if (!(request instanceof HttpServletRequest) && !(response instanceof HttpServletResponse)) {

        logger.debug("This is not an HTTP request");
        chain.doFilter(request, response);

    } else {

        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        Exception exception = null;

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Filtering request: %s%s", httpReq.getContextPath(),
                    httpReq.getServletPath()));
        }

        try {

            if (!hasRequestUri(httpReq)) {
                cacheRequestUri(httpReq);
            }

            boolean canExecute = hasCredentials(httpReq);

            // Attempt to login the user and obtain a Subject.

            if (!canExecute) {
                canExecute = login(httpReq);
            }

            if (canExecute) {

                // The Subject was found which means the user has a valid
                // credential (Subject).  Processing can continue.

                // TODO: always wrap request, set to cached requestURI
                HttpServletRequest sendOn = httpReq;

                if (setRemoteUserOnLogin) {
                    sendOn = new JaasmineHttpServletRequest(httpReq, getSubject(httpReq));
                    logger.debug(String.format("Wrapping request in %s", sendOn.toString()));

                }

                chain.doFilter(sendOn, httpResp);

            } else {

                // No Subject found, need to dispatch to someplace to gather
                // the user's credentials and attempt a login on the
                // next request.

                RequestDispatcher loginDispatcher = null;
                if (!loginPath.equals(EMPTY_STRING)) {

                    loginDispatcher = httpReq.getSession().getServletContext().getRequestDispatcher(loginPath);

                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format("Dispatching login " + "request to path %s", loginPath));
                    }

                } else if (!loginRedirect.equals(EMPTY_STRING)) {

                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format("Redirectiong login " + "request to %s", loginRedirect));
                    }
                    httpResp.sendRedirect(loginRedirect);

                    // TODO: cache incoming requestURI

                    return;

                } else if (isUsingBasicAuthentication) {

                    String s = "Basic realm=\"Jaasmine\"";
                    httpResp.setHeader("WWW-Authenticate", s);
                    httpResp.setStatus(401);

                    return;
                } else {

                    loginDispatcher = httpReq.getSession().getServletContext()
                            .getNamedDispatcher(loginServletName);

                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format("Dispatching login " + "request to named dispatcher %s",
                                loginServletName));
                    }
                }

                if (loginDispatcher != null) {

                    loginDispatcher.forward(httpReq, httpResp);
                    return;

                } else {

                    // Try to figure out what went wrong and send back
                    // a HELPFUL exception message.

                    String msg = "";

                    if (!loginPath.equals(EMPTY_STRING)) {

                        // First, is there a loginPath set, but nowhere to
                        // send it to?

                        msg = String.format(
                                "loginPath set to %s, but no " + "resource is available to dispatch to",
                                loginPath);
                    } else {

                        // Is JaasLoginServlet (or the servlet-name
                        // specified by loginServletName) not configured in
                        // the web.xml?

                        msg = String.format("Servlet named %s specified by "
                                + "the loginServletName is not configured in " + "the web.xml",
                                loginServletName);
                    }

                    throw new ServletException(msg);

                }
            }

        } catch (IOException ex) {

            exception = ex;
            throw (ex);

        } catch (ServletException ex) {

            exception = ex;
            throw (ex);

        } finally {

            if (exception != null) {

                if (logger.isErrorEnabled()) {
                    String msg = String.format("Caught exception in filter chain: %s", exception.getMessage());
                    logger.error(msg, exception);
                }
            }

        }
    }
}

From source file:org.apache.click.ClickServlet.java

/**
 * Performs rendering of the specified page.
 *
 * @param page page to render/*w  w w  .j  av a 2 s . co m*/
 * @param context the request context
 * @param actionResult the action result
 * @throws java.lang.Exception if error occurs
 */
protected void performRender(Page page, Context context, ActionResult actionResult) throws Exception {

    // Process page interceptors, and abort rendering if specified
    for (PageInterceptor interceptor : getThreadLocalInterceptors()) {
        if (!interceptor.preResponse(page)) {
            return;
        }
    }

    final HttpServletRequest request = context.getRequest();
    final HttpServletResponse response = context.getResponse();

    if (StringUtils.isNotBlank(page.getRedirect())) {
        String url = page.getRedirect();

        url = response.encodeRedirectURL(url);

        if (logger.isTraceEnabled()) {
            logger.debug("   redirect: " + url);

        } else if (logger.isDebugEnabled()) {
            logger.debug("redirect: " + url);
        }

        response.sendRedirect(url);

    } else if (StringUtils.isNotBlank(page.getForward())) {
        // Indicates the request is forwarded
        request.setAttribute(CLICK_FORWARD, CLICK_FORWARD);

        if (logger.isTraceEnabled()) {
            logger.debug("   forward: " + page.getForward());

        } else if (logger.isDebugEnabled()) {
            logger.debug("forward: " + page.getForward());
        }

        if (page.getForward().endsWith(".jsp")) {
            renderJSP(page);

        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher(page.getForward());

            dispatcher.forward(request, response);
        }

    } else if (actionResult != null) {
        renderActionResult(actionResult, page, context);

    } else if (page.getPath() != null) {
        // Render template unless the request was a page action. This check
        // guards against the scenario where the page action returns null
        // instead of a action result
        if (context.getRequestParameter(Page.PAGE_ACTION) == null) {
            String pagePath = page.getPath();

            // Check if request is a JSP page
            if (pagePath.endsWith(".jsp") || configService.isJspPage(pagePath)) {
                // CLK-141. Set pagePath as the forward value.
                page.setForward(StringUtils.replace(pagePath, ".htm", ".jsp"));

                // Indicates the request is forwarded
                request.setAttribute(CLICK_FORWARD, CLICK_FORWARD);
                renderJSP(page);

            } else {
                renderTemplate(page);
            }
        }

    } else {
        if (logger.isTraceEnabled()) {
            logger.debug("   path not defined for " + page.getClass().getName());

        } else if (logger.isDebugEnabled()) {
            logger.debug("path not defined for " + page.getClass().getName());
        }
    }
}

From source file:de.zib.scalaris.examples.wikipedia.bliki.WikiServlet.java

/**
 * Forwards a request to the <tt>page.jsp</tt> with the given page bean.
 * //  w ww. ja  va 2s  .  com
 * @param request
 *            the request of the current operation
 * @param response
 *            the response of the current operation
 * @param connection
 *            connection to the database
 * @param page
 *            the bean for the page
 * 
 * @throws ServletException
 * @throws IOException
 */
protected void forwardToPageJsp(HttpServletRequest request, HttpServletResponse response, Connection connection,
        WikiPageBeanBase page, String jsp) throws ServletException, IOException {
    final String[] pageSaveTimes = getParam(request, "save_times").split(",");
    for (String pageSaveTime : pageSaveTimes) {
        final int pageSaveTimeInt = parseInt(pageSaveTime, -1);
        if (pageSaveTimeInt >= 0) {
            final String statName = "SAVE:" + page.getTitle();
            page.addStat(statName, pageSaveTimeInt);
        }
    }
    final int pageSaveServerTime = parseInt(getParam(request, "server_time"), -1);
    if (pageSaveServerTime >= 0) {
        page.addStat("server_time (last op)", pageSaveServerTime);
    }
    page.setSaveAttempts(parseInt(getParam(request, "save_attempts"), 0));
    for (int i = 1; i <= Options.getInstance().WIKI_SAVEPAGE_RETRIES; ++i) {
        final String failedKeysPar = getParam(request, "failed_keys" + i);
        if (!failedKeysPar.isEmpty()) {
            final List<String> pageSaveFailedKeys = Arrays.asList(failedKeysPar.split(" # "));
            page.getFailedKeys().put(i, pageSaveFailedKeys);
        }
    }
    final String involvedKeysPar = getParam(request, "involved_keys");
    if (!involvedKeysPar.isEmpty()) {
        page.getInvolvedKeys().add(new InvolvedKey());
        InvolvedKey.addInvolvedKeys(page.getInvolvedKeys(), Arrays.asList(involvedKeysPar.split(" # ")), true);
    }
    final String[] pageRandomTimes = getParam(request, "random_times").split(",");
    for (String pageRandomTime : pageRandomTimes) {
        final int pageRandomTimeInt = parseInt(pageRandomTime, -1);
        if (pageRandomTimeInt >= 0) {
            final String statName = "RANDOM_PAGE (last op)";
            page.addStat(statName, pageRandomTimeInt);
        }
    }
    // forward the request and the bean to the jsp:
    request.setAttribute("pageBean", page);
    request.setAttribute("servlet", this);
    RequestDispatcher dispatcher = request.getRequestDispatcher(jsp);
    dispatcher.forward(request, response);
}