Example usage for javax.servlet.http HttpServletRequest getRequestDispatcher

List of usage examples for javax.servlet.http HttpServletRequest getRequestDispatcher

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRequestDispatcher.

Prototype

public RequestDispatcher getRequestDispatcher(String path);

Source Link

Document

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

Usage

From source file:controllers.ServerController.java

public void login(HttpServletRequest request, HttpServletResponse response)
        throws IOException, InterruptedException, ServletException, LDAPException {
    try {/*from w w  w .ja v  a 2 s.c om*/
        LDAPConnection c = new LDAPConnection("192.168.1.10", 389,
                "cn=" + request.getParameter("username") + ",ou=printing,dc=iliberis,dc=com",
                (String) request.getParameter("password"));

        if (c.isConnected()) {
            HttpSession session = LDAPConn.getInstance().loadGroups(request);
            ServerController.getInstance().listPrinter(request, response);
            RequestDispatcher rd;
            List<String> groups = (List<String>) session.getAttribute("groups");
            if (groups.contains("10000")) {
                rd = request.getRequestDispatcher("admin.jsp");
                request.setAttribute("groupsList", LDAPConn.getInstance().getPrintingGroups());
            } else
                rd = request.getRequestDispatcher("success.jsp");
            rd.forward(request, response);
        }

    } catch (LDAPException ex) {
        // LDAPException(resultCode=49): Credenciales invalidas
        // LDAPException(resultCode=89): DN o pass vacios
        System.out.println("No connection: " + ex.getExceptionMessage());
        Logger.getLogger(MainServlet.class.getName()).log(Level.SEVERE, null, ex);
        RequestDispatcher rd = request.getRequestDispatcher("index.html");
        rd.forward(request, response);
    } catch (Exception ex) {
        Logger.getLogger(ServerController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.re.ResponseEndpoint.java

private void forwardToSSOLogout(HttpServletRequest request, HttpServletResponse response, ISession session)
        throws OAException {
    try {/*from   w ww .j  av a 2s  .c  o m*/
        request.setAttribute(ISession.ID_NAME, session);

        StringBuffer sbForward = new StringBuffer(_sWebSSOPath);
        if (!_sWebSSOPath.endsWith("/"))
            sbForward.append("/");
        sbForward.append(SSO_LOGOUT_URI);

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

        oDispatcher.forward(request, response);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error during forward to sso logout", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:eionet.util.Util.java

public static void forward2errorpage(HttpServletRequest request, HttpServletResponse response, Throwable t,
        String backURL) throws ServletException, IOException {

    String msg = t.getMessage();//from  w  w w. java2  s.c o  m

    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    t.printStackTrace(new PrintStream(bytesOut));

    String trace = bytesOut.toString(response.getCharacterEncoding());

    request.setAttribute("DD_ERR_MSG", msg);
    request.setAttribute("DD_ERR_TRC", trace);
    request.setAttribute("DD_ERR_BACK_LINK", backURL);

    request.getRequestDispatcher("error.jsp").forward(request, response);
}

From source file:com.quartercode.femtoweb.api.resolutions.View.java

@Override
public Action execute(HttpServletRequest request, HttpServletResponse response, Context context)
        throws IOException, ServletException {

    // Generate the actual target path (depending on the invoked constructor, use the set path or combine the "directory" URI of the set action's URI with the set name)
    String actualPath;/*from   w w w  . ja v a  2  s . c  om*/
    if (path != null) {
        actualPath = path;
    } else {
        String dirUri = StringUtils.substringBeforeLast(context.getUri(dir), "/");
        actualPath = dirUri + "/" + name;
    }

    // Add the path prefix to the directory containing dynamic content
    actualPath = context.getDynamicAssetPath() + "/" + StringUtils.stripStart(actualPath, "/");

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Forwarding request to '{}' to '{}'", RequestUtils.getRequestUri(request), actualPath);
    }

    // Actually forward the request
    request.getRequestDispatcher(actualPath).forward(request, response);

    return null;
}

From source file:jetbrains.buildServer.symbols.DownloadSourcesController.java

@Nullable
@Override/*from  ww  w. j  a v  a  2  s  .c o  m*/
protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response)
        throws Exception {
    final String requestURI = request.getRequestURI();
    if (!requestURI.matches(VALID_URL_PATTERN)) {
        WebUtil.notFound(request, response, "Url is invalid", null);
        return null;
    }

    final SUser user = myAuthHelper.getAuthenticatedUser(request, response, new Predicate<SUser>() {
        public boolean apply(SUser user) {
            return true;
        }
    });
    if (user == null)
        return null;

    String restMethodUrl = requestURI.replace("/builds/id-", "/builds/id:").replace("/app/sources/",
            "/app/rest/");
    final String contextPath = request.getContextPath();
    if (restMethodUrl.startsWith(contextPath)) {
        restMethodUrl = restMethodUrl.substring(contextPath.length());
    }
    RequestDispatcher dispatcher = request.getRequestDispatcher(restMethodUrl);
    if (dispatcher != null) {
        LOG.debug(String.format("Forwarding request. From %s To %s", requestURI, restMethodUrl));
        dispatcher.forward(request, response);
    }
    return null;
}

From source file:com.edgenius.wiki.webapp.servlet.UploadServlet.java

@SuppressWarnings("unchecked")
protected void doService(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if ("GET".equalsIgnoreCase(request.getMethod())) {
        //just render blank page for upload
        String pageUuid = request.getParameter("puuid");
        String spaceUname = request.getParameter("uname");
        String draft = request.getParameter("draft");

        request.setAttribute("pageUuid", pageUuid);
        request.setAttribute("spaceUname", spaceUname);
        request.setAttribute("draft", NumberUtils.toInt(draft, PageType.NONE_DRAFT.value()));

        request.getRequestDispatcher("/WEB-INF/pages/upload.jsp").forward(request, response);

        return;/* w ww  .  j av  a 2s.c o  m*/
    }

    //post - upload

    //      if(WikiUtil.getUser().isAnonymous()){
    //      //anonymous can not allow to upload any files

    PageService pageService = getPageService();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

    List<FileNode> files = new ArrayList<FileNode>();
    String pageUuid = null, spaceUname = null;
    try {
        int status = PageType.NONE_DRAFT.value();
        // index->filename
        Map<String, FileItem> fileMap = new HashMap<String, FileItem>();
        Map<String, String> descMap = new HashMap<String, String>();
        // index->index
        Map<String, String> indexMap = new HashMap<String, String>();

        //offline submission, filename put into hidden variable rather than <input type="file> tag
        Map<String, String> filenameMap = new HashMap<String, String>();
        //TODO: offline submission, version also upload together with file, this give a change to do failure tolerance check:
        //if version is same with online save, then it is OK, if greater, means it maybe duplicated upload, if less, unpexected case
        Map<String, String> versionMap = new HashMap<String, String>();

        Map<String, Boolean> bulkMap = new HashMap<String, Boolean>();

        Map<String, Boolean> sharedMap = new HashMap<String, Boolean>();
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String name = item.getFieldName();
            if (StringUtils.equals(name, "spaceUname")) {
                spaceUname = item.getString(Constants.UTF8);
            } else if (StringUtils.equals(name, "pageUuid")) {
                pageUuid = item.getString();
            } else if (name.startsWith("draft")) {
                // check this upload is from "click save button" or "auto upload in draft status"
                status = Integer.parseInt(item.getString());
            } else if (name.startsWith("file")) {
                fileMap.put(name.substring(4), item);
                indexMap.put(name.substring(4), name.substring(4));
            } else if (name.startsWith("desc")) {
                descMap.put(name.substring(4), item.getString(Constants.UTF8));
            } else if (name.startsWith("shar")) {
                sharedMap.put(name.substring(4), Boolean.parseBoolean(item.getString()));
            } else if (name.startsWith("name")) {
                filenameMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("vers")) {
                versionMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("bulk")) {
                bulkMap.put(name.substring(4), BooleanUtils.toBoolean(item.getString()));
            }
        }
        if (StringUtils.isBlank(pageUuid)) {
            log.error("Attachment can not be load because of page does not save successfully.");
            throw new PageException("Attachment can not be load because of page does not save successfully.");
        }

        List<FileNode> bulkFiles = new ArrayList<FileNode>();
        String username = request.getRemoteUser();
        // put file/desc pair into final Map
        for (String id : fileMap.keySet()) {
            FileItem item = fileMap.get(id);
            if (item == null || item.getInputStream() == null || item.getSize() <= 0) {
                log.warn("Empty upload item:" + (item != null ? item.getName() : ""));
                continue;
            }
            FileNode node = new FileNode();
            node.setComment(descMap.get(id));
            node.setShared(sharedMap.get(id) == null ? false : sharedMap.get(id));
            node.setFile(item.getInputStream());
            String filename = item.getName();
            if (StringUtils.isBlank(filename)) {
                //this could be offline submission, get name from map
                filename = filenameMap.get(id);
            }
            node.setFilename(FileUtil.getFileName(filename));
            node.setContentType(item.getContentType());
            node.setIndex(indexMap.get(id));
            node.setType(RepositoryService.TYPE_ATTACHMENT);
            node.setIdentifier(pageUuid);
            node.setCreateor(username);
            node.setStatus(status);
            node.setSize(item.getSize());
            node.setBulkZip(bulkMap.get(id) == null ? false : bulkMap.get(id));

            files.add(node);

            if (node.isBulkZip())
                bulkFiles.add(node);
        }
        if (spaceUname != null && pageUuid != null && files.size() > 0) {
            files = pageService.uploadAttachments(spaceUname, pageUuid, files, false);

            //only save non-draft uploaded attachment
            if (status == 0) {
                try {
                    getActivityLog().logAttachmentUploaded(spaceUname,
                            pageService.getCurrentPageByUuid(pageUuid).getTitle(), WikiUtil.getUser(), files);
                } catch (Exception e) {
                    log.warn("Activity log save error for attachment upload", e);
                }
            }
            //as bulk files won't in return list in PageService.uploadAttachments(), here need 
            //append to all return list, but only for client side "uploading panel" clean purpose
            files.addAll(bulkFiles);
            //TODO: if version come in together, then do check
            //            if(versionMap.size() > 0){
            //               for (FileNode node: files) {
            //                  
            //               }
            //            }
        }

    } catch (RepositoryQuotaException e) {
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.quota.exhaust"));
        files = Arrays.asList(att);
    } catch (AuthenticationException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_LOGIN;
        log.info("Send Authentication redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.authentication.required"));
        files = Arrays.asList(att);

    } catch (AccessDeniedException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_ACCESS_DENIED;
        log.info("Send AccessDenied redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.access.denied"));
        files = Arrays.asList(att);

    } catch (Exception e) {
        // FileUploadException,RepositoryException
        log.error("File upload failed ", e);
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.upload"));
        files = Arrays.asList(att);
    }

    try {
        String json = FileNode.toAttachmentsJson(files, spaceUname, WikiUtil.getUser(), getMessageService(),
                getUserReadingService());

        //TODO: does not compress request in Gzip, refer to 
        //http://www.google.com/codesearch?hl=en&q=+RemoteServiceServlet+show:PAbNFg2Qpdo:akEoB_bGF1c:4aNSrXYgYQ4&sa=N&cd=1&ct=rc&cs_p=https://ssl.shinobun.org/svn/repos/trunk&cs_f=proprietary/gwt/gwt-user/src/main/java/com/google/gwt/user/server/rpc/RemoteServiceServlet.java#first
        byte[] reply = json.getBytes(Constants.UTF8);
        response.setContentLength(reply.length);
        response.setContentType("text/plain; charset=utf-8");
        response.getOutputStream().write(reply);
    } catch (IOException e) {
        log.error(e.toString(), e);
    }
}

From source file:io.github.benas.todolist.web.servlet.user.RegisterServlet.java

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

    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String confirmationPassword = request.getParameter("confirmationPassword");

    RegistrationForm registrationForm = new RegistrationForm();
    registrationForm.setName(name);/*from ww  w . j  av a 2  s . c o m*/
    registrationForm.setEmail(email);
    registrationForm.setPassword(password);
    registrationForm.setConfirmationPassword(confirmationPassword);

    String nextPage = REGISTER_PAGE;

    validateRegistrationForm(request, registrationForm);

    checkPasswordsMatch(request, password, confirmationPassword);

    if (isInvalid(request)) {
        request.getRequestDispatcher(nextPage).forward(request, response);
        return;
    }

    if (isAlreadyUsed(email)) {
        request.setAttribute("error",
                MessageFormat.format(resourceBundle.getString("register.error.global.account"), email));
        request.getRequestDispatcher(nextPage).forward(request, response);
        return;
    }

    User user = new User(name, email, password);
    user = userService.create(user);
    HttpSession session = request.getSession(true);
    session.setAttribute(TodoListUtils.SESSION_USER, user);
    request.getRequestDispatcher("/todos").forward(request, response);

}

From source file:net.hillsdon.reviki.web.dispatching.impl.DispatcherImpl.java

private void handleException(final HttpServletRequest request, final HttpServletResponse response,
        final Exception ex, final boolean logTrace, final String customMessage, final int statusCode)
        throws ServletException, IOException {
    response.setStatus(statusCode);/*from w  ww. jav a2s  .c o m*/
    String user = (String) request.getAttribute(RequestAttributes.USERNAME);
    if (user == null) {
        user = "[none]";
    }
    String queryString = request.getQueryString();
    String uri = request.getRequestURI() + (queryString == null ? "" : "?" + queryString);
    String message = format("%s for user '%s' accessing '%s'.", ex.getClass().getSimpleName(), user, uri);
    if (logTrace) {
        LOG.error(message, ex);
    } else {
        LOG.warn(message, null);
    }
    request.setAttribute("exception", ex);
    request.setAttribute("customMessage", customMessage);
    request.getRequestDispatcher("/WEB-INF/templates/Error.jsp").forward(request, response);
}

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

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) {
        return;//from w  w  w  .  j  av a2s  .c o  m
    }

    String entURI = request.getParameter("uri");
    VitroRequest vreq = (new VitroRequest(request));
    ApplicationBean application = vreq.getAppBean();

    //Individual ent = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(entURI);
    Individual ent = vreq.getUnfilteredAssertionsWebappDaoFactory().getIndividualDao()
            .getIndividualByURI(entURI);
    if (ent == null) {
        try {
            RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
            request.setAttribute("bodyJsp", "/jenaIngest/notfound.jsp");
            request.setAttribute("title", "Individual Not Found");
            request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
                    + application.getThemeDir() + "css/edit.css\"/>");
            rd.forward(request, response);
        } catch (Exception e) {
            log.error("EntityEditController could not forward to view.");
            log.error(e.getMessage());
            log.error(e.getStackTrace());
        }
    }

    Individual inferredEnt = vreq.getUnfilteredWebappDaoFactory().getIndividualDao().getIndividualByURI(entURI);
    if (inferredEnt == null) {
        inferredEnt = new IndividualImpl(entURI);
    }

    request.setAttribute("entity", ent);

    ArrayList<String> results = new ArrayList<String>();
    int colCount = 4;
    results.add("Name");
    results.add("class");
    results.add("display level");
    results.add("edit level");
    results.add("last updated");
    colCount++;
    results.add("URI");
    colCount++;
    results.add("publish level");
    colCount++;

    String rName = null;
    if (ent.getName() != null && ent.getName().length() > 0) {
        rName = ent.getName();
    } else if (ent.getLocalName() != null && ent.getLocalName().length() > 0) {
        rName = ent.getLocalName();
    } else if (ent.isAnonymous()) {
        rName = "[anonymous resource]";
    } else {
        rName = "[resource]";
    }
    results.add(rName);

    String classStr = "";
    List<VClass> classList = inferredEnt.getVClasses(false);
    sortForPickList(classList, vreq);
    if (classList != null) {
        for (Iterator<VClass> classIt = classList.iterator(); classIt.hasNext();) {
            VClass vc = classIt.next();
            String rClassName = "";
            try {
                rClassName = "<a href=\"vclassEdit?uri=" + URLEncoder.encode(vc.getURI(), "UTF-8") + "\">"
                        + vc.getPickListName() + "</a>";
            } catch (Exception e) {
                rClassName = vc.getLocalNameWithPrefix();
            }
            classStr += rClassName;
            if (classIt.hasNext()) {
                classStr += ", ";
            }
        }
    }
    results.add(classStr);

    results.add(ent.getHiddenFromDisplayBelowRoleLevel() == null ? "unspecified"
            : ent.getHiddenFromDisplayBelowRoleLevel().getDisplayLabel());
    results.add(ent.getProhibitedFromUpdateBelowRoleLevel() == null ? "unspecified"
            : ent.getProhibitedFromUpdateBelowRoleLevel().getUpdateLabel());

    String rModTime = (ent.getModTime() == null) ? "" : publicDateFormat.format(ent.getModTime());
    results.add(rModTime);
    results.add((ent.getURI() == null) ? "[anonymous individual]" : ent.getURI());
    results.add(ent.getHiddenFromPublishBelowRoleLevel() == null ? "unspecified"
            : ent.getHiddenFromPublishBelowRoleLevel().getDisplayLabel());
    request.setAttribute("results", results);
    request.setAttribute("columncount", colCount);
    request.setAttribute("suppressquery", "true");

    EditProcessObject epo = super.createEpo(request, FORCE_NEW);
    request.setAttribute("epo", epo);

    FormObject foo = new FormObject();
    HashMap<String, List<Option>> OptionMap = new HashMap<String, List<Option>>();

    List<VClass> types = ent.getVClasses(false);
    sortForPickList(types, vreq);
    request.setAttribute("types", types); // we're displaying all assertions, including indirect types

    try {
        List<Option> externalIdOptionList = new LinkedList<Option>();
        if (ent.getExternalIds() != null) {
            Iterator<DataPropertyStatement> externalIdIt = ent.getExternalIds().iterator();
            while (externalIdIt.hasNext()) {
                DataPropertyStatement eid = externalIdIt.next();
                String multiplexedString = new String(
                        "DatapropURI:" + new String(Base64.encodeBase64(eid.getDatapropURI().getBytes())) + ";"
                                + "Data:" + new String(Base64.encodeBase64(eid.getData().getBytes())));
                externalIdOptionList.add(new Option(multiplexedString, eid.getData()));
            }
        }
        OptionMap.put("externalIds", externalIdOptionList);
    } catch (Exception e) {
        log.error(e, e);
    }

    try {
        OptionMap.put("VClassURI",
                FormUtils.makeOptionListFromBeans(
                        vreq.getUnfilteredWebappDaoFactory().getVClassDao().getAllVclasses(), "URI",
                        "PickListName", ent.getVClassURI(), null, false));
    } catch (Exception e) {
        log.error(e, e);
    }

    PropertyInstanceDao piDao = vreq.getUnfilteredWebappDaoFactory().getPropertyInstanceDao();
    // existing property statements
    try {
        List epiOptionList = new LinkedList();
        Collection<PropertyInstance> epiColl = piDao.getExistingProperties(ent.getURI(), null);
        Iterator<PropertyInstance> epiIt = epiColl.iterator();
        while (epiIt.hasNext()) {
            PropertyInstance pi = epiIt.next();
            String multiplexedString = new String("PropertyURI:"
                    + new String(Base64.encodeBase64(pi.getPropertyURI().getBytes())) + ";" + "ObjectEntURI:"
                    + new String(Base64.encodeBase64(pi.getObjectEntURI().getBytes())));
            epiOptionList.add(new Option(multiplexedString, pi.getDomainPublic() + " " + pi.getObjectName()));
        }
        OptionMap.put("ExistingPropertyInstances", epiOptionList);
    } catch (Exception e) {
        log.error(e, e);
    }
    // possible property statements
    try {
        Collection piColl = piDao.getAllPossiblePropInstForIndividual(ent.getURI());
        List piList = new ArrayList();
        piList.addAll(piColl);
        OptionMap.put("PropertyURI", FormUtils.makeOptionListFromBeans(piList, "PropertyURI", "DomainPublic",
                (String) null, (String) null, false));
    } catch (Exception e) {
        log.error(e, e);
    }

    foo.setOptionLists(OptionMap);

    epo.setFormObject(foo);

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("entityWebapp", ent);
    request.setAttribute("bodyJsp", "/templates/edit/specific/ents_edit.jsp");
    request.setAttribute("title", "Individual Control Panel");
    request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + application.getThemeDir()
            + "css/edit.css\"/>");
    request.setAttribute("scripts", "/templates/edit/specific/ents_edit_head.jsp");

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

}

From source file:org.jtwig.util.render.RenderHttpServletRequest.java

public RenderHttpServletRequest(HttpServletRequest initialRequest) {
    initialValues = snapshot(initialRequest, HttpServletRequest.class);
    Enumeration attributeNames = initialRequest.getAttributeNames();
    if (attributeNames != null) {
        while (attributeNames.hasMoreElements()) {
            String name = (String) attributeNames.nextElement();
            attributes.put(name, initialRequest.getAttribute(name));
        }//from  www . j av a2s .  co m
    }
    realPath = initialRequest.getRealPath("");
    requestDispatcher = initialRequest.getRequestDispatcher(initialRequest.getServletPath());
}