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:org.apache.catalina.core.StandardHostValve.java

/**
 * Handle an HTTP status code or Java exception by forwarding control
 * to the location included in the specified errorPage object.  It is
 * assumed that the caller has already recorded any request attributes
 * that are to be forwarded to this page.  Return <code>true</code> if
 * we successfully utilized the specified error page location, or
 * <code>false</code> if the default error report should be rendered.
 *
 * @param request The request being processed
 * @param response The response being generated
 * @param errorPage The errorPage directive we are obeying
 *//*w w  w.  j  a  va2  s.  co m*/
protected boolean custom(Request request, Response response, ErrorPage errorPage) {

    if (debug >= 1)
        log("Processing " + errorPage);

    // Validate our current environment
    if (!(request instanceof HttpRequest)) {
        if (debug >= 1)
            log(" Not processing an HTTP request --> default handling");
        return (false); // NOTE - Nothing we can do generically
    }
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    if (!(response instanceof HttpResponse)) {
        if (debug >= 1)
            log("Not processing an HTTP response --> default handling");
        return (false); // NOTE - Nothing we can do generically
    }
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();

    ((HttpRequest) request).setPathInfo(errorPage.getLocation());

    try {

        // Reset the response if possible (else IllegalStateException)
        //hres.reset();
        // Reset the response (keeping the real error code and message)
        Integer statusCodeObj = (Integer) hreq.getAttribute(Globals.STATUS_CODE_ATTR);
        int statusCode = statusCodeObj.intValue();
        String message = (String) hreq.getAttribute(Globals.ERROR_MESSAGE_ATTR);
        ((HttpResponse) response).reset(statusCode, message);

        // Forward control to the specified location
        ServletContext servletContext = request.getContext().getServletContext();
        RequestDispatcher rd = servletContext.getRequestDispatcher(errorPage.getLocation());
        rd.forward(hreq, hres);

        // If we forward, the response is suspended again
        response.setSuspended(false);

        // Indicate that we have successfully processed this custom page
        return (true);

    } catch (Throwable t) {

        // Report our failure to process this custom page
        log("Exception Processing " + errorPage, t);
        return (false);

    }

}

From source file:com.alfaariss.oa.authentication.remote.aselect.selector.DefaultSelector.java

private void forwardUser(HttpServletRequest oRequest, HttpServletResponse oResponse, ISession oSession,
        List<ASelectIDP> listOrganizations, String sMethodName, List<Warnings> oWarnings) throws OAException {
    try {//from ww  w .  j  a  va  2 s. c om
        //set request attributes
        oRequest.setAttribute(ISession.ID_NAME, oSession.getId());
        oRequest.setAttribute(ISession.LOCALE_NAME, oSession.getLocale());
        oRequest.setAttribute(REQUEST_PARAM_ORGANIZATIONS, listOrganizations);
        if (oWarnings != null)
            oRequest.setAttribute(DetailedUserException.DETAILS_NAME, oWarnings);
        oRequest.setAttribute(IWebAuthenticationMethod.AUTHN_METHOD_ATTRIBUTE_NAME, sMethodName);
        oRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer());

        RequestDispatcher oDispatcher = oRequest.getRequestDispatcher(_sTemplatePath);
        if (oDispatcher == null) {
            _logger.warn("There is no request dispatcher supported with name: " + _sTemplatePath);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        _logger.debug("Forward user to: " + _sTemplatePath);

        oDispatcher.forward(oRequest, oResponse);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error during forward", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL, e);
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.selector.DefaultSelector.java

private void forwardUser(HttpServletRequest oRequest, HttpServletResponse oResponse, ISession oSession,
        List<SAML2IDP> listIDPs, String sMethodName, List<Warnings> oWarnings) throws OAException {
    try {// w  w  w  .j  av  a  2 s.  c  o  m
        //set request attributes
        oRequest.setAttribute(ISession.ID_NAME, oSession.getId());
        oRequest.setAttribute(ISession.LOCALE_NAME, oSession.getLocale());
        oRequest.setAttribute(REQUEST_PARAM_IDPS, listIDPs);
        if (oWarnings != null)
            oRequest.setAttribute(DetailedUserException.DETAILS_NAME, oWarnings);
        oRequest.setAttribute(IWebAuthenticationMethod.AUTHN_METHOD_ATTRIBUTE_NAME, sMethodName);
        oRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer());

        RequestDispatcher oDispatcher = oRequest.getRequestDispatcher(_sTemplatePath);
        if (oDispatcher == null) {
            _logger.warn("There is no request dispatcher supported with name: " + _sTemplatePath);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        _logger.debug("Forward user to: " + _sTemplatePath);

        oDispatcher.forward(oRequest, oResponse);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error during forward", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:org.apache.jackrabbit.demo.blog.servlet.BlogAddControllerServlet.java

/**
 * This methods handles POST requests and adds the blog entries according to the parameters in the 
 * request. Request must be multi-part encoded.
 *///from   w w w .j  a v a2 s.c o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    List parameters = null;
    String title = null;
    String content = null;
    FileItem image = null;
    FileItem video = null;

    // Check whether the request is multipart encoded
    if (ServletFileUpload.isMultipartContent(request)) {
        DefaultFileItemFactory fileItemFactory = new DefaultFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);

        try {
            // Parse the request and get the paramter set
            parameters = fileUpload.parseRequest(request);
            Iterator paramIter = parameters.iterator();

            // Resolve the parameter set
            while (paramIter.hasNext()) {
                FileItem item = (FileItem) paramIter.next();
                if (item.getFieldName().equalsIgnoreCase("title")) {
                    title = item.getString();
                } else if (item.getFieldName().equalsIgnoreCase("content")) {
                    content = item.getString();
                } else if (item.getFieldName().equalsIgnoreCase("image")) {
                    image = item;
                } else if (item.getFieldName().equalsIgnoreCase("video")) {
                    video = item;
                }
            }

        } catch (FileUploadException e) {
            throw new ServletException("Error occured in processing the multipart request", e);
        }
    } else {
        throw new ServletException("Request is not a multi-part encoded request");
    }

    try {
        //log in to the repository and aquire a session
        Session session = repository.login(new SimpleCredentials("username", "password".toCharArray()));

        String username = (String) request.getSession().getAttribute("username");

        // Only logged in users are allowed to create blog entries
        if (username == null) {
            //set the attributes which are required by user messae page
            request.setAttribute("msgTitle", "Authentication Required");
            request.setAttribute("msgBody", "Only logged in users are allowed to add blog entries.");
            request.setAttribute("urlText", "go back to login page");
            request.setAttribute("url", "/jackrabbit-jcr-demo/blog/index.jsp");

            //forward the request to user massage page
            RequestDispatcher requestDispatcher = this.getServletContext()
                    .getRequestDispatcher("/blog/userMessage.jsp");
            requestDispatcher.forward(request, response);
            return;

        }

        Node blogRootNode = session.getRootNode().getNode("blogRoot");
        Node userNode = blogRootNode.getNode(username);

        // Node to hold the current year
        Node yearNode;
        // Node to hold the current month
        Node monthNode;
        // Node to hold the blog entry to be added
        Node blogEntryNode;
        // Holds the name of the blog entry node
        String nodeName;

        // createdOn property of the blog entry is set to the current time. 
        Calendar calendar = Calendar.getInstance();
        String year = calendar.get(Calendar.YEAR) + "";
        String month = calendar.get(Calendar.MONTH) + "";

        // check whether node exists for current year under usernode and creates a one if not exist
        if (userNode.hasNode(year)) {
            yearNode = userNode.getNode(year);
        } else {
            yearNode = userNode.addNode(year, "nt:folder");
        }

        // check whether node exists for current month under the current year and creates a one if not exist
        if (yearNode.hasNode(month)) {
            monthNode = yearNode.getNode(month);
        } else {
            monthNode = yearNode.addNode(month, "nt:folder");
        }

        if (monthNode.hasNode(title)) {
            nodeName = createUniqueName(title, monthNode);
        } else {
            nodeName = title;
        }

        // creates a blog entry under the current month
        blogEntryNode = monthNode.addNode(nodeName, "blog:blogEntry");
        blogEntryNode.setProperty("blog:title", title);
        blogEntryNode.setProperty("blog:content", content);
        Value date = session.getValueFactory().createValue(Calendar.getInstance());
        blogEntryNode.setProperty("blog:created", date);
        blogEntryNode.setProperty("blog:rate", 0);

        // If the blog entry has an image
        if (image.getSize() > 0) {

            if (image.getContentType().startsWith("image")) {

                Node imageNode = blogEntryNode.addNode("image", "nt:file");
                Node contentNode = imageNode.addNode("jcr:content", "nt:resource");
                contentNode.setProperty("jcr:data", image.getInputStream());
                contentNode.setProperty("jcr:mimeType", image.getContentType());
                contentNode.setProperty("jcr:lastModified", date);
            } else {

                session.refresh(false);

                //set the attributes which are required by user messae page
                request.setAttribute("msgTitle", "Unsupported image format");
                request.setAttribute("msgBody", "The image you attached in not supported");
                request.setAttribute("urlText", "go back to new blog entry page");
                request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp");

                //forward the request to user massage page
                RequestDispatcher requestDispatcher = this.getServletContext()
                        .getRequestDispatcher("/blog/userMessage.jsp");
                requestDispatcher.forward(request, response);
                return;
            }

        }

        // If the blog entry has a video
        if (video.getSize() > 0) {

            if (video.getName().endsWith(".flv") || video.getName().endsWith(".FLV")) {

                Node imageNode = blogEntryNode.addNode("video", "nt:file");
                Node contentNode = imageNode.addNode("jcr:content", "nt:resource");
                contentNode.setProperty("jcr:data", video.getInputStream());
                contentNode.setProperty("jcr:mimeType", video.getContentType());
                contentNode.setProperty("jcr:lastModified", date);

            } else {

                session.refresh(false);

                //set the attributes which are required by user messae page
                request.setAttribute("msgTitle", "Unsupported video format");
                request.setAttribute("msgBody",
                        "Only Flash videos (.flv) are allowed as video attachement. click <a href=\"www.google.com\">here</a> to covert the videos online.");
                request.setAttribute("urlText", "go back to new blog entry page");
                request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp");

                //forward the request to user massage page
                RequestDispatcher requestDispatcher = this.getServletContext()
                        .getRequestDispatcher("/blog/userMessage.jsp");
                requestDispatcher.forward(request, response);
                return;
            }
        }

        // persist the changes done
        session.save();

        //set the attributes which are required by user messae page
        request.setAttribute("msgTitle", "Blog entry added succesfully");
        request.setAttribute("msgBody",
                "Blog entry titled \"" + title + "\" was successfully added to your blog space");
        request.setAttribute("urlText", "go back to my blog page");
        request.setAttribute("url", "/jackrabbit-jcr-demo/blog/view");

        //forward the request to user massage page
        RequestDispatcher requestDispatcher = this.getServletContext()
                .getRequestDispatcher("/blog/userMessage.jsp");
        requestDispatcher.forward(request, response);

    } catch (RepositoryException e) {
        throw new ServletException("Repository error occured", e);
    } finally {
        if (session != null) {
            session.logout();
        }
    }
}

From source file:com.centurylink.mdw.hub.servlet.SoapServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug("SOAP Listener GET Request:\n" + request.getRequestURI()
                + (request.getQueryString() == null ? "" : ("?" + request.getQueryString())));
    }/*  w  ww  .j  av  a2 s  . c o m*/

    if (request.getServletPath().endsWith(RPC_SERVICE_PATH) || RPC_SERVICE_PATH.equals(request.getPathInfo())) {
        Asset rpcWsdlAsset = AssetCache.getAsset(Package.MDW + "/MdwRpcWebService.wsdl", Asset.WSDL);
        response.setContentType("text/xml");
        response.getWriter().print(substituteRuntimeWsdl(rpcWsdlAsset.getStringContent()));
    } else if (request.getPathInfo() == null || request.getPathInfo().equalsIgnoreCase("mdw.wsdl")) {
        // forward to general wsdl
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/mdw.wsdl");
        requestDispatcher.forward(request, response);
    } else if (request.getPathInfo().toUpperCase().endsWith(Asset.WSDL)) {
        String wsdlAsset = request.getPathInfo().substring(1);
        Asset asset = AssetCache.getAsset(wsdlAsset, Asset.WSDL);
        if (asset == null) {
            // try trimming file extension
            wsdlAsset = wsdlAsset.substring(0, wsdlAsset.length() - 5);
            asset = AssetCache.getAsset(wsdlAsset, Asset.WSDL);
        }
        if (asset == null) {
            // try with lowercase extension
            wsdlAsset = wsdlAsset + ".wsdl";
            asset = AssetCache.getAsset(wsdlAsset, Asset.WSDL);
        }
        if (asset == null) {
            String message = "No WSDL resource found: " + request.getPathInfo().substring(1);
            logger.severe(message);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().print(message);
        } else {
            response.setContentType("text/xml");
            response.getWriter().print(substituteRuntimeWsdl(asset.getStringContent()));
        }
    } else {
        ServletException ex = new ServletException(
                "HTTP GET not supported for URL: " + request.getRequestURL());
        logger.severeException(ex.getMessage(), ex);
        throw ex;
    }
}

From source file:com.mockey.ui.ServicePlanSetupServlet.java

/**
 * //from   w w  w .jav  a  2  s  .c  om
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {
        // API BUSINESS LOGIC
        // log.debug("Service Plan setup/delete");
        ServicePlan servicePlan = null;
        Long servicePlanId = null;
        List<Service> allServices = store.getServices();
        // *********************
        // BEST EFFORT HERE.
        // We try to find the service by ID.
        // If not found, we try by NAME.
        // Otherwise, let the rest of the logic do its thing.
        // *********************

        try {
            servicePlanId = new Long(req.getParameter(API_SETPLAN_PARAMETER_PLAN_ID));
            servicePlan = store.getServicePlanById(servicePlanId);
        } catch (Exception e) {
            if (req.getParameter(API_SETPLAN_PARAMETER_PLAN_ID) != null) {
                log.debug("No service plan with ID '" + req.getParameter(API_SETPLAN_PARAMETER_PLAN_ID)
                        + "' found.", e);
            }
        }
        if (servicePlan == null) {
            try {
                String servicePlanName = req.getParameter(API_SET_SAVE_OR_UPDATE_PARAMETER_PLAN_NAME);
                servicePlan = store.getServicePlanByName(servicePlanName.trim());
            } catch (Exception e) {
                if (req.getParameter(API_SET_SAVE_OR_UPDATE_PARAMETER_PLAN_NAME) != null) {
                    log.debug(
                            "No service plan with NAME '"
                                    + req.getParameter(API_SET_SAVE_OR_UPDATE_PARAMETER_PLAN_NAME) + "' found.",
                            e);
                }
            }
        }

        JSONObject jsonResultObject = new JSONObject();

        String action = req.getParameter(API_SETPLAN_PARAMETER_ACTION);
        String transientState = req.getParameter(API_TRANSIENT_STATE);
        try {
            if (transientState != null) {
                servicePlan.setTransientState(new Boolean(transientState));
            }
        } catch (Exception e) {
            log.debug("ServicePlan not set to transient state but a value was given as: " + transientState);

        }
        if (API_SETPLAN_PARAMETER_ACTION_VALUE_DELETE_PLAN.equals(action)) {
            JSONObject jsonObject = new JSONObject();

            try {
                store.deleteServicePlan(servicePlan);
                jsonObject.put("success", "Service plan '" + servicePlan.getName() + "' deleted");
                jsonObject.put("planId", "" + servicePlan.getId());
                jsonObject.put("planName", "" + servicePlan.getName());
            } catch (Exception e) {

                jsonObject.put("fail", "Service plan not deleted. Please check your logs for insight.");

            }
            resp.setContentType("application/json");
            PrintWriter out = resp.getWriter();
            jsonResultObject.put("result", jsonObject);
            out.println(jsonResultObject.toString());
            out.flush();
            out.close();
            return;
        } else if (API_SETPLAN_PARAMETER_ACTION_VALUE_SET_PLAN.equals(action) && servicePlan != null) {
            JSONObject jsonObject = new JSONObject();

            try {
                setPlan(servicePlan);
                String msg = "Service plan " + servicePlan.getName() + " set";
                jsonObject.put("success", msg);
                jsonObject.put("planid", "" + servicePlan.getId());
                jsonObject.put("planName", "" + servicePlan.getName());

                Util.saveSuccessMessage(msg, req); // For redirect
            } catch (Exception e) {
                jsonObject.put("fail", "Service plan not set. Please check your logs for insight.");
            }
            resp.setContentType("application/json");
            PrintWriter out = resp.getWriter();
            jsonResultObject.put("result", jsonObject);
            out.println(jsonResultObject.toString());
            out.flush();
            out.close();
            return;
        } else if (API_SETPLAN_PARAMETER_ACTION_VALUE_SAVE_PLAN.equals(action)) {

            if (servicePlan == null) {
                servicePlan = new ServicePlan();
            }
            // ***************************
            // LET'S PREVENT EMPTY PLAN NAMES
            // ***************************

            String servicePlanName = req.getParameter(API_SET_SAVE_OR_UPDATE_PARAMETER_PLAN_NAME);
            if (servicePlanName == null) {
                // If possible, carry over the name from an existing Plan.
                servicePlanName = servicePlan.getName();
            }
            // If all fails, inject a name.
            if (servicePlanName == null || servicePlanName.trim().length() == 0) {
                servicePlanName = "Plan (auto-generated-name)";
            }
            servicePlan.setName(servicePlanName.trim());

            // ***************************
            // SAVE/UPDATE THE PLAN
            // ***************************
            ServicePlan savedServicePlan = createOrUpdatePlan(servicePlan);

            // ***************************
            // SAVE/UPDATE THE PLAN
            // ***************************
            resp.setContentType("application/json");
            PrintWriter out = resp.getWriter();
            String msg = "Service plan " + servicePlan.getName() + " saved";

            // HACK: For redirect IF JavaScript decides to (if type is not
            // JSON)
            if (!"json".equalsIgnoreCase(req.getParameter(API_SETPLAN_PARAMETER_TYPE))) {
                Util.saveSuccessMessage(msg, req);
            }
            // JSON response
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("success", msg);
            jsonObject.put("planid", "" + savedServicePlan.getId());
            jsonObject.put("planName", "" + savedServicePlan.getName());
            jsonResultObject.put("result", jsonObject);
            out.println(jsonResultObject.toString());
            out.flush();
            out.close();
            return;
        }

        req.setAttribute("services", allServices);
        req.setAttribute("plans", store.getServicePlans());
        RequestDispatcher dispatch = req.getRequestDispatcher("/home.jsp");
        dispatch.forward(req, resp);
    } catch (JSONException jsonException) {
        throw new ServletException(jsonException);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.NamespacePrefixRetryController.java

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.USE_MISCELLANEOUS_ADMIN_PAGES.ACTION)) {
        return;//from  ww w.  jav a 2  s  .com
    }

    //create an EditProcessObject for this and put it in the session
    EditProcessObject epo = super.createEpo(request);

    if (request.getParameter("prefix") != null) {
        epo.setAction("update");
        request.setAttribute("_action", "update");
    } else {
        epo.setAction("insert");
        request.setAttribute("_action", "insert");
    }

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("editAction", "namespacePrefixOp");
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    request.setAttribute("formJsp", "/templates/edit/specific/namespacePrefix_retry.jsp");
    request.setAttribute("title", "Edit Namespace Prefix Mapping");
    setRequestAttributes(request, epo);

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error(this.getClass().getName() + " could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

From source file:org.deegree.test.gui.StressTestController.java

private void doStep2(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Map<String, String> paramsSet = new HashMap<String, String>();
    String[] datasets = request.getParameterValues("datasets");
    if (datasets != null) {
        String datasetsStr = "";
        for (int i = 0; i < datasets.length; i++)
            datasetsStr = datasetsStr + "," + datasets[i];
        paramsSet.put("datasets", datasetsStr);
    }//from www .  ja va  2 s  .  c  om

    String elevModel = request.getParameter("elevModel");
    if (elevModel != null && elevModel.length() > 0)
        paramsSet.put("elevModel", elevModel);

    String pitch = request.getParameter("pitch");
    if (pitch != null && pitch.length() > 0)
        paramsSet.put("pitch", pitch);

    String yaw = request.getParameter("yaw");
    if (yaw != null && yaw.length() > 0)
        paramsSet.put("yaw", yaw);

    String roll = request.getParameter("roll");
    if (roll != null && roll.length() > 0)
        paramsSet.put("roll", roll);

    String distance = request.getParameter("distance");
    if (distance != null && distance.length() > 0)
        paramsSet.put("distance", distance);

    String aov = request.getParameter("aov");
    if (aov != null && aov.length() > 0)
        paramsSet.put("aov", aov);

    String clipping = request.getParameter("clipping");
    if (clipping != null && clipping.length() > 0)
        paramsSet.put("clipping", clipping);

    String crs = request.getParameter("crs");
    if (crs != null && crs.length() > 0)
        paramsSet.put("crs", crs);

    String width = request.getParameter("width");
    if (width != null && width.length() > 0)
        paramsSet.put("width", width);

    String height = request.getParameter("height");
    if (height != null && height.length() > 0)
        paramsSet.put("height", height);

    String scale = request.getParameter("scale");
    if (scale != null && scale.length() > 0)
        paramsSet.put("scale", scale);

    request.getSession().setAttribute("paramsSet", paramsSet);

    RequestDispatcher dispatcher = request.getRequestDispatcher("/wpvs_threads.jsp");
    dispatcher.forward(request, response);
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.JenaXMLFileUpload.java

/**
 * Each file will be converted to RDF/XML and loaded to the target model.
 * If any of the files fail, no data will be loaded.
 * // w  w  w  .  ja  va  2s . com
 * parameters:
 * targetModel - model to save to
 * defaultNamespace - namespace to use for elements in xml that lack a namespace
 * 
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
    VitroRequest vreq = new VitroRequest(request);
    if (vreq.hasFileSizeException()) {
        throw new ServletException("Size limit exceeded: " + vreq.getFileSizeException().getLocalizedMessage());
    }
    if (vreq.isMultipart()) {
        log.debug("multipart content detected");
    } else {
        // TODO: forward to error message
        throw new ServletException("Must POST a multipart encoded request");
    }

    if (!isAuthorizedToDisplayPage(request, resp, SimplePermission.USE_ADVANCED_DATA_TOOLS_PAGES.ACTION)) {
        return;
    }

    ModelMaker modelMaker = getModelMaker(vreq);
    String targetModel = request.getParameter("targetModel");
    if (targetModel == null) {
        throw new ServletException("targetModel not specified.");
    }

    Model m = modelMaker.getModel(targetModel);
    if (m == null)
        throw new ServletException("targetModel '" + targetModel + "' was not found.");
    request.setAttribute("targetModel", targetModel);

    List<File> filesToLoad = saveFiles(vreq.getFiles());
    List<File> rdfxmlToLoad = convertFiles(filesToLoad);
    List<Model> modelsToLoad = loadRdfXml(rdfxmlToLoad);

    try {
        m.enterCriticalSection(Lock.WRITE);
        for (Model model : modelsToLoad) {
            m.add(model);
        }
    } finally {
        m.leaveCriticalSection();
    }

    long count = countOfStatements(modelsToLoad);
    request.setAttribute("statementCount", count);

    request.setAttribute("title", "Uploaded files and converted to RDF");
    request.setAttribute("bodyJsp", "/jenaIngest/xmlFileUploadSuccess.jsp");

    request.setAttribute("fileItems", vreq.getFiles());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
            + vreq.getAppBean().getThemeDir() + "css/edit.css\"/>");

    try {
        rd.forward(request, resp);
    } catch (Exception e) {
        System.out.println(this.getClass().getName() + " could not forward to view.");
        System.out.println(e.getMessage());
        System.out.println(e.getStackTrace());
    }
}

From source file:com.concursive.connect.web.controller.servlets.URLControllerServlet.java

private void mapToMVCAction(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // Translate the URI into its parts
    // URLControllerServlet-> contextPath: /context
    // URLControllerServlet-> path: /show/something
    String uri = request.getRequestURI();
    String contextPath = request.getContextPath();

    LOG.debug("Using uri: " + uri);
    URLControllerBean bean = new URLControllerBean(uri, contextPath);
    String queryString = request.getQueryString();
    String path = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString);
    request.setAttribute("requestedURL", path);
    LOG.debug("Requested path: " + path);

    // Map to the MVC Action
    String mappedPath = null;//w w  w  .  j  a v  a 2  s. com
    try {
        if (bean.getAction().equals(URLControllerBean.EDITOR)) {
            mappedPath = "ProjectPortal.do?command=Builder";
        } else if (bean.getAction().equals(URLControllerBean.REGISTER)) {
            mappedPath = "page/register";
        } else if (bean.getAction().equals(URLControllerBean.LOGIN)) {
            if (bean.getDomainObject() == null) {
                mappedPath = "Login.do?command=Default";
            } else {
                mappedPath = "Login.do?command=Login";
            }
        } else if (bean.getAction().equals(URLControllerBean.LOGOUT)) {
            mappedPath = "Login.do?command=Logout";
        } else if (bean.getAction().equals(URLControllerBean.RSS)) {
            mappedPath = "ProjectManagement.do?command=RSS";
        } else if (bean.getAction().equals(URLControllerBean.RSVP)) {
            mappedPath = "";
        } else if (bean.getAction().equals(URLControllerBean.INVITATIONS)) {
            mappedPath = "ProjectManagement.do?command=RSVP";
        } else if (bean.getAction().equals(URLControllerBean.SETUP)) {
            mappedPath = "Setup.do";
        } else if (bean.getAction().equals(URLControllerBean.ADMIN)) {
            mappedPath = LinkGenerator.getAdminPortalLink(bean);
        } else if (bean.getAction().equals(URLControllerBean.CATALOG)) {
            mappedPath = "Order.do";
        } else if (bean.getAction().equals(URLControllerBean.CONTACT_US)) {
            mappedPath = "ContactUs.do";
        } else if (bean.getAction().equals(URLControllerBean.PAGE)) {
            mappedPath = "Portal.do?command=ShowPortalPage&name="
                    + URLEncoder.encode(bean.getDomainObject(), "UTF-8")
                    + (StringUtils.hasText(bean.getObjectValue())
                            ? "&view=" + URLEncoder.encode(bean.getObjectValue(), "UTF-8")
                            : "")
                    + (StringUtils.hasText(bean.getParams()) ? "&params=" + bean.getParams() : "");
        } else if (bean.getAction().equals(URLControllerBean.IMAGE)) {
            mappedPath = "Portal.do?command=Img&url=" + bean.getDomainObject();
        } else if (bean.getAction().equals(URLControllerBean.SETTINGS)) {
            mappedPath = "Profile.do";
        } else if (bean.getAction().equals(URLControllerBean.PROFILE)) {
            mappedPath = "ProjectManagement.do?command=Dashboard";
        } else if (bean.getAction().equals(URLControllerBean.BROWSE)) {
            mappedPath = "ProjectManagement.do?command=ProjectList";
        } else if (bean.getAction().equals(URLControllerBean.SEARCH)) {
            mappedPath = "Search.do?command=Default";
        } else if (bean.getAction().equals(URLControllerBean.SUPPORT)) {
            mappedPath = "ContactUs.do";
        } else if (bean.getAction().equals(URLControllerBean.REPORTS)) {
            mappedPath = "Reports.do?command=List";
        } else if (bean.getAction().equals(URLControllerBean.BADGE)) {
            mappedPath = "Badges.do?command=Details&id=" + bean.getObjectValue();
        } else if (bean.getAction().equals(URLControllerBean.MANAGEMENT_CRM)) {
            mappedPath = LinkGenerator.getCRMLink();
        } else if (bean.getAction().equals(URLControllerBean.SHOW)) {
            if (bean.getDomainObject() == null) {
                mappedPath = LinkGenerator.getProjectPortalLink(bean);
            } else if ("image".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getProfileImageLink(bean.getProjectId(), bean.getObjectValue());
            } else if ("dashboard".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getDashboardLink(bean.getProjectId(), bean.getObjectValue());
            } else if ("blog-image".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getBlogImageLink(bean.getProjectId(), bean.getObjectValue());
            } else if ("wiki-image".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getWikiImageLink(bean.getProjectId(), bean.getObjectValue());
            } else if ("lists".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getListsLink(bean.getProjectId());
            } else if ("list".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getListDetailsLink(bean.getProjectId(), bean.getObjectValueAsInt());
            } else if ("plans".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getPlanLink(bean.getProjectId());
            } else if ("plan".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getPlanLink(bean.getProjectId(), bean.getObjectValueAsInt());
            } else if ("issues".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getTicketsLink(bean.getProjectId());
            } else if ("issue".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getTicketDetailsLink(bean.getProjectId(),
                        bean.getObjectValueAsInt());
            } else if ("details".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getDetailsLink(bean.getProjectId());
            } else if ("setup".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getSetupLink(bean.getProjectId());
            } else if ("customize".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getCustomizeLink(bean.getProjectId());
            } else if ("permissions".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getPermissionsLink(bean.getProjectId());
            } else if ("customize-style".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getCustomizeStyleLink(bean.getProjectId());
            } else if ("style-image".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getStyleImageLink(bean.getProjectId(), bean.getObjectValue());
            } else if ("app".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getPageLink(bean.getProjectId(), bean.getObjectValue());
            } else if ("tools".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getToolsLink(bean.getProjectId(), bean.getObjectValue());
            } else if ("crm-account".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getCRMAccountLink(bean.getProjectId(), bean.getObjectValue());
            } else {
                mappedPath = LinkGenerator.getProjectPortalLink(bean);
            }
        } else if (bean.getAction().equals(URLControllerBean.CREATE)) {
            if (bean.getDomainObject() == null) {
                mappedPath = "ProjectManagement.do?command=ModifyProject&pid=" + bean.getProjectId()
                        + "&return=ProjectCenter";
            } else {
                mappedPath = LinkGenerator.getProjectPortalLink(bean);
            }
        } else if (bean.getAction().equals(URLControllerBean.MODIFY)) {
            if (bean.getDomainObject() == null) {
                mappedPath = "ProjectManagement.do?command=ModifyProject&pid=" + bean.getProjectId()
                        + "&return=ProjectCenter";
            } else {
                mappedPath = LinkGenerator.getProjectPortalLink(bean);
            }
        } else if (bean.getAction().equals(URLControllerBean.REMOVE)) {
            if ("image".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getRemoveProfileImageLink(bean.getProjectId(),
                        bean.getObjectValue());
            }
        } else if (bean.getAction().equals(URLControllerBean.SET)) {
            if ("image".equals(bean.getDomainObject())) {
                mappedPath = LinkGenerator.getSetProfileImageLink(bean.getProjectId(), bean.getObjectValue());
            } else {
                mappedPath = LinkGenerator.getProjectPortalLink(bean);
            }
        } else if (bean.getAction().equals(URLControllerBean.ACCEPT)) {
            mappedPath = "ProjectManagement.do?command=AcceptProject&pid=" + bean.getProjectId();
        } else if (bean.getAction().equals(URLControllerBean.REJECT)) {
            mappedPath = "ProjectManagement.do?command=RejectProject&pid=" + bean.getProjectId();
        } else if (bean.getAction().equals(URLControllerBean.DOWNLOAD)
                || bean.getAction().equals(URLControllerBean.STREAM)) {
            if ("file".equals(bean.getDomainObject())) {
                mappedPath = "ProjectManagementFiles.do?command=Download" + "&pid=" + bean.getProjectId()
                        + "&fid=" + bean.getObjectValue()
                        + (bean.getParams() != null ? "&ver=" + bean.getParams() : "")
                        + (bean.getAction().equals(URLControllerBean.STREAM) ? "&view=true" : "");
            } else {
                mappedPath = LinkGenerator.getProjectActionLink(bean);
            }
        } else {
            if (bean.getProjectId() > -1) {
                mappedPath = LinkGenerator.getProjectPortalLink(bean);
            }
        }
    } catch (Exception ex) {
        String msg = "URLControllerServletError1";
        LOG.error(msg, ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    }

    try {
        String forwardPath = null;
        if (mappedPath == null) {
            forwardPath = "/redirect404.jsp";
            LOG.error("A mapped path was not found for action: " + path);
        } else {
            forwardPath = "/" + mappedPath;
            LOG.debug("Forwarding request to: " + forwardPath);
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(forwardPath);
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        String msg = "URLControllerServletError2";
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    }

}