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.jeeframework.webframework.filter.dispatcher.JSONJspServletDispatcherResult.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.//from   w w  w. java 2 s  .co  m
 * 
 * @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.
 */
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();

        String curFileName = StringUtils.getFileNamePreffix(finalLocation);
        String curFileSuffix = StringUtils.getFilenameExtension(finalLocation);
        String dstFile = curFileName;

        if (curFileName.startsWith(JSONJspServletDispatcherResult.JSONJSP_PREFIX)
                && curFileName.length() > JSONJspServletDispatcherResult.JSONJSP_PREFIX.length()) {
            dstFile = curFileName.substring(JSONJspServletDispatcherResult.JSONJSP_PREFIX.length());
        }
        if (curFileName.endsWith(JSONJspServletDispatcherResult.JSONJSP_SUFFIX)
                && curFileName.length() > JSONJspServletDispatcherResult.JSONJSP_SUFFIX.length()) {
            dstFile = dstFile.substring(0,
                    dstFile.length() - JSONJspServletDispatcherResult.JSONJSP_SUFFIX.length());
        }

        String webroot = System.getProperty(StrutsPrepareAndExecuteFilterWrapper.CUR_DEFAULT_WEBROOT_KEY);
        if (!webroot.endsWith("/") && !webroot.endsWith("\\")) {
            webroot = webroot + "/";
        }

        String dstFilePath = webroot + finalLocation;

        File dstCurjsp = new File(dstFilePath);
        // && !dstCurjsp.exists()
        if (!dstCurjsp.exists()) {
            try {
                String srcFilePath = webroot;//
                if (!(dstFile.startsWith("/") || dstFile.startsWith("\\"))) {
                    srcFilePath = srcFilePath + "/";
                }
                srcFilePath = srcFilePath + dstFile + "." + curFileSuffix;

                File srcCurjsp = new File(srcFilePath);

                String srcCurjspContent = FileUtils.readFileToString(srcCurjsp,
                        StrutsPrepareAndExecuteFilterWrapper.FILE_ENCODING);
                srcCurjspContent = srcCurjspContent.replaceAll("[\r\n\t]", "");

                FileUtils.writeStringToFile(dstCurjsp, srcCurjspContent,
                        StrutsPrepareAndExecuteFilterWrapper.FILE_ENCODING);

            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("? jsonjsp " + dstFilePath + "error");
            }
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

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

            return;
        }

        // If we're included, then include the view
        // Otherwise do forward
        // This allow the page to, for example, set content type
        if (!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.Sor.User.LoginServlet.java

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

        session = request.getSession(true);
        //response.setContentType("text/html");  
        PrintWriter out = response.getWriter();
        String n = request.getParameter("usr");
        String p = request.getParameter("pass");
        System.out.println(n);/*from   ww  w. j a va  2  s  .  c  o m*/
        System.out.println(p);

        if (validate(n, p)) {
            String url = "/viewPerson.jsp";
            RequestDispatcher rd = request.getRequestDispatcher(url);
            rd.forward(request, response);
            //HttpServletResponse.sendRedirect(url);
        } else {
            out.print("Sorry. Wrong username or password! ");
        }
        out.close();

    }

From source file:pt.webdetails.cns.notifications.sparkl.kettle.baserver.web.utils.HttpConnectionHelper.java

protected static Response invokePlatformEndpoint(final String endpointPath, final String httpMethod,
        final Map<String, String> queryParameters) {

    Response response = new Response();

    // get servlet context and request dispatcher
    ServletContext servletContext = null;
    RequestDispatcher requestDispatcher = null;
    try {/*from  w ww  .  j ava  2  s  .  c o m*/
        Object context = PentahoSystem.getApplicationContext().getContext();
        if (context instanceof ServletContext) {
            servletContext = (ServletContext) context;
            requestDispatcher = servletContext.getRequestDispatcher("/api" + endpointPath);
        }
    } catch (NoClassDefFoundError ex) {
        logger.error("Failed to get application servlet context", ex);
        return response;
    }

    if (requestDispatcher != null) {

        // create servlet request
        final InternalHttpServletRequest servletRequest = new InternalHttpServletRequest(httpMethod, "/pentaho",
                "/api", endpointPath);
        servletRequest.setAttribute("org.apache.catalina.core.DISPATCHER_TYPE", 2); // FORWARD = 2

        for (Map.Entry<String, String> entry : queryParameters.entrySet()) {
            servletRequest.setParameter(entry.getKey(), entry.getValue());
        }

        ServletRequestEvent servletRequestEvent = new ServletRequestEvent(servletContext, servletRequest);
        RequestContextListener requestContextListener = new RequestContextListener();
        requestContextListener.requestInitialized(servletRequestEvent);

        // create servlet response
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final InternalHttpServletResponse servletResponse = new InternalHttpServletResponse(outputStream);

        try {
            // used for calculating the response time
            long startTime = System.currentTimeMillis();

            requestDispatcher.forward(servletRequest, servletResponse);

            // get response time
            long responseTime = System.currentTimeMillis() - startTime;

            response.setStatusCode(servletResponse.getStatus());
            response.setResult(servletResponse.getContentAsString());
            response.setResponseTime(responseTime);
        } catch (ServletException ex) {
            logger.error("Failed ", ex);
            return response;
        } catch (IOException ex) {
            logger.error("Failed ", ex);
            return response;
        } finally {
            requestContextListener.requestDestroyed(servletRequestEvent);
        }

    }

    return response;
}

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

@Override
public void doPost(HttpServletRequest rawRequest, HttpServletResponse res)
        throws ServletException, IOException {
    try {//from   w ww  . j  av  a 2 s.  co  m
        VitroRequest req = new VitroRequest(rawRequest);
        if (req.hasFileSizeException()) {
            throw new FdcException("Size limit exceeded: " + req.getFileSizeException().getLocalizedMessage());
        }
        if (!req.isMultipart()) {
            throw new FdcException("Must POST a multipart encoded request");
        }

        //check if fedora is on line
        OntModel sessionOntModel = ModelAccess.on(getServletContext()).getOntModel();
        synchronized (FedoraDatastreamController.class) {
            if (fedoraUrl == null) {
                setup(sessionOntModel, getServletContext());
                if (fedoraUrl == null)
                    throw new FdcException("Connection to the file repository is "
                            + "not setup correctly.  Could not read fedora.properties file");
            } else {
                if (!canConnectToFedoraServer()) {
                    fedoraUrl = null;
                    throw new FdcException("Could not connect to Fedora.");
                }
            }
        }
        FedoraClient fedora;
        try {
            fedora = new FedoraClient(fedoraUrl, adminUser, adminPassword);
        } catch (MalformedURLException e) {
            throw new FdcException("Malformed URL for fedora Repository location: " + fedoraUrl);
        }
        FedoraAPIM apim;
        try {
            apim = fedora.getAPIM();
        } catch (Exception e) {
            throw new FdcException("could not create fedora APIM:" + e.getMessage());
        }

        //get the parameters from the request
        String pId = req.getParameter("pid");
        String dsId = req.getParameter("dsid");
        String fileUri = req.getParameter("fileUri");

        boolean useNewName = false;
        if ("true".equals(req.getParameter("useNewName"))) {
            useNewName = true;
        }
        if (pId == null || pId.length() == 0)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing pid parameter)");
        if (dsId == null || dsId.length() == 0)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing dsid parameter)");
        if (fileUri == null || fileUri.length() == 0)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing fileUri parameter)");

        FileItem fileRes = req.getFileItem("fileRes");
        if (fileRes == null)
            throw new FdcException("Your form submission did not contain "
                    + "enough information to complete your request.(Missing fileRes)");

        //check if file individual has a fedora:PID for a data stream
        VitroRequest vreq = new VitroRequest(rawRequest);
        IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao();
        Individual fileEntity = iwDao.getIndividualByURI(fileUri);

        //check if logged in
        //TODO: check if logged in

        //check if user is allowed to edit datastream
        //TODO:check if can edit datastream

        //check if digital object and data stream exist in fedora
        Datastream ds = apim.getDatastream(pId, dsId, null);
        if (ds == null)
            throw new FdcException(
                    "There was no datastream in the " + "repository for " + pId + " " + DEFAULT_DSID);

        //upload to temp holding area
        String originalName = fileRes.getName();
        String name = originalName.replaceAll("[,+\\\\/$%^&*#@!<>'\"~;]", "_");
        name = name.replace("..", "_");
        name = name.trim().toLowerCase();

        String saveLocation = baseDirectoryForFiles + File.separator + name;
        String savedName = name;
        int next = 0;
        boolean foundUnusedName = false;
        while (!foundUnusedName) {
            File test = new File(saveLocation);
            if (test.exists()) {
                next++;
                savedName = name + '(' + next + ')';
                saveLocation = baseDirectoryForFiles + File.separator + savedName;
            } else {
                foundUnusedName = true;
            }
        }

        File uploadedFile = new File(saveLocation);

        try {
            fileRes.write(uploadedFile);
        } catch (Exception ex) {
            log.error("Unable to save POSTed file. " + ex.getMessage());
            throw new FdcException("Unable to save file to the disk. " + ex.getMessage());
        }

        //upload to temp area on fedora
        File file = new File(saveLocation);
        String uploadFileUri = fedora.uploadFile(file);
        // System.out.println("Fedora upload temp = upload file uri is " + uploadFileUri);
        String md5 = md5hashForFile(file);
        md5 = md5.toLowerCase();

        //make change to data stream on fedora
        apim.modifyDatastreamByReference(pId, dsId, null, null, fileRes.getContentType(), null, uploadFileUri,
                "MD5", null, null, false);

        String checksum = apim.compareDatastreamChecksum(pId, dsId, null);

        //update properties like checksum, file size, and content type

        WebappDaoFactory wdf = vreq.getWebappDaoFactory();
        DataPropertyStatement dps = null;
        DataProperty contentType = wdf.getDataPropertyDao().getDataPropertyByURI(this.contentTypeProperty);
        if (contentType != null) {
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, contentType);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(contentType.getURI());
            dps.setData(fileRes.getContentType());
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
        }

        DataProperty fileSize = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileSizeProperty);
        if (fileSize != null) {
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileSize);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(fileSize.getURI());
            dps.setData(Long.toString(fileRes.getSize()));
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
            //System.out.println("Updated file size with " + fileRes.getSize());
        }

        DataProperty checksumDp = wdf.getDataPropertyDao().getDataPropertyByURI(this.checksumDataProperty);
        if (checksumDp != null) {
            //System.out.println("Checksum data property is also not null");
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, checksumDp);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(checksumDp.getURI());
            dps.setData(checksum);
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
        }

        //I'm leaving if statement out for now as the above properties are obviously being replaced as well
        //if( "true".equals(useNewName)){
        //Do we need to encapuslate in this if OR is this path always for replacing a file
        //TODO: Put in check to see if file name has changed and only execute these statements if file name has changed
        DataProperty fileNameProperty = wdf.getDataPropertyDao().getDataPropertyByURI(this.fileNameProperty);
        if (fileNameProperty != null) {
            wdf.getDataPropertyStatementDao()
                    .deleteDataPropertyStatementsForIndividualByDataProperty(fileEntity, fileNameProperty);
            dps = new DataPropertyStatementImpl();
            dps.setIndividualURI(fileEntity.getURI());
            dps.setDatapropURI(fileNameProperty.getURI());
            dps.setData(originalName); //This follows the pattern of the original file upload - the name returned from the uploaded file object
            wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
            //System.out.println("File name property is not null = " + fileNameProperty.getURI() + " updating to " + originalName);
        } else {
            //System.out.println("file name property is null");
        }

        //Need to also update the check sum node - how would we do that
        //Find checksum node related to this particular file uri, then go ahead and update two specific fields

        List<ObjectPropertyStatement> csNodeStatements = fileEntity.getObjectPropertyMap()
                .get(this.checksumNodeProperty).getObjectPropertyStatements();
        if (csNodeStatements.size() == 0) {
            System.out.println("No object property statements correspond to this property");
        } else {
            ObjectPropertyStatement cnodeStatement = csNodeStatements.get(0);
            String cnodeUri = cnodeStatement.getObjectURI();
            //System.out.println("Checksum node uri is " + cnodeUri);

            Individual checksumNodeObject = iwDao.getIndividualByURI(cnodeUri);

            DataProperty checksumDateTime = wdf.getDataPropertyDao()
                    .getDataPropertyByURI(this.checksumNodeDateTimeProperty);
            if (checksumDateTime != null) {
                String newDatetime = sessionOntModel.createTypedLiteral(new DateTime()).getString();
                //Review how to update date time
                wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(
                        checksumNodeObject, checksumDateTime);
                dps = new DataPropertyStatementImpl();
                dps.setIndividualURI(checksumNodeObject.getURI());
                dps.setDatapropURI(checksumDateTime.getURI());
                dps.setData(newDatetime);
                wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);

            }
            DataProperty checksumNodeValue = wdf.getDataPropertyDao()
                    .getDataPropertyByURI(this.checksumDataProperty);
            if (checksumNodeValue != null) {
                wdf.getDataPropertyStatementDao().deleteDataPropertyStatementsForIndividualByDataProperty(
                        checksumNodeObject, checksumNodeValue);
                dps = new DataPropertyStatementImpl();
                dps.setIndividualURI(checksumNodeObject.getURI());
                dps.setDatapropURI(checksumNodeValue.getURI());
                dps.setData(checksum); //Same as fileName above - change if needed
                wdf.getDataPropertyStatementDao().insertNewDataPropertyStatement(dps);
            }

        }

        //Assumes original entity name is equal to the location - as occurs with regular file upload
        String originalEntityName = fileEntity.getName();
        if (originalEntityName != originalName) {
            //System.out.println("Setting file entity to name of uploaded file");
            fileEntity.setName(originalName);
        } else {
            //System.out.println("Conditional for file entity name and uploaded name is saying same");
        }
        iwDao.updateIndividual(fileEntity);
        //}

        req.setAttribute("fileUri", fileUri);
        req.setAttribute("originalFileName", fileEntity.getName());
        req.setAttribute("checksum", checksum);
        if ("true".equals(useNewName)) {
            req.setAttribute("useNewName", "true");
            req.setAttribute("newFileName", originalName);
        } else {
            req.setAttribute("newFileName", fileEntity.getName());
        }

        //forward to form     
        req.setAttribute("bodyJsp", "/fileupload/datastreamModificationSuccess.jsp");
        RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
        rd.forward(req, res);
    } catch (FdcException ex) {
        rawRequest.setAttribute("errors", ex.getMessage());
        RequestDispatcher rd = rawRequest.getRequestDispatcher("/edit/fileUploadError.jsp");
        rd.forward(rawRequest, res);
        return;
    }
}

From source file:at.gv.egovernment.moa.id.auth.servlet.AuthServlet.java

/**
 * Handles a <code>WrongParametersException</code>.
 * /*  www  . j  av a 2s.  c  o  m*/
 * @param req
 *            servlet request
 * @param resp
 *            servlet response
 */
protected void handleWrongParameters(WrongParametersException ex, HttpServletRequest req,
        HttpServletResponse resp) {
    Logger.error(ex.toString());
    req.setAttribute("WrongParameters", ex.getMessage());

    // forward this to errorpage-auth.jsp where the HTML error page is
    // generated
    ServletContext context = getServletContext();
    RequestDispatcher dispatcher = context.getRequestDispatcher("/errorpage-auth.jsp");
    try {
        resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
        resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
        resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
        resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,
                MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);

        dispatcher.forward(req, resp);
    } catch (ServletException e) {
        Logger.error(e);
    } catch (IOException e) {
        Logger.error(e);
    }
}

From source file:com.alfaariss.oa.sso.web.profile.logout.LogoutProfile.java

private void showConfirmJSP(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        ISession session, List<IRequestor> listRequestors, IRequestor requestor) throws OAException {
    try {/*from w ww .java2s  .  co  m*/
        servletRequest.setAttribute(ISession.ID_NAME, session.getId());
        servletRequest.setAttribute("requestors", listRequestors);
        servletRequest.setAttribute("requestor", requestor);
        servletRequest.setAttribute("user", session.getUser());

        //Set server info as attribute
        servletRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer());
        //Forward to page                
        RequestDispatcher oDispatcher = servletRequest.getRequestDispatcher(_sJSPConfirmation);
        if (oDispatcher != null)
            oDispatcher.forward(servletRequest, servletResponse);
        else {
            _logger.fatal("Forward request not supported");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error during jsp forward", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.alfaariss.oa.sso.web.profile.logout.LogoutProfile.java

private void showLogoutJSP(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        SessionState state, String sessionID, List<TGTEventError> warnings) throws OAException {
    try {/*from w  w  w  .  j  a v  a 2  s  .c  om*/
        if (sessionID != null)
            servletRequest.setAttribute(ISession.ID_NAME, sessionID);

        if (state != null)
            servletRequest.setAttribute(JSP_LOGOUT_STATE, state);

        if (warnings != null) {
            servletRequest.setAttribute(DetailedUserException.DETAILS_NAME, warnings);
        }

        //Show user info
        //Set server info as attribute
        servletRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer());
        //Forward to page                
        RequestDispatcher oDispatcher = servletRequest.getRequestDispatcher(_sJSPUserLogout);
        if (oDispatcher != null)
            oDispatcher.forward(servletRequest, servletResponse);
        else {
            _logger.fatal("Forward request not supported");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error during jsp forward to logout page", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:at.gv.egovernment.moa.id.auth.servlet.AuthServlet.java

protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, HttpServletRequest req,
        HttpServletResponse resp) {/*from   ww  w . j a  v a2  s . c o  m*/

    if (null != errorMessage) {
        Logger.error(errorMessage);
        req.setAttribute("ErrorMessage", errorMessage);
    }

    if (null != exceptionThrown) {
        if (null == errorMessage)
            errorMessage = exceptionThrown.getMessage();
        Logger.error(errorMessage, exceptionThrown);
        req.setAttribute("ExceptionThrown", exceptionThrown);
    }

    if (Logger.isDebugEnabled()) {
        req.setAttribute("LogLevel", "debug");
    }

    StatisticLogger logger = StatisticLogger.getInstance();
    logger.logErrorOperation(exceptionThrown);

    // forward this to errorpage-auth.jsp where the HTML error page is
    // generated
    ServletContext context = getServletContext();
    RequestDispatcher dispatcher = context.getRequestDispatcher("/errorpage-auth.jsp");
    try {

        resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
        resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
        resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
        resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,
                MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);

        dispatcher.forward(req, resp);
    } catch (ServletException e) {
        Logger.error(e);
    } catch (IOException e) {
        Logger.error(e);
    }
}

From source file:Control.FrontControl.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w ww  . j av  a2  s .  c o m*/
 *
 * @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(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8"); //Characterencoding for special characters

    //This part of the code, checks if there might be files for upload, and seperates them, if that is the case
    Collection<Part> parts = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        parts = request.getParts(); //Extracts the part of the form that has files and parameters
    }

    HttpSession sessionObj = request.getSession(); //Get the session
    DomainFacade df = (DomainFacade) sessionObj.getAttribute("Controller"); //Get the DomainFacede
    //If it is a new session, create a new DomainFacade Object and put it in the session.
    sessionObj.setAttribute("testing", testing);
    if (df == null) {
        df = DomainFacade.getInstance();
        sessionObj.setAttribute("Controller", df);
    }

    //Set base url
    String url = "/index.jsp";
    String action = request.getParameter("action");
    if (action == null) {
        action = "";
    }

    String page = request.getParameter("page");
    if (testing) {
        System.out.println("Redirect parameter (page) set to:");
    }
    if (testing) {
        System.out.println(page);
    }
    try {
        if (page == null) {
            page = "";
        }
        //For creating a new report
        if (page.equalsIgnoreCase("newreport")) {
            url = "/reportJSPs/choosebuilding.jsp";
            sessionObj.setAttribute("customerSelcted", false);
            cuh.chooseCustomer(sessionObj, df);
        }
        //For choosing the customer //TODO split redirect and action
        if (page.equalsIgnoreCase("report_cus_choosen")) {
            url = "/reportJSPs/choosebuilding.jsp";
            bh.loadCustomersBuildings(request, sessionObj, df);
        }
        //When building has been chosen, it sets up the report object
        if (page.equalsIgnoreCase("report_start")) {
            url = "/reportJSPs/report_start.jsp";
            rh.createReport(request, sessionObj, df);
        }

        //For choosing room when setting up report, after exterior has been added
        if (page.equalsIgnoreCase("ChooseRoom")) {
            url = "/reportJSPs/chooseroom.jsp";
            rh.saveReportExterior(request, sessionObj, parts, this);
        }

        //For inspecting the chosen room.
        if (page.equalsIgnoreCase("inspectRoom")) {
            url = "/reportJSPs/reportaddaroom.jsp";
            rh.setUpForRoomInspection(request, sessionObj, df, parts);
        }

        //For submitting what is written about the room
        if (page.equalsIgnoreCase("submittedRoom")) {
            url = "/reportJSPs/chooseroom.jsp";
            rh.createReportRoomElements(request, sessionObj, parts, this);
        }

        //Saving finished report and redirection to report view. 
        if (page.equalsIgnoreCase("saveFinishedReport")) {
            url = "/viewreport.jsp";
            rh.finishReportObject(request, sessionObj);
            int reportId = rh.saveFinishedReport(sessionObj, df);
            request.getSession().setAttribute("report", df.getReport(reportId));
        }

        if (page.equalsIgnoreCase("toFinishReport")) {
            url = "/reportJSPs/finishreport.jsp";
        }
        if (page.equalsIgnoreCase("backToChooseRoom")) {
            url = "/reportJSPs/chooseroom.jsp";
        }

        //For inspecting a room you just added to the building
        if (page.equalsIgnoreCase("inspectRoomjustCreated")) {
            url = "/reportJSPs/reportaddaroom.jsp";
            bh.createNewRoom(request, sessionObj, df);
            rh.setUpForRoomInspection(request, sessionObj, df, parts);
        }

        //List all reports for all customers
        if (page.equalsIgnoreCase("listreports")) {
            sessionObj.setAttribute("reports", df.getListOfReports(1));
            response.sendRedirect("viewreports.jsp");
            return;
        }
        if (page.equalsIgnoreCase("addbuilding")) {
            url = "/addbuilding.jsp";
        }
        if (page.equalsIgnoreCase("addcustomer")) {
            url = "/addcustomer.jsp";
        }

        //Viewing the list of all the 
        if (page.equalsIgnoreCase("viewmybuildings")) {
            bh.findListOfBuilding(request, df, sessionObj);
            User tempUser = (User) request.getSession().getAttribute("user");
            List<Building> buildings = df.getListOfBuildings(tempUser.getCustomerid());
            url = "/viewcustomer.jsp";
            sessionObj.setAttribute("buildings", buildings);
        }

        //Edit a building
        if (page.equalsIgnoreCase("editBuilding")) {
            bh.findBuildingToBeEdit(request, sessionObj, df);
            response.sendRedirect("editBuilding.jsp");
            return;
        }

        if (page.equalsIgnoreCase("viewreport")) {
            int reportId = Integer.parseInt(request.getParameter("reportid"));
            Report report = df.getReport(reportId);
            sessionObj.setAttribute("report", report);
            response.sendRedirect("viewreport.jsp");
            return;
        }

        if (page.equalsIgnoreCase("viewcustomers")) {
            List<Customer> customers = df.loadAllCustomers();
            sessionObj.setAttribute("customers", customers);
            response.sendRedirect("viewcustomers.jsp");
            return;
        }

        if (page.equalsIgnoreCase("viewcustomer")) {
            int custId = Integer.parseInt(request.getParameter("customerid"));
            sessionObj.setAttribute("customer_id", custId);
            List<Building> buildings = df.getListOfBuildings(custId);
            List<Customer> customers = df.loadAllCustomers();
            for (Customer customer : customers) {
                if (customer.getCustomerId() == custId) {
                    sessionObj.setAttribute("customer", customer);
                }
            }
            sessionObj.setAttribute("buildings", buildings);
            response.sendRedirect("viewcustomer.jsp");
            return;
        }

        //This gets a Dashboard for a building
        if (page.equalsIgnoreCase("viewbuildingadmin")) {
            System.out.println("Did it go here?");
            int buildId = Integer.parseInt(request.getParameter("buildingid"));
            Building b = df.getBuilding(buildId);
            sessionObj.setAttribute("building", b);
            response.sendRedirect("viewbuildingadmin.jsp");
            return;
        }

        //TODO seperate redirect and action
        if (page.equalsIgnoreCase("newbuilding")) {

            Building b = bh.createBuilding(request, df, sessionObj, parts, this);
            response.sendRedirect("viewnewbuilding.jsp");
            return;
        }

        //TODO: seperate action and redirect
        if (page.equalsIgnoreCase("vieweditedbuilding")) {
            Building b = bh.updateBuilding(request, df, sessionObj, parts, this);
            response.sendRedirect("viewbuildingadmin.jsp");
            return;
        }

        //TODO: seperate action and redirect
        if (page.equalsIgnoreCase("submitcustomer")) {
            cuh.createNewCustomer(request, df, sessionObj, this);
            response.sendRedirect("customersubmitted.jsp");
            return;
        }

        if (page.equalsIgnoreCase("addfloorsubmit")) {
            bh.addFloors(request, df, sessionObj, this);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("selBdg")) {
            bh.selectBuilding(request, df, sessionObj, this);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("addfloor")) {
            sessionObj.setAttribute("customerSelcted", false);
            cuh.chooseCustomer(sessionObj, df);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("selCust")) {
            bh.loadCustomersBuildings(request, sessionObj, df);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("loadFloors")) {
            bh.loadFloors(request, sessionObj, df, this);
            response.sendRedirect("addfloor.jsp");
            return;
        }

        if (page.equalsIgnoreCase("selFlr")) {
            bh.selectFloor(request, sessionObj, df, this);
            response.sendRedirect("addroom.jsp");
            return;
        }

        if (page.equalsIgnoreCase("loadRooms")) {
            bh.loadRooms(request, sessionObj, df, this);
            response.sendRedirect("addroom.jsp");
            return;
        }

        if (page.equalsIgnoreCase("addroomsubmit")) {
            bh.addRoom(request, sessionObj, df, this);
            response.sendRedirect("addroom.jsp");
            return;
        }

        //loading order request page
        if (page.equalsIgnoreCase("orderRequest")) {
            bh.loadBuildingsAfterLogIn(sessionObj, df, this);
            response.sendRedirect("orderRequest.jsp");
            return;
        }

        //selecting a building for order request
        if (page.equalsIgnoreCase("selBdgReq")) {
            bh.selectBuilding(request, df, sessionObj, this);
            response.sendRedirect("orderRequest.jsp");
            return;
        }

        //create an order request
        if (page.equalsIgnoreCase("orderRequestSubmit")) {
            oh.saveOrder(request, sessionObj, df, this);
            response.sendRedirect("ordersuccess.jsp");
            return;
        }

        //displays the order history and order progress
        if (page.equalsIgnoreCase("orderhistory")) {
            oh.loadCustomerOrders(sessionObj, df, this);
            response.sendRedirect("orderhistory.jsp");
            return;
        }

        //displays the order list and order progress
        if (page.equalsIgnoreCase("orderslist")) {
            oh.loadAllOrders(sessionObj, df);
            response.sendRedirect("orderslist.jsp");
            return;
        }

        //displays the order details
        if (page.equalsIgnoreCase("vieworder")) {
            int orderNumber = Integer.parseInt(request.getParameter("ordernumber"));
            sessionObj.setAttribute("orderNumber", orderNumber);
            sessionObj.setAttribute("selectedOrder", df.getOrder(orderNumber));
            response.sendRedirect("vieworder.jsp");
            return;
        }

        //updates the order progress
        if (page.equalsIgnoreCase("updateStat")) {
            int newStat = Integer.parseInt(request.getParameter("orderstatus"));
            Order o = (Order) sessionObj.getAttribute("selectedOrder");
            df.updateStatus(o.getOrderNumber(), newStat);
            oh.loadAllOrders(sessionObj, df);
            response.sendRedirect("orderslist.jsp");
            return;
        }

        if (page.equalsIgnoreCase("continue")) {
            url = "/addroom.jsp";
        }

        if (page.equalsIgnoreCase("login")) {
            url = "/login.jsp";

        }
        if (page.equalsIgnoreCase("loguserin")) {
            if (request.getParameter("empOrCus").equals("emp")) {
                cuh.emplogin(df, request, response);
            } else {
                cuh.login(df, request, response);
            }
            url = "/login.jsp";
        }

        if (page.equalsIgnoreCase("logout")) {
            request.setAttribute("user", null);
            request.setAttribute("loggedin", false);
            request.getSession().invalidate();
            url = "/index.jsp";
        }

        if (page.equalsIgnoreCase("printReport")) {
            rh.printReport(sessionObj, df, response, this);
            return;
        }

        if (request.getServletPath().equalsIgnoreCase("/viewreports")) {
            url = "/viewreports.jsp";
        }
        if (request.getServletPath().equalsIgnoreCase("/getreport")) {
            url = "/viewreport.jsp";
        }
        System.out.println(request.getServletPath());
        System.out.println(request.getMethod());

        //get the building and send it to the sessionobj
        System.out.println("test of action: " + action);
        if (action.equalsIgnoreCase("viewbuildingadmin")) {
            System.out.println("test!");
            int buildId = Integer.parseInt(request.getParameter("buildingid"));
            Building b = df.getBuilding(buildId);
            request.getSession().setAttribute("building", b);
            request.setAttribute("showBuilding", true);
            url = "/viewbuildingadmin.jsp";

        }

        //retrieve a room from the buildingobject and put it in response.
        if (action.equalsIgnoreCase("viewroom")) {
            Building b = (Building) request.getSession().getAttribute("building");
            int roomNumber;
            String viewReportRoomString = request.getParameter("viewroom");
            if (viewReportRoomString != null && b != null) {
                roomNumber = Integer.parseInt(viewReportRoomString);
                BuildingRoom r = b.returnARoom(roomNumber);
                request.getSession().setAttribute("room", r);
                request.getSession().setAttribute("building", b);
                request.setAttribute("showRoom", true);
                url = "/viewbuildingadmin.jsp";

            }
        }

        if (action.equalsIgnoreCase("addfloor")) {
            request.setAttribute("addFloor", true);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("addroom")) {
            int floorId = Integer.parseInt(request.getParameter("floor"));
            request.setAttribute("addRoom", true);
            request.setAttribute("floorId", floorId);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("listreports")) {
            request.getSession().setAttribute("reports", df.getSimpleListOfReports());
        }

        if (action.equalsIgnoreCase("addfloorsubmit")) {
            bh.addFloors(request, df);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("addroomsubmit")) {
            int floorId = Integer.parseInt(request.getParameter("floorID"));
            bh.addRoom(request, df, floorId);
            request.setAttribute("showBuilding", true);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("editbuilding")) {
            request.setAttribute("editBuilding", true);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("showBuilding")) {
            request.setAttribute("showBuilding", true);
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("showreport")) {

            int reportId = Integer.parseInt(request.getParameter("reportid"));
            Report report = df.getReport(reportId);
            Building b = df.getBuilding(report.getBuildingId());
            report.setBuildingName(b.getBuildingName());
            //
            request.getSession().setAttribute("report", report);

        }
        if (action.equalsIgnoreCase("reportroom")) {

            int reportRoomId = Integer.parseInt(request.getParameter("viewroom"));
            Report report = (Report) request.getSession().getAttribute("report");
            ReportRoom rr = report.getReportRoomFromReportFloor(reportRoomId);
            //
            request.setAttribute("reportroom", rr);
            request.setAttribute("showroom", true);
            url = "/viewreport.jsp";

        }

        //Trying to see if I can work this out
        if (action.equalsIgnoreCase("roomfiles")) {
            //int buildId = Integer.parseInt(request.getParameter("buildingid"));
            request.setAttribute("roomfiles", true);
            //request.setAttribute("reportroom", report.getReportRoomFromReportFloor(roomId) );
            url = "/viewbuildingadmin.jsp";

        }
        if (action.equalsIgnoreCase("addfloorplans")) {
            Building b = (Building) request.getSession().getAttribute("building");
            ArrayList<BuildingFloor> bfList = df.listOfFloors(b.getBdgId());
            ArrayList<Floorplan> plans = df.getFloorplans(bfList);
            request.getSession().setAttribute("floorplans", plans);
            request.getSession().setAttribute("floorsList", bfList);
            request.setAttribute("addfloorplans", true);
            url = "/viewbuildingadmin.jsp";

        }

        if (action.equalsIgnoreCase("addfilessubmit")) {
            request = nfu.addFiles(request, parts, df, this);
            url = "/viewbuildingadmin.jsp";

        }

        if (action.equalsIgnoreCase("addfloorplanssubmit")) {
            request = nfu.addFloorplans(request, parts, df, this);
            url = "/viewbuildingadmin.jsp";

        }

        if (action.equalsIgnoreCase("addBuilding")) {
            Building b = new Building();
            b.setBuildingName("tempname");
            request.getSession().setAttribute("building", b);

        }
        if (action.equalsIgnoreCase("viewbuildingadmin")) {
            int buildId = Integer.parseInt(request.getParameter("buildingid"));
            Building b = df.getBuilding(buildId);
            request.getSession().setAttribute("building", b);
        }
        if (action.equalsIgnoreCase("viewbuildingreports")) {
            request.setAttribute("viewbuildingreports", true);
            url = "/viewbuildingadmin.jsp";

        }
    } catch (PolygonException ex) {
        Logger.getLogger(FrontControl.class.getName()).log(Level.SEVERE, null, ex);
        request.setAttribute("errormessage", ex.getMessage());
        url = "/errorpage.jsp";
    }
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);
}

From source file:RestrictedService.java

/**
 * When the servlet receives a POST request.
 * /*  www  . j  a  v  a2 s .  c  om*/
 * SIMILIAR DOCUMENTATION AS SAGAtoNIF PROJECT
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String forward = "";
    String eurosentiment = "";
    HttpEntity entity = null;
    //HttpResponse responseMARL = null;
    HttpSession session = request.getSession();
    RequestDispatcher view;
    // Get a map of the request parameters
    Map parameters = request.getParameterMap();
    if (parameters.containsKey("input")) {
        if (parameters.containsKey("intype") && parameters.containsKey("informat")
                && parameters.containsKey("outformat")) {
            if (!request.getParameter("intype").equalsIgnoreCase("direct")) {
                forward = RESPONSE_JSP;
                eurosentiment = "intype should be direct";
                session.setAttribute("eurosentiment", eurosentiment);
                view = request.getRequestDispatcher(forward);
                view.forward(request, response);
                return;
            }
            if (!request.getParameter("informat").equalsIgnoreCase("text")) {
                forward = RESPONSE_JSP;
                eurosentiment = "informat should be text";
                session.setAttribute("eurosentiment", eurosentiment);
                view = request.getRequestDispatcher(forward);
                view.forward(request, response);
                return;
            }
            if (!request.getParameter("outformat").equalsIgnoreCase("json-ld")) {
                forward = RESPONSE_JSP;
                eurosentiment = "outformat should be json-ld";
                session.setAttribute("eurosentiment", eurosentiment);
                view = request.getRequestDispatcher(forward);
                view.forward(request, response);
                return;
            }
            //Check that in not url or the other type
            forward = RESPONSE_JSP;
            String textToAnalize = request.getParameter("input");
            try {
                if (parameters.containsKey("algo")) {
                    if (request.getParameter("algo").equalsIgnoreCase("enFinancial")) {
                        entity = callSAGA(textToAnalize, "enFinancial");
                    } else if (request.getParameter("algo").equalsIgnoreCase("enFinancialEmoticon")) {
                        entity = callSAGA(textToAnalize, "enFinancialEmoticon");
                    } else if (request.getParameter("algo").equalsIgnoreCase("ANEW2010All")) {
                        entity = callANEW(textToAnalize, "ANEW2010All");
                    } else if (request.getParameter("algo").equalsIgnoreCase("ANEW2010Men")) {
                        entity = callANEW(textToAnalize, "ANEW2010Men");
                    } else if (request.getParameter("algo").equalsIgnoreCase("ANEW2010Women")) {
                        entity = callANEW(textToAnalize, "ANEW2010Women");
                    }
                }

                if (entity != null) {
                    InputStream instream = entity.getContent();
                    try {
                        BufferedReader in = new BufferedReader(new InputStreamReader(instream));
                        String inputLine;
                        StringBuffer marl = new StringBuffer();

                        while ((inputLine = in.readLine()) != null) {
                            marl.append(inputLine);
                            marl.append("\n");
                        }
                        in.close();
                        eurosentiment = marl.toString();
                        session.setAttribute("eurosentiment", eurosentiment);

                    } finally {
                        instream.close();
                    }
                }
            } catch (Exception e) {
                System.err.println(e);
            }
        } else {
            forward = RESPONSE_JSP;
            eurosentiment = "There is no intype, informat or outformat especified";
            session.setAttribute("eurosentiment", eurosentiment);
        }
    } else {
        forward = RESPONSE_JSP;
        eurosentiment = "There is no input";
        session.setAttribute("eurosentiment", eurosentiment);
    }
    view = request.getRequestDispatcher(forward);
    view.forward(request, response);

}