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:edu.cornell.mannlib.vitro.webapp.controller.edit.Classes2ClassesRetryController.java

public void doPost(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
        return;/*from w w  w .j  a  v  a2  s  . c o m*/
    }

    VitroRequest request = new VitroRequest(req);

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

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    VClassDao vcDao = ModelAccess.on(getServletContext()).getWebappDaoFactory().getVClassDao();
    epo.setDataAccessObject(vcDao);
    Classes2Classes objectForEditing = new Classes2Classes();

    String superclassURIstr = request.getParameter("SuperclassURI");
    String subclassURIstr = request.getParameter("SubclassURI");
    if (superclassURIstr != null && superclassURIstr.length() > 0)
        objectForEditing.setSuperclassURI(superclassURIstr);
    if (subclassURIstr != null && subclassURIstr.length() > 0)
        objectForEditing.setSubclassURI(subclassURIstr);

    epo.setOriginalBean(objectForEditing);

    populateBeanFromParams(objectForEditing, request);

    HashMap hash = new HashMap();
    hash.put("SuperclassURI", FormUtils.makeOptionListFromBeans(vcDao.getAllVclasses(), "URI", "PickListName",
            objectForEditing.getSuperclassURI(), null));
    hash.put("SubclassURI", FormUtils.makeOptionListFromBeans(vcDao.getAllVclasses(), "URI", "PickListName",
            objectForEditing.getSubclassURI(), null));

    FormObject foo = new FormObject();
    foo.setOptionLists(hash);

    epo.setFormObject(foo);

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    String modeStr = request.getParameter("opMode");
    if (modeStr != null && modeStr.equals("disjointWith")) {
        request.setAttribute("editAction", "classes2ClassesOp");
        request.setAttribute("formJsp", "/templates/edit/specific/disjointClasses_retry.jsp");
        request.setAttribute("title", "Disjointness Axiom Editing Form");
    } else if (modeStr != null && modeStr.equals("equivalentClass")) {
        request.setAttribute("editAction", "classes2ClassesOp");
        request.setAttribute("formJsp", "/templates/edit/specific/equivalentClasses_retry.jsp");
        request.setAttribute("title", "Equivalent Class Editing Form");
    } else {
        request.setAttribute("formJsp", "/templates/edit/specific/class2classes_retry.jsp");
        request.setAttribute("title", "Super/Subclass Editing Form");
    }
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "Classes2Classes");
    setRequestAttributes(request, epo);

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

}

From source file:edu.lternet.pasta.portal.MapBrowseServlet.java

/**
 * The doPost method of the servlet. <br>
 * /*from w  w  w. ja  v  a2 s . c o  m*/
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession httpSession = request.getSession();
    String titleHTML = "";
    String creatorsHTML = "";
    String abstractHTML = "";
    String publicationDateHTML = "";
    String spatialCoverageHTML = "";
    String googleMapHTML = "";
    String packageIdHTML = "";
    String resourcesHTML = "";
    String citationHTML = "";
    String provenanceHTML = "";
    String codeGenerationHTML = "";
    String digitalObjectIdentifier = "";
    String pastaDataObjectIdentifier = "";
    String savedDataHTML = "";
    boolean showSaved = false;
    boolean isSaved = false;

    String uid = (String) httpSession.getAttribute("uid");

    if (uid == null || uid.isEmpty()) {
        uid = "public";
    } else {
        showSaved = true;
    }

    Integer id = null;
    boolean isPackageId = false;

    // Accept packageId by parts or whole
    String scope = request.getParameter("scope");
    String identifier = request.getParameter("identifier");
    String revision = request.getParameter("revision");
    String packageid = request.getParameter("packageid");

    try {
        if (scope != null && !(scope.isEmpty()) && identifier != null && !(identifier.isEmpty())) {

            if (revision == null || revision.isEmpty()) {
                revision = "newest";
            }

            id = Integer.valueOf(identifier);
            isPackageId = true;
        } else if (packageid != null && !packageid.isEmpty()) {

            String[] tokens = packageid.split("\\.");

            if (tokens.length == 3) {
                scope = tokens[0];
                identifier = tokens[1];
                id = Integer.valueOf(identifier);
                revision = tokens[2];
                isPackageId = true;
            }
        } else {
            String msg = "A well-formed packageId was not found.";
            throw new UserErrorException(msg);
        }

        if (isPackageId) {
            StringBuilder titleHTMLBuilder = new StringBuilder();
            StringBuilder creatorsHTMLBuilder = new StringBuilder();
            StringBuilder publicationDateHTMLBuilder = new StringBuilder();
            StringBuilder spatialCoverageHTMLBuilder = new StringBuilder();
            StringBuilder googleMapHTMLBuilder = new StringBuilder();
            StringBuilder packageIdHTMLBuilder = new StringBuilder();
            StringBuilder resourcesHTMLBuilder = new StringBuilder();
            StringBuilder citationHTMLBuilder = new StringBuilder();
            StringBuilder provenanceHTMLBuilder = new StringBuilder();
            StringBuilder codeGenerationHTMLBuilder = new StringBuilder();
            StringBuilder savedDataHTMLBuilder = new StringBuilder();

            String packageId = null;

            Integer size = null;
            Integer predecessor = null;
            Integer successor = null;
            String previous = "";
            String next = "";
            String revisions = "";

            String metadataUri = pastaUriHead + "metadata/eml";
            String reportUri = pastaUriHead + "report";
            String dataUri = pastaUriHead + "data/eml";

            String[] uriTokens = null;
            String entityId = null;
            String resource = null;

            String map = null;
            StrTokenizer tokens = null;
            String emlString = null;
            EmlObject emlObject = null;
            ArrayList<Title> titles = null;
            ArrayList<ResponsibleParty> creators = null;

            DataPackageManagerClient dpmClient = null;
            RevisionUtility revUtil = null;

            try {

                dpmClient = new DataPackageManagerClient(uid);

                String revisionList = dpmClient.listDataPackageRevisions(scope, id, null);
                revUtil = new RevisionUtility(revisionList);
                size = revUtil.getSize();

                if (revision.equals("newest"))
                    revision = revUtil.getNewest().toString();

                packageId = scope + "." + id.toString() + "." + revision;
                predecessor = revUtil.getPredecessor(Integer.valueOf(revision));
                successor = revUtil.getSuccessor(Integer.valueOf(revision));

                emlString = dpmClient.readMetadata(scope, id, revision);
                emlObject = new EmlObject(emlString);
                titles = emlObject.getTitles();

                if (showSaved) {
                    SavedData savedData = new SavedData(uid);
                    Integer identifierInt = new Integer(identifier);
                    isSaved = savedData.hasDocid(scope, identifierInt);
                }

                if (showSaved) {
                    String operation = isSaved ? "unsave" : "save";
                    String display = isSaved ? "Remove from your data shelf" : "Add to your data shelf";
                    String imgName = isSaved ? "minus_blue_small.png" : "plus_blue_small.png";

                    savedDataHTMLBuilder.append(
                            "<form style=\"display:inline-block\" id=\"savedData\" class=\"form-no-margin\" name=\"savedDataForm\" method=\"post\" action=\"./savedDataServlet\" >\n");
                    savedDataHTMLBuilder.append(
                            "  <input type=\"hidden\" name=\"operation\" value=\"" + operation + "\" >\n");
                    savedDataHTMLBuilder.append(
                            "  <input type=\"hidden\" name=\"packageId\" value=\"" + packageId + "\" >\n");
                    savedDataHTMLBuilder.append("  <input type=\"hidden\" name=\"forward\" value=\"\" >\n");
                    savedDataHTMLBuilder.append("  <sup><input type=\"image\" name=\"submit\" src=\"images/"
                            + imgName + "\" alt=\"" + display + "\" title=\"" + display + "\"></sup>");
                    savedDataHTMLBuilder.append("</form>\n");
                    savedDataHTML = savedDataHTMLBuilder.toString();
                }

                if (titles != null) {
                    titleHTMLBuilder.append("<ul class=\"no-list-style\">\n");

                    for (Title title : titles) {
                        String listItem = "<li>" + title.getTitle() + "</li>\n";
                        titleHTMLBuilder.append(listItem);
                    }

                    titleHTMLBuilder.append("</ul>\n");
                    titleHTML = titleHTMLBuilder.toString();
                }

                creators = emlObject.getCreators();

                if (creators != null) {

                    creatorsHTMLBuilder.append("<ul class=\"no-list-style\">\n");

                    for (ResponsibleParty creator : creators) {
                        creatorsHTMLBuilder.append("<li>");

                        String individualName = creator.getIndividualName();
                        String positionName = creator.getPositionName();
                        String organizationName = creator.getOrganizationName();

                        if (individualName != null) {
                            creatorsHTMLBuilder.append(individualName);
                        }

                        if (positionName != null) {
                            if (individualName != null) {
                                creatorsHTMLBuilder.append("; " + positionName);
                            } else {
                                creatorsHTMLBuilder.append(positionName);
                            }
                        }

                        if (organizationName != null) {
                            if (positionName != null || individualName != null) {
                                creatorsHTMLBuilder.append("; " + organizationName);
                            } else {
                                creatorsHTMLBuilder.append(organizationName);
                            }
                        }

                        creatorsHTMLBuilder.append("</li>\n");
                    }

                    creatorsHTMLBuilder.append("</ul>\n");
                    creatorsHTML = creatorsHTMLBuilder.toString();
                }

                String abstractText = emlObject.getAbstractText();

                if (abstractText != null) {
                    abstractHTML = toSingleLine(abstractText);
                }

                String pubDate = emlObject.getPubDate();

                if (pubDate != null) {
                    publicationDateHTMLBuilder.append("<ul class=\"no-list-style\">\n");
                    publicationDateHTMLBuilder.append("<li>" + pubDate + "</li>");
                    publicationDateHTMLBuilder.append("</ul>");
                    publicationDateHTML = publicationDateHTMLBuilder.toString();
                }

                map = dpmClient.readDataPackage(scope, id, revision);

                String jsonCoordinates = emlObject.jsonSerializeCoordinates();
                String stringCoordinates = emlObject.stringSerializeCoordinates();

                request.setAttribute("jsonCoordinates", jsonCoordinates);
                if (stringCoordinates != null && !stringCoordinates.equals("")) {

                    String[] coordinatesArray = stringCoordinates.split(":");

                    /*
                     * If there are two or fewer sets of coordinates, then initially
                     * show them expanded, otherwise show them collapsed (to save
                     * screen space.)
                     */
                    request.setAttribute("expandCoordinates", new Boolean((coordinatesArray.length <= 2)));

                    // Only use the expander widget if there's more than one set of coordinates
                    boolean useExpander = (coordinatesArray.length > 1) ? true : false;

                    if (useExpander) {
                        spatialCoverageHTMLBuilder.append("<div id='jqxWidget'>\n");
                        spatialCoverageHTMLBuilder.append("    <div id='jqxExpander'>\n");
                        spatialCoverageHTMLBuilder.append("        <div>Geographic Coordinates</div>\n");
                        spatialCoverageHTMLBuilder.append("        <div>\n");
                        spatialCoverageHTMLBuilder.append("            <ul class=\"no-list-style\">\n");
                        boolean firstCoordinates = true;

                        for (String coordinates : coordinatesArray) {
                            String[] nsew = coordinates.split(",");
                            Double northCoord = new Double(nsew[0]);
                            Double southCoord = new Double(nsew[1]);
                            Double eastCoord = new Double(nsew[2]);
                            Double westCoord = new Double(nsew[3]);
                            if (firstCoordinates) {
                                request.setAttribute("northCoord", northCoord);
                                request.setAttribute("southCoord", southCoord);
                                request.setAttribute("eastCoord", eastCoord);
                                request.setAttribute("westCoord", westCoord);
                            }
                            firstCoordinates = false;
                            String spatial = String.format("N: %s,  S: %s,  E: %s,  W: %s", northCoord,
                                    southCoord, eastCoord, westCoord);
                            spatialCoverageHTMLBuilder.append(String.format("  <li>%s</li>\n", spatial));
                        }

                        spatialCoverageHTMLBuilder.append("            </ul>\n");
                        spatialCoverageHTMLBuilder.append("        </div>\n");
                        spatialCoverageHTMLBuilder.append("    </div>\n");
                        spatialCoverageHTMLBuilder.append("</div>\n");
                    } else {
                        String[] nsew = coordinatesArray[0].split(",");
                        Double northCoord = new Double(nsew[0]);
                        Double southCoord = new Double(nsew[1]);
                        Double eastCoord = new Double(nsew[2]);
                        Double westCoord = new Double(nsew[3]);
                        request.setAttribute("northCoord", northCoord);
                        request.setAttribute("southCoord", southCoord);
                        request.setAttribute("eastCoord", eastCoord);
                        request.setAttribute("westCoord", westCoord);
                        final String spacer = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                        spatialCoverageHTMLBuilder.append("<div>\n");
                        String spatial = String.format("N: %s%sS: %s%sE: %s%sW: %s", northCoord, spacer,
                                southCoord, spacer, eastCoord, spacer, westCoord);
                        spatialCoverageHTMLBuilder.append(String.format("%s\n", spatial));
                        spatialCoverageHTMLBuilder.append("</div>\n");
                    }

                    spatialCoverageHTML = spatialCoverageHTMLBuilder.toString();

                    googleMapHTMLBuilder.append("<ul class=\"no-list-style\">\n");
                    googleMapHTMLBuilder.append("  <li><div id='map-canvas-summary'></div></li>");
                    googleMapHTMLBuilder.append("</ul>\n");
                    googleMapHTML = googleMapHTMLBuilder.toString();
                }

            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
                throw (e);
            }

            tokens = new StrTokenizer(map);

            URLCodec urlCodec = new URLCodec();

            String packageIdListItem = null;
            String metadata = null;
            String report = null;
            String data = "";
            String doiId = null;
            String entityNames = dpmClient.readDataEntityNames(scope, id, revision);
            String entitySizes = dpmClient.readDataEntitySizes(scope, id, revision);

            while (tokens.hasNext()) {
                resource = tokens.nextToken();

                if (resource.contains(metadataUri)) {

                    metadata = "<li><a class=\"searchsubcat\" href=\"./metadataviewer?packageid=" + packageId
                            + "\">Metadata</a></li>\n";

                } else if (resource.contains(reportUri)) {

                    report = "<li><a class=\"searchsubcat\" href=\"./reportviewer?packageid=" + packageId
                            + "\" target=\"_blank\">Report</a></li>\n";

                } else if (resource.contains(dataUri)) {
                    uriTokens = resource.split("/");
                    entityId = uriTokens[uriTokens.length - 1];
                    String entityName = null;
                    String entitySize = null;
                    String entitySizeStr = "";

                    entityName = findEntityName(entityNames, entityId);
                    entitySize = findEntitySize(entitySizes, entityId);

                    if (entitySize != null) {
                        entitySizeStr = String.format("&nbsp;&nbsp;<small><em>(%s bytes)</em></small>",
                                entitySize);
                    }

                    // Safe URL encoding of entity id
                    try {
                        entityId = urlCodec.encode(entityId);
                    } catch (EncoderException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }

                    /*
                     * Entity name will only be returned for authorized data
                     * entities, so if it's non-null then we know the user is authorized.
                     */
                    Boolean isAuthorized = false;

                    if (entityName != null) {
                        isAuthorized = true;
                    }

                    if (isAuthorized) {
                        data += "<li><a class=\"searchsubcat\" href=\"./dataviewer?packageid=" + packageId
                                + "&entityid=" + entityId + "\" target=\"_blank\">" + entityName + "</a>"
                                + entitySizeStr + "</li>\n";
                    } else {
                        entityName = "Data object";
                        String tooltip = null;
                        if (uid.equals("public")) {
                            tooltip = "You may need to log in before you can access this data object.";
                        } else {
                            tooltip = "You may not have permission to access this data object.";
                        }
                        data += String.format(
                                "<li>%s [<span name='%s' class='tooltip'><em>more info</em></span>]</li>\n",
                                entityName, tooltip);
                    }
                } else {

                    try {
                        doiId = dpmClient.readDataPackageDoi(scope, id, revision);
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }

                    pastaDataObjectIdentifier = dpmClient.getPastaPackageUri(scope, id, revision);

                    packageIdListItem = "<li>" + packageId + "&nbsp;&nbsp;" + savedDataHTML + "</li>\n";

                    if (predecessor != null) {
                        previous = "<li><a class=\"searchsubcat\" href=\"./mapbrowse?scope=" + scope
                                + "&identifier=" + identifier.toString() + "&revision=" + predecessor.toString()
                                + "\">previous revision</a></li>\n";
                    }

                    if (successor != null) {
                        next = "<li><a class=\"searchsubcat\" href=\"./mapbrowse?scope=" + scope
                                + "&identifier=" + identifier.toString() + "&revision=" + successor.toString()
                                + "\">next revision</a></li>\n";
                    }

                    if (size > 1) {
                        revisions = "<li><a class=\"searchsubcat\" href=\"./revisionbrowse?scope=" + scope
                                + "&identifier=" + identifier.toString() + "\">all revisions</a></li>\n";
                    }

                }

            }

            packageIdHTMLBuilder.append("<ul class=\"no-list-style\">\n");
            packageIdHTMLBuilder.append(packageIdListItem);
            packageIdHTMLBuilder.append(previous);
            packageIdHTMLBuilder.append(next);
            packageIdHTMLBuilder.append(revisions);
            packageIdHTMLBuilder.append("</ul>\n");
            packageIdHTML = packageIdHTMLBuilder.toString();

            resourcesHTMLBuilder.append("<ul class=\"no-list-style\">\n");
            resourcesHTMLBuilder.append(metadata);
            resourcesHTMLBuilder.append(report);
            resourcesHTMLBuilder.append("<li>Data <sup><strong>*</strong></sup>\n");
            resourcesHTMLBuilder.append("<ol>\n");
            resourcesHTMLBuilder.append(data);
            resourcesHTMLBuilder.append("</ol>\n");
            resourcesHTMLBuilder.append("</li>\n");

            resourcesHTMLBuilder.append("<li>&nbsp;</li>\n");

            resourcesHTMLBuilder.append("<li>\n");
            resourcesHTMLBuilder.append("<div>\n");
            resourcesHTMLBuilder.append(
                    "<form id=\"archive\" name=\"archiveform\" method=\"post\" action=\"./archiveDownload\"   target=\"_top\">\n");
            resourcesHTMLBuilder
                    .append("  <input type=\"hidden\" name=\"packageid\" value=\"" + packageId + "\" >\n");
            resourcesHTMLBuilder.append(
                    "  <input class=\"btn btn-info btn-default\" type=\"submit\" name=\"archive\" value=\"Download Zip Archive\" >\n");
            resourcesHTMLBuilder.append("</form>\n");
            resourcesHTMLBuilder.append("</div>\n");
            resourcesHTMLBuilder.append("</li>\n");

            resourcesHTMLBuilder.append("<li>\n");
            resourcesHTMLBuilder.append(
                    "<sup><strong>*</strong></sup> <em>By downloading any data you implicitly acknowledge the "
                            + "<a class=\"searchsubcat\" href=\"http://www.lternet.edu/data/netpolicy.html\">"
                            + "LTER Data Policy</a></em>");
            resourcesHTMLBuilder.append("</li>\n");

            resourcesHTMLBuilder.append("</ul>\n");
            resourcesHTML = resourcesHTMLBuilder.toString();

            if (doiId != null) {
                digitalObjectIdentifier = doiId;
            }

            citationHTMLBuilder.append("<a class=\"searchsubcat\" href=\"./dataPackageCitation?scope=" + scope
                    + "&" + "identifier=" + identifier.toString() + "&" + "revision=" + revision
                    + "\">How to cite this data package</a>\n");
            citationHTML = citationHTMLBuilder.toString();

            String dataSourcesStr = dpmClient.listDataSources(scope, id, revision);

            String source = null;
            String derived = null;

            if (dataSourcesStr != null && dataSourcesStr.length() > 0) {
                derived = packageId;
                String[] dataSources = dataSourcesStr.split("\n");
                if (dataSources.length > 0) {
                    String dataSource = dataSources[0];
                    if (dataSource != null && dataSource.length() > 0) {
                        provenanceHTMLBuilder
                                .append("This data package is derived from the following sources:<br/>");
                        provenanceHTMLBuilder.append("<ol>\n");
                        for (String uri : dataSources) {
                            String mapbrowseURL = mapbrowseURL(uri);
                            if (source == null) {
                                source = packageIdFromPastaId(uri);
                            }
                            String listItem = String.format("<li>%s</li>", mapbrowseURL);
                            provenanceHTMLBuilder.append(listItem);
                        }
                        provenanceHTMLBuilder.append("</ol>\n");
                        provenanceHTMLBuilder.append("<br/>");
                    }
                }
            }

            String dataDescendantsStr = dpmClient.listDataDescendants(scope, id, revision);

            if (dataDescendantsStr != null && dataDescendantsStr.length() > 0) {
                source = packageId;
                String[] dataDescendants = dataDescendantsStr.split("\n");
                if (dataDescendants.length > 0) {
                    String dataDescendant = dataDescendants[0];
                    if (dataDescendant != null && dataDescendant.length() > 0) {
                        provenanceHTMLBuilder.append(
                                "This data package is a source for the following derived data packages:<br/>");
                        provenanceHTMLBuilder.append("<ol>\n");
                        for (String uri : dataDescendants) {
                            String mapbrowseURL = mapbrowseURL(uri);
                            if (derived == null) {
                                derived = packageIdFromPastaId(uri);
                            }
                            String listItem = String.format("<li>%s</li>", mapbrowseURL);
                            provenanceHTMLBuilder.append(listItem);
                        }
                        provenanceHTMLBuilder.append("</ol>\n");
                        provenanceHTMLBuilder.append("<br/>");
                    }
                }
            }

            /*
             * Provenance graph
             */
            if ((source != null) && (derived != null)) {
                String graphString = String.format(
                        "View a <a class=\"searchsubcat\" href=\"./provenanceGraph?source=%s&derived=%s\">"
                                + "provenance graph</a> of this data package",
                        source, derived);
                provenanceHTMLBuilder.append(graphString);
                provenanceHTMLBuilder.append("<br/><br/>");
            }

            /*
             * Provenance metadata generator
             */
            provenanceHTMLBuilder
                    .append(String.format(
                            "Generate <a class=\"searchsubcat\" href=\"./provenanceGenerator?packageid=%s\">"
                                    + "provenance metadata</a> for use within your derived data package",
                            packageId));

            provenanceHTML = provenanceHTMLBuilder.toString();

            /*
             * Add code generation section only if this data package has at
             * least one entity that is a data table.
             */
            DataPackage dataPackage = emlObject.getDataPackage();
            boolean hasDataTableEntity = dataPackage.hasDataTableEntity();
            if (hasDataTableEntity) {
                ArrayList<String> programLinks = CodeGenerationServlet.getProgramLinks(packageId);
                codeGenerationHTMLBuilder.append("Analyze this data package using ");
                for (String programLink : programLinks) {
                    codeGenerationHTMLBuilder.append(String.format("%s, ", programLink));
                }
                codeGenerationHTML = codeGenerationHTMLBuilder.toString();
                codeGenerationHTML = codeGenerationHTML.substring(0, codeGenerationHTML.length() - 2); // trim the last
                // comma and
                // space
            }

        }

        else {
            String msg = "The 'scope', 'identifier', or 'revision' field of the packageId is empty.";
            throw new UserErrorException(msg);
        }
    } catch (Exception e) {
        handleDataPortalError(logger, e);
    }

    request.setAttribute("dataPackageTitleHTML", titleHTML);
    request.setAttribute("dataPackageCreatorsHTML", creatorsHTML);
    request.setAttribute("abstractHTML", abstractHTML);
    request.setAttribute("dataPackagePublicationDateHTML", publicationDateHTML);
    request.setAttribute("spatialCoverageHTML", spatialCoverageHTML);
    request.setAttribute("googleMapHTML", googleMapHTML);
    request.setAttribute("dataPackageIdHTML", packageIdHTML);
    request.setAttribute("dataPackageResourcesHTML", resourcesHTML);
    request.setAttribute("dataPackageCitationHTML", citationHTML);
    request.setAttribute("digitalObjectIdentifier", digitalObjectIdentifier);
    request.setAttribute("pastaDataObjectIdentifier", pastaDataObjectIdentifier);
    request.setAttribute("provenanceHTML", provenanceHTML);
    request.setAttribute("codeGenerationHTML", codeGenerationHTML);

    RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
    requestDispatcher.forward(request, response);
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.sp.sso.SPSingleLogout.java

private void processLogoutResponse(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context, LogoutResponse message)
        throws OAException, SAML2SecurityException {
    String sInResponseTo = message.getInResponseTo();
    if (sInResponseTo == null) {
        _logger.debug("Incoming SAML object is missing InResponseTo attribute");
        throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
    }/* w ww  . ja  v a2 s. c o  m*/

    //DD: Session ID is extracted from InResponseTo. If null, relaystate or target are used for Unsolicited Response.
    String sSessionID = null;
    String sRequestIDPrefix = null;
    if (sInResponseTo.length() <= SAML2AuthNConstants.REQUEST_ID_LENGTH) {
        StringBuffer sbWarn = new StringBuffer("Invalid InResponseTo ID supplied (");
        sbWarn.append(sInResponseTo);
        sbWarn.append(") is must have a length that is at least bigger then: ");
        sbWarn.append(SAML2AuthNConstants.REQUEST_ID_LENGTH);
        _logger.warn(sbWarn.toString());

        throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
    }

    sRequestIDPrefix = sInResponseTo.substring(0, SAML2AuthNConstants.REQUEST_ID_LENGTH);
    sSessionID = sInResponseTo.substring(SAML2AuthNConstants.REQUEST_ID_LENGTH);

    if (!SessionValidator.validateDefaultSessionId(sSessionID)) {
        StringBuffer sbError = new StringBuffer("Invalid '");
        sbError.append(ISession.ID_NAME);
        sbError.append("' in request: ");
        sbError.append(sSessionID);
        _logger.debug(sbError.toString());
        throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
    }

    ISession session = _sessionFactory.retrieve(sSessionID);

    if (session == null || session.isExpired()) {
        _logger.debug("Could not process SAML response; Session expired");
        throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
    }

    if (session.getAttributes().contains(SAML2AuthNConstants.class,
            SAML2AuthNConstants.AUTHNREQUEST_ID_PREFIX)) {
        String sSessionRequestIDPrefix = (String) session.getAttributes().get(SAML2AuthNConstants.class,
                SAML2AuthNConstants.AUTHNREQUEST_ID_PREFIX);

        if (sSessionRequestIDPrefix != null && sRequestIDPrefix != null
                && !sSessionRequestIDPrefix.equals(sRequestIDPrefix)) {
            StringBuffer sbError = new StringBuffer(
                    "Invalid InResponseTo session ID prefix in request: expected '");
            sbError.append(sSessionRequestIDPrefix);
            sbError.append("' but recieved: ");
            sbError.append(sRequestIDPrefix);
            _logger.debug(sbError.toString());
            throw new SAML2SecurityException(RequestorEvent.REQUEST_INVALID);
        }
    }

    //forward user to /sso to finish logout (in authn.saml2 where result will be checked)

    servletRequest.setAttribute(SAML2AuthNConstants.SESSION_ATTRIBUTE_NAME, context);
    servletRequest.setAttribute(ISession.ID_NAME, session);

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

    _logger.debug("Forwarding user to: " + sbForward.toString());

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

    try {
        oDispatcher.forward(servletRequest, servletResponse);
    } catch (Exception e) {
        _logger.fatal("Could not forward user", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.liferay.portlet.InvokerPortletImpl.java

protected void invoke(LiferayPortletRequest portletRequest, LiferayPortletResponse portletResponse,
        String lifecycle, List<? extends PortletFilter> filters) throws IOException, PortletException {

    FilterChain filterChain = new FilterChainImpl(_portlet, filters);

    if (_portletConfigImpl.isWARFile()) {
        String invokerPortletName = _portletConfigImpl.getInitParameter(INIT_INVOKER_PORTLET_NAME);

        if (invokerPortletName == null) {
            invokerPortletName = _portletConfigImpl.getPortletName();
        }/*w w w  .  j a v a 2s .  c  om*/

        String path = StringPool.SLASH + invokerPortletName + "/invoke";

        RequestDispatcher requestDispatcher = _portletContextImpl.getServletContext()
                .getRequestDispatcher(path);

        HttpServletRequest request = portletRequest.getHttpServletRequest();
        HttpServletResponse response = portletResponse.getHttpServletResponse();

        request.setAttribute(JavaConstants.JAVAX_PORTLET_PORTLET, _portlet);
        request.setAttribute(PortletRequest.LIFECYCLE_PHASE, lifecycle);
        request.setAttribute(PortletServlet.PORTLET_SERVLET_FILTER_CHAIN, filterChain);

        try {

            // Resource phase must be a forward because includes do not
            // allow you to specify the content type or headers

            if (lifecycle.equals(PortletRequest.RESOURCE_PHASE)) {
                requestDispatcher.forward(request, response);
            } else {
                requestDispatcher.include(request, response);
            }
        } catch (ServletException se) {
            Throwable cause = se.getRootCause();

            if (cause instanceof PortletException) {
                throw (PortletException) cause;
            }

            throw new PortletException(cause);
        }
    } else {
        PortletFilterUtil.doFilter(portletRequest, portletResponse, lifecycle, filterChain);
    }

    portletResponse.transferMarkupHeadElements();

    Map<String, String[]> properties = portletResponse.getProperties();

    if ((properties != null) && (properties.size() > 0)) {
        if (_expCache != null) {
            String[] expCache = properties.get(RenderResponse.EXPIRATION_CACHE);

            if ((expCache != null) && (expCache.length > 0) && (expCache[0] != null)) {

                _expCache = new Integer(GetterUtil.getInteger(expCache[0]));
            }
        }
    }
}

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

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) {
        return;/*from  www.j a va  2s  . c o m*/
    }

    VitroRequest vreq = new VitroRequest(request);
    String siteAdminUrl = vreq.getContextPath() + Controllers.SITE_ADMIN;

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

    epo.setBeanClass(Individual.class);
    epo.setImplementationClass(IndividualImpl.class);

    String action = null;
    if (epo.getAction() == null) {
        action = "insert";
        epo.setAction("insert");
    } else {
        action = epo.getAction();
    }

    LoginStatusBean loginBean = LoginStatusBean.getBean(request);
    WebappDaoFactory myWebappDaoFactory = getWebappDaoFactory(loginBean.getUserURI());

    IndividualDao ewDao = myWebappDaoFactory.getIndividualDao();
    epo.setDataAccessObject(ewDao);
    VClassDao vcDao = myWebappDaoFactory.getVClassDao();
    VClassGroupDao cgDao = myWebappDaoFactory.getVClassGroupDao();
    DataPropertyDao dpDao = myWebappDaoFactory.getDataPropertyDao();

    Individual individualForEditing = null;
    if (epo.getUseRecycledBean()) {
        individualForEditing = (Individual) epo.getNewBean();
    } else {
        String uri = vreq.getParameter("uri");
        if (uri != null) {
            try {
                individualForEditing = (Individual) ewDao.getIndividualByURI(uri);
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
            }
        } else {
            individualForEditing = new IndividualImpl();
            if (vreq.getParameter("VClassURI") != null) {
                individualForEditing.setVClassURI(vreq.getParameter("VClassURI"));
            }
        }

        epo.setOriginalBean(individualForEditing);

        //make a simple mask for the entity's id
        Object[] simpleMaskPair = new Object[2];
        simpleMaskPair[0] = "URI";
        simpleMaskPair[1] = individualForEditing.getURI();
        epo.getSimpleMask().add(simpleMaskPair);

    }

    //set any validators

    LinkedList lnList = new LinkedList();
    lnList.add(new RequiredFieldValidator());
    epo.getValidatorMap().put("Name", lnList);

    //make a postinsert pageforwarder that will send us to a new entity's fetch screen
    epo.setPostInsertPageForwarder(new EntityInsertPageForwarder());
    epo.setPostDeletePageForwarder(new UrlForwarder(siteAdminUrl));

    //set the getMethod so we can retrieve a new bean after we've inserted it
    try {
        Class[] args = new Class[1];
        args[0] = String.class;
        epo.setGetMethod(ewDao.getClass().getDeclaredMethod("getIndividualByURI", args));
    } catch (NoSuchMethodException e) {
        log.error("EntityRetryController could not find the entityByURI method in the dao");
    }

    epo.setIdFieldName("URI");
    epo.setIdFieldClass(String.class);

    HashMap hash = new HashMap();

    if (individualForEditing.getVClassURI() == null) {
        // we need to do a special thing here to make an option list with option groups for the classgroups.
        List classGroups = cgDao.getPublicGroupsWithVClasses(true, true, false); // order by displayRank, include uninstantiated classes, don't get the counts of individuals
        Iterator classGroupIt = classGroups.iterator();
        ListOrderedMap optGroupMap = new ListOrderedMap();
        while (classGroupIt.hasNext()) {
            VClassGroup group = (VClassGroup) classGroupIt.next();
            List classes = group.getVitroClassList();
            optGroupMap.put(group.getPublicName(), FormUtils.makeOptionListFromBeans(classes, "URI", "Name",
                    individualForEditing.getVClassURI(), null, false));
        }
        hash.put("VClassURI", optGroupMap);
    } else {
        VClass vClass = null;
        Option opt = null;
        try {
            vClass = vcDao.getVClassByURI(individualForEditing.getVClassURI());
        } catch (Exception e) {
        }
        if (vClass != null) {
            opt = new Option(vClass.getURI(), vClass.getName(), true);
        } else {
            opt = new Option(individualForEditing.getVClassURI(), individualForEditing.getVClassURI(), true);
        }
        List<Option> optList = new LinkedList<Option>();
        optList.add(opt);
        hash.put("VClassURI", optList);
    }

    hash.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getDisplayOptionsList(individualForEditing));
    hash.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getUpdateOptionsList(individualForEditing));
    hash.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getPublishOptionsList(individualForEditing));

    FormObject foo = new FormObject();
    foo.setOptionLists(hash);

    ListOrderedMap dpMap = new ListOrderedMap();

    //make dynamic datatype property fields
    List<VClass> vclasses = individualForEditing.getVClasses(true);
    if (vclasses == null) {
        vclasses = new ArrayList<VClass>();
        if (individualForEditing.getVClassURI() != null) {
            try {
                VClass cls = vreq.getUnfilteredWebappDaoFactory().getVClassDao()
                        .getVClassByURI(individualForEditing.getVClassURI());
                if (cls != null) {
                    vclasses.add(cls);
                }
            } catch (Exception e) {
            }
        }
    }
    List<DataProperty> allApplicableDataprops = new ArrayList<DataProperty>();
    for (VClass cls : vclasses) {
        List<DataProperty> dataprops = dpDao.getDataPropertiesForVClass(cls.getURI());
        for (DataProperty dp : dataprops) {
            boolean notDuplicate = true;
            for (DataProperty existingDp : allApplicableDataprops) {
                if (existingDp.getURI().equals(dp.getURI())) {
                    notDuplicate = false;
                    break;
                }
            }
            if (notDuplicate) {
                allApplicableDataprops.add(dp);
            }
        }
    }
    Collections.sort(allApplicableDataprops);

    if (allApplicableDataprops != null) {
        Iterator<DataProperty> datapropsIt = allApplicableDataprops.iterator();

        while (datapropsIt.hasNext()) {
            DataProperty d = datapropsIt.next();
            if (!dpMap.containsKey(d.getURI())) {
                dpMap.put(d.getURI(), d);
            }

        }

        if (individualForEditing.getDataPropertyList() != null) {
            Iterator<DataProperty> existingDps = individualForEditing.getDataPropertyList().iterator();
            while (existingDps.hasNext()) {
                DataProperty existingDp = existingDps.next();
                // Since the edit form begins with a "name" field, which gets saved as the rdfs:label,
                // do not want to include the label as well. 
                if (!existingDp.getPublicName().equals("label")) {
                    dpMap.put(existingDp.getURI(), existingDp);
                }
            }
        }

        List<DynamicField> dynamicFields = new ArrayList();
        Iterator<String> dpHashIt = dpMap.orderedMapIterator();
        while (dpHashIt.hasNext()) {
            String uri = dpHashIt.next();
            DataProperty dp = (DataProperty) dpMap.get(uri);
            DynamicField dynamo = new DynamicField();
            dynamo.setName(dp.getPublicName());
            dynamo.setTable("DataPropertyStatement");
            dynamo.setVisible(dp.getDisplayLimit());
            dynamo.setDeleteable(true);
            DynamicFieldRow rowTemplate = new DynamicFieldRow();
            Map parameterMap = new HashMap();
            parameterMap.put("DatatypePropertyURI", dp.getURI());
            rowTemplate.setParameterMap(parameterMap);
            dynamo.setRowTemplate(rowTemplate);
            try {
                Iterator<DataPropertyStatement> existingValues = dp.getDataPropertyStatements().iterator();
                while (existingValues.hasNext()) {
                    DataPropertyStatement existingValue = existingValues.next();
                    DynamicFieldRow row = new DynamicFieldRow();
                    //TODO: UGH
                    //row.setId(existingValue.getId());
                    row.setParameterMap(parameterMap);
                    row.setValue(existingValue.getData());
                    if (dynamo.getRowList() == null)
                        dynamo.setRowList(new ArrayList());
                    dynamo.getRowList().add(row);
                }
            } catch (NullPointerException npe) {
                //whatever
            }
            if (dynamo.getRowList() == null)
                dynamo.setRowList(new ArrayList());
            dynamo.getRowList().add(rowTemplate);
            dynamicFields.add(dynamo);
        }
        foo.setDynamicFields(dynamicFields);
    }

    foo.setErrorMap(epo.getErrMsgMap());

    epo.setFormObject(foo);

    // DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    DateFormat minutesOnlyDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    DateFormat dateOnlyFormat = new SimpleDateFormat("yyyy-MM-dd");
    FormUtils.populateFormFromBean(individualForEditing, action, epo, foo, epo.getBadValueMap());

    List cList = new ArrayList();
    cList.add(new IndividualDataPropertyStatementProcessor());
    //cList.add(new SearchReindexer()); // handled for now by SearchReindexingListener on model
    epo.setChangeListenerList(cList);

    epo.getAdditionalDaoMap().put("DataPropertyStatement", myWebappDaoFactory.getDataPropertyStatementDao()); // EntityDatapropProcessor will look for this
    epo.getAdditionalDaoMap().put("DataProperty", myWebappDaoFactory.getDataPropertyDao()); // EntityDatapropProcessor will look for this

    ApplicationBean appBean = vreq.getAppBean();

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("formJsp", "/templates/edit/specific/entity_retry.jsp");
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("title", "Individual Editing Form");
    request.setAttribute("css",
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + appBean.getThemeDir() + "css/edit.css\"/>");
    request.setAttribute("scripts", "/js/edit/entityRetry.js");
    // NC Commenting this out for now. Going to pass on DWR for moniker and use jQuery instead
    // request.setAttribute("bodyAttr"," onLoad=\"monikerInit()\"");
    request.setAttribute("_action", action);
    request.setAttribute("unqualifiedClassName", "Individual");
    setRequestAttributes(request, epo);
    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("EntityRetryController could not forward to view.");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
    }

}

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

private void showSelectPage(HttpServletRequest oRequest, HttpServletResponse oResponse, ISession oSession)
        throws SSOException {
    try {//from   w  ww .  j av  a 2 s. com
        //Set optional warning
        if (oSession.getState() == SessionState.AUTHN_NOT_SUPPORTED) {
            oRequest.setAttribute(UserException.USEREVENT_NAME, UserEvent.AUTHN_METHOD_NOT_SUPPORTED);
        }

        //Save session
        oSession.setState(SessionState.AUTHN_SELECTION_IN_PROGRESS);
        oSession.persist();

        //Add requestor object as attribute
        oRequest.setAttribute(IRequestor.REQUESTOR_ATTRIBUTE_NAME, _ssoService.getRequestor(oSession));

        //Set authenticationProfiles map as attribute
        oRequest.setAttribute(AUTHN_PROFILES_NAME, oSession.getAuthNProfiles());
        //Set session ID and locale as attribute              
        oRequest.setAttribute(ISession.ID_NAME, oSession.getId());
        oRequest.setAttribute(ISession.LOCALE_NAME, oSession.getLocale());
        //Set server info as attribute
        oRequest.setAttribute(Server.SERVER_ATTRIBUTE_NAME, Engine.getInstance().getServer());
        //Forward to page                
        RequestDispatcher oDispatcher = oRequest.getRequestDispatcher(_sSelectionPath);
        if (oDispatcher == null) {
            _systemLogger.fatal(new SystemLogItem(oSession.getId(), SystemErrors.ERROR_INTERNAL,
                    "Forward request not supported"));
            throw new SSOException(SystemErrors.ERROR_INTERNAL);
        }

        //Redirect user
        oDispatcher.forward(oRequest, oResponse);
    } catch (SSOException e) {
        throw e;
    } catch (OAException e) {
        //Wrap exception
        throw new SSOException(e.getCode(), e);
    } catch (Exception e) {
        _systemLogger.fatal("Could not forward request with session: " + oSession.getId(), e);
        throw new SSOException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.sp.sso.SPSingleLogout.java

private void processLogoutRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context, String sBinding,
        String sReason) throws OAException, SAML2SecurityException, StatusException {
    //Validate requestor and signature
    SAML2IDP saml2IDP = validateRequestMessage(context, IDPSSODescriptor.DEFAULT_ELEMENT_NAME);

    //Process request
    ITGT tgt = _protocol.processRequest(context);

    String sInReponseTo = context.getInboundSAMLMessageId();

    boolean bIsPartiallyLogout = false;
    if (sReason != null) {
        if (_htLogoutReasonActions.containsKey(sReason)) {//The reason logout action can be optionally configured
            bIsPartiallyLogout = _htLogoutReasonActions.get(sReason).booleanValue();
        } else {//from   ww w  .j  av  a  2  s . c  o m
            if (sReason.equals(LogoutResponse.GLOBAL_TIMEOUT_URI)) {//More info about this reason: saml-core-2.0-o.s.pdf r2662
                bIsPartiallyLogout = true;
            } else if (sReason.equals(LogoutResponse.SP_TIMEOUT_URI)) {//More info about this reason: saml-core-2.0-o.s.pdf r2665
                                                                       //it is agreed with the requestor that we must do a full logout
                bIsPartiallyLogout = false;
            } else if (sReason.equals(LogoutResponse.USER_LOGOUT_URI)) {//More info about this reason: saml-core-2.0-o.s.pdf r2580
                bIsPartiallyLogout = false;
            } else if (sReason.equals(LogoutResponse.ADMIN_LOGOUT_URI)) {//More info about this reason: saml-core-2.0-o.s.pdf r2583
                bIsPartiallyLogout = false;
            }
        }
    }

    if (bIsPartiallyLogout || sBinding.equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
        //Process response
        _protocol.processResponse(tgt, sInReponseTo, context, bIsPartiallyLogout);

        context.setOutboundMessageIssuer(saml2IDP.getID());
        context.setMetadataProvider(saml2IDP.getMetadataProvider());

        //Send response      
        sendResponse(context, servletRequest, servletResponse, sBinding);

        _eventLogger.info(new UserEventLogItem(null, tgt.getId(), null, UserEvent.USER_LOGGED_OUT,
                tgt.getUser().getID(), servletRequest.getRemoteAddr(), saml2IDP.getID(), this,
                context.getOutboundSAMLMessageId()));
    } else {//process a-synchronous logout

        //DD Creating a session with an OpenASelect IdP instead of an OpenASelect Requestor has the consequence that any SP Aliasses for a requestor with the same ID will be removed 
        ISession session = _sessionFactory.createSession(saml2IDP.getID());

        ISessionAttributes sessionAttributes = session.getAttributes();
        sessionAttributes.put(this.getClass(), SESSION_REQUEST_ID, sInReponseTo);
        sessionAttributes.put(this.getClass(), SESSION_REQUEST_PROTOCOLBINDING, sBinding);

        String sRelayState = context.getRelayState();
        if (sRelayState != null)
            sessionAttributes.put(this.getClass(), SESSION_REQUEST_RELAYSTATE, sRelayState);

        session.persist();//this generates the session ID

        StringBuffer sbProfileURL = new StringBuffer();
        sbProfileURL.append(_sProfileURL);
        sbProfileURL.append("?");
        sbProfileURL.append(ISession.ID_NAME);
        sbProfileURL.append("=");
        sbProfileURL.append(session.getId());
        session.setProfileURL(sbProfileURL.toString());

        servletRequest.setAttribute(ISession.ID_NAME, session);

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

        _logger.debug("Forwarding user to: " + sbForward.toString());

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

        _eventLogger.info(new UserEventLogItem(session, servletRequest.getRemoteAddr(),
                UserEvent.USER_LOGOUT_IN_PROGRESS, this, null));
        try {
            oDispatcher.forward(servletRequest, servletResponse);
        } catch (Exception e) {
            _logger.fatal("Could not forward user", e);
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
    }
}

From source file:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");

    // check connection details
    if (strabonWrapper.getStrabon() == null) {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/connection.jsp");

        // pass the current details of the connection
        request.setAttribute("username", strabonWrapper.getUsername());
        request.setAttribute("password", strabonWrapper.getPassword());
        request.setAttribute("dbname", strabonWrapper.getDatabaseName());
        request.setAttribute("hostname", strabonWrapper.getHostName());
        request.setAttribute("port", strabonWrapper.getPort());
        request.setAttribute("dbengine", strabonWrapper.getDBEngine());

        // pass the other parameters as well
        request.setAttribute("query", request.getParameter("query"));
        if (request.getParameter("format").equalsIgnoreCase("PIECHART")
                || request.getParameter("format").equalsIgnoreCase("AREACHART")
                || request.getParameter("format").equalsIgnoreCase("COLUMNCHART")) {
            request.setAttribute("format", "CHART");
        } else {/*from  ww w.ja v a  2 s.c o  m*/
            request.setAttribute("format", request.getParameter("format"));
        }
        request.setAttribute("handle", request.getParameter("handle"));

        // forward the request
        dispatcher.forward(request, response);

    } else {

        if (Common.VIEW_TYPE.equals(request.getParameter(Common.VIEW))) {
            // HTML visual interface
            processVIEWRequest(request, response);

        } else {// invoked as a service
            processRequest(request, response);
        }
    }
}

From source file:org.overlord.sramp.server.mvn.services.MavenRepositoryService.java

private void listItemsResponse(HttpServletRequest req, HttpServletResponse resp, String url)
        throws ServletException, IOException {
    if (!url.endsWith("/")) { //$NON-NLS-1$
        url = url + "/"; //$NON-NLS-1$
    }/*from   w ww.j  av a2  s.co m*/
    try {
        // Gets all the items from the maven url
        Set<String> items = getItems(url);

        // If there are items or the request is the root maven folder
        if ((items != null && items.size() > 0) || (url.equals("/") || url.equals(""))) { //$NON-NLS-1$ //$NON-NLS-2$
            // Dispatch the request to the JSP that would display the items
            RequestDispatcher dispatcher = req.getRequestDispatcher(JSP_LOCATION_LIST_DIR);
            if (StringUtils.isNotBlank(url) && !url.equals("/")) { //$NON-NLS-1$
                String[] urlTokens = url.split("/"); //$NON-NLS-1$
                String parentPath = ""; //$NON-NLS-1$
                if (urlTokens.length > 1) {
                    for (int i = 0; i < urlTokens.length - 1; i++) {
                        parentPath += urlTokens[i] + "/"; //$NON-NLS-1$
                    }
                }
                parentPath = "/" + parentPath; //$NON-NLS-1$
                req.setAttribute("parentPath", parentPath); //$NON-NLS-1$
            } else {
                url = ""; //$NON-NLS-1$
            }
            req.setAttribute("relativePath", url); //$NON-NLS-1$
            req.setAttribute("items", items); //$NON-NLS-1$
            dispatcher.forward(req, resp);
        } else {
            resp.setStatus(HttpStatus.SC_NOT_FOUND);
        }
    } catch (MavenRepositoryException e) {
        resp.sendError(HttpStatus.SC_NOT_FOUND, e.getMessage());
    }
}

From source file:com.controller.PolicyController.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("PolicyController:: doPost invoked");

    if (request.getSession(false).getAttribute("userid") == null) {

        response.sendRedirect(request.getContextPath() + "/LoginPage.jsp");

    }//from   ww  w .  j av a  2  s. c om

    Service s = new Service();

    // String action = request.getParameter("action");
    // System.out.println("User action received by controller: " + action);

    // /////////////////////// Health Policy Registration ///////////////

    HttpSession session = request.getSession(true);
    String action = (String) session.getAttribute("healthAction");

    if ("registerHealthPolicy".equals(action)) {

        String errorMsg = null;
        if (request.getParameter("id").equals(null) || request.getParameter("id").equals("")) {
            errorMsg = "CustomerId cannot be null or empty";
        }
        if (request.getParameter("pid").equals(null) || request.getParameter("pid").equals("")) {
            errorMsg = "PolicyId cannot be null or empty";
        }
        if (request.getParameter("tenure").equals(null) || request.getParameter("tenure").equals("")) {
            errorMsg = "Tenure cannot be null or empty";
        }
        if (request.getParameter("cDate").equals(null) || request.getParameter("cDate").equals("")) {
            errorMsg = "Commencement Date cannot be null or empty";
        }
        if (request.getParameter("eDate").equals(null) || request.getParameter("eDate").equals("")) {
            errorMsg = "End Date cannot be null or empty";
        }
        if (request.getParameter("pMode").equals(null) || request.getParameter("pMode").equals("")) {
            errorMsg = "Payment Mode cannot be null or empty";
        }
        if (request.getParameter("pFrequency").equals(null) || request.getParameter("pFrequency").equals("")) {
            errorMsg = "Payment Frequency cannot be null or empty";
        }
        if (request.getParameter("pAmount").equals(null) || request.getParameter("pAmount").equals("")) {
            errorMsg = "Payment Amount cannot be null or empty";
        }
        if (errorMsg != null) {
            RequestDispatcher rd = request.getRequestDispatcher(
                    "/Insurance Policy Registration/HealthInsuranceScheme/HealthInsuranceRegistration.jsp");
            request.setAttribute("msg", "This field cannot be null or empty");
            rd.forward(request, response);

        } else {

            HttpSession officerSession = request.getSession(true);
            String officer = (String) officerSession.getAttribute("userid");
            System.out.println("officer:" + officer);
            if (officer.substring(0, 2).equals("IO")) {

                int custId = Integer.parseInt(request.getParameter("id"));
                boolean checkCustId = false;
                boolean checkPolicyID = false;

                ArrayList<Customer> customers = s.allCustomer();

                for (Customer customer : customers) {

                    if (customer.getCustomerId() == custId) {
                        checkCustId = true;
                        System.out.println("Show" + custId);
                    }
                }
                if (checkCustId) {
                    String policyID = request.getParameter("pid");

                    ArrayList<HealthPolicy> policies = s.viewPolicy();
                    for (HealthPolicy hp : policies) {

                        if (hp.getPolicyId().equals(policyID)) {

                            checkPolicyID = true;
                            System.out.println("Show" + policyID);
                        }
                    }
                    if (checkPolicyID) {
                        String dateInString = request.getParameter("cDate");
                        System.out.println(dateInString);

                        SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");

                        HealthPolicy hp = new HealthPolicy();

                        hp.setCustomerId(Integer.parseInt(request.getParameter("id")));
                        hp.setPolicyId(request.getParameter("pid"));
                        int tenure = Integer.parseInt(request.getParameter("tenure"));
                        hp.setPolicytenure(tenure);
                        hp.setPolicyCommDate(request.getParameter("cDate"));
                        String date = request.getParameter("cDate");

                        String[] parts = date.split("/");
                        parts[2] = Integer.toString(tenure + Integer.parseInt(parts[2]));

                        date = parts[0] + "/" + parts[1] + "/" + parts[2];
                        Date dateInDateFormat = null;

                        try {
                            dateInDateFormat = sdf.parse(date);
                            System.out.println(dateInDateFormat);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        hp.setPolicyEndDate(request.getParameter("eDate"));
                        if (request.getParameter("eDate").equals(date)) {
                            hp.setPaymentMode(request.getParameter("pMode"));

                            hp.setPaymentFreq(request.getParameter("pFrequency"));
                            hp.setPremiumAmount(Double.parseDouble(request.getParameter("pAmount")));

                            String polRefNum = s.registerHealthPolicy(hp);

                            request.setAttribute("polRefNum", polRefNum);
                            System.out.println("hello" + polRefNum);
                            if (polRefNum != null) {
                                RequestDispatcher rd = request.getRequestDispatcher(
                                        "/Insurance Policy Registration/HealthInsuranceScheme/createHealthResult.jsp");
                                rd.forward(request, response);
                            } else {
                                RequestDispatcher rd = request.getRequestDispatcher(
                                        "/Insurance Policy Registration/HealthInsuranceScheme/HealthInsuranceRegistration.jsp");
                                request.setAttribute("msg",
                                        "This policy already exists for this customer or this policy Id is invalid for health ");
                                rd.forward(request, response);

                            }

                        } else {
                            RequestDispatcher rd = request.getRequestDispatcher(
                                    "/Insurance Policy Registration/HealthInsuranceScheme/HealthInsuranceRegistration.jsp");
                            request.setAttribute("msg", "EndDate is not valid.Please enter a valid End Date");
                            rd.forward(request, response);
                        }
                    } else {

                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/HealthInsuranceScheme/HealthInsuranceRegistration.jsp");
                        request.setAttribute("msg", "Policy Id does not exist.Please enter a valid Policy Id");
                        rd.forward(request, response);
                    }
                } else {
                    RequestDispatcher rd = request.getRequestDispatcher(
                            "/Insurance Policy Registration/HealthInsuranceScheme/HealthInsuranceRegistration.jsp");
                    request.setAttribute("msg", "Customer Id does not exist");
                    rd.forward(request, response);

                }
            } else {
                RequestDispatcher rd = request.getRequestDispatcher(
                        "/Insurance Policy Registration/HealthInsuranceScheme/HealthInsuranceRegistration.jsp");
                request.setAttribute("msg", "No rights to register");
                rd.forward(request, response);
            }
        }
    }

    // ///////////////////////// Vehicle Policy Registration /////////////

    else if ("registerVehiclePolicy".equals(action)) {
        String errorMsg = null;
        if (request.getParameter("id").equals(null) || request.getParameter("id").equals("")) {
            errorMsg = "CustomerId cannot be null or empty";
        }
        if (request.getParameter("pid").equals(null) || request.getParameter("pid").equals("")) {
            errorMsg = "PolicyId cannot be null or empty";
        }

        if (request.getParameter("cDate").equals(null) || request.getParameter("cDate").equals("")) {
            errorMsg = "Commencement Date cannot be null or empty";
        }
        if (request.getParameter("vNum").equals(null) || request.getParameter("vNum").equals("")) {
            errorMsg = "Vehicle Number cannot be null or empty";
        }
        if (request.getParameter("lNum").equals(null) || request.getParameter("lNum").equals("")) {
            errorMsg = "license Number cannot be null or empty";
        }

        if (request.getParameter("vType").equals(null) || request.getParameter("vType").equals("")) {
            errorMsg = "Vehicle type cannot be null or empty";
        }

        if (request.getParameter("pMode").equals(null) || request.getParameter("pMode").equals("")) {
            errorMsg = "Payment Mode cannot be null or empty";
        }
        if (request.getParameter("pFrequency").equals(null) || request.getParameter("pFrequency").equals("")) {
            errorMsg = "Payment Frequency cannot be null or empty";
        }
        if (request.getParameter("pAmount").equals(null) || request.getParameter("pAmount").equals("")) {
            errorMsg = "Payment Amount cannot be null or empty";
        }
        if (errorMsg != null) {
            RequestDispatcher rd = request.getRequestDispatcher(
                    "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
            request.setAttribute("msg", "This field cannot be null or empty");
            rd.forward(request, response);

        } else {
            HttpSession officerSession = request.getSession(true);
            String officer = (String) officerSession.getAttribute("userid");
            System.out.println("officer:" + officer);
            if (officer.substring(0, 2).equals("FO")) {

                int custId = Integer.parseInt(request.getParameter("id"));
                boolean checkCustId = false;
                boolean checkPolicyID = false;

                ArrayList<Customer> customers = s.allCustomer();

                for (Customer customer : customers) {

                    if (customer.getCustomerId() == custId) {
                        checkCustId = true;
                        System.out.println("Show" + custId);
                    }
                }
                if (checkCustId) {
                    String policyID = request.getParameter("pid");

                    ArrayList<HealthPolicy> policies = s.viewPolicy();
                    for (HealthPolicy hp : policies) {

                        if (hp.getPolicyId().equals(policyID)) {

                            checkPolicyID = true;
                            System.out.println("Show" + policyID);
                        }
                    }
                    if (checkPolicyID) {

                        String dateInString = request.getParameter("cDate");
                        System.out.println(dateInString);

                        SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");

                        VehiclePolicy vp = new VehiclePolicy();

                        vp.setCustomerId(Integer.parseInt(request.getParameter("id")));
                        vp.setPolicyId(request.getParameter("pid"));
                        vp.setPolicyCommDate(request.getParameter("cDate"));

                        String date = request.getParameter("cDate");

                        String[] parts = date.split("/");
                        parts[2] = Integer.toString(1 + Integer.parseInt(parts[2]));

                        date = parts[0] + "/" + parts[1] + "/" + parts[2];
                        Date dateInDateFormat = null;
                        vp.setPolicyEndDate(date);
                        try {
                            dateInDateFormat = sdf.parse(date);
                            System.out.println(dateInDateFormat);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        vp.setVehicleNum(request.getParameter("vNum"));
                        System.out.println(request.getParameter("lNum"));
                        vp.setLicenseNum(request.getParameter("lNum"));
                        vp.setVehicleType(request.getParameter("vType"));

                        vp.setPaymentMode(request.getParameter("pMode"));
                        vp.setPaymentFreq(request.getParameter("pFrequency"));
                        vp.setPremiumAmount(Double.parseDouble(request.getParameter("pAmount")));

                        String polRefNum = s.registerVehiclePolicy(vp);

                        request.setAttribute("polRefNum", polRefNum);
                        request.setAttribute("endDate", date);

                        System.out.println("hello" + polRefNum);

                        if (polRefNum != null) {
                            RequestDispatcher rd = request.getRequestDispatcher(
                                    "/Insurance Policy Registration/VehicleInsuranceScheme/createVehicleResult.jsp");
                            rd.forward(request, response);
                        } else {
                            RequestDispatcher rd = request.getRequestDispatcher(
                                    "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
                            request.setAttribute("msg",
                                    "This policy already exists for this customer or this policy Id is invalid for vehicle ");
                            rd.forward(request, response);

                        }
                    } else {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
                        request.setAttribute("msg", "Policy Id does not exist.Please enter a valid Policy Id");
                        rd.forward(request, response);
                    }
                } else {
                    RequestDispatcher rd = request.getRequestDispatcher(
                            "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
                    request.setAttribute("msg", "Customer Id does not exist");
                    rd.forward(request, response);

                }
            } else {
                RequestDispatcher rd = request.getRequestDispatcher(
                        "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
                request.setAttribute("msg", "No rights to register");
                rd.forward(request, response);
            }
        }
    }

    // ///////////////////////// Modify Health Policy /////////////

    else if ("modifyHealthPolicy".equals(action)) {
        String errorMsg = null;
        if (request.getParameter("ID").equals(null) || request.getParameter("ID").equals("")) {
            errorMsg = "Policy Reference number cannot be null or empty";
        }

        if (request.getParameter("pMode").equals(null) || request.getParameter("pMode").equals("")) {
            errorMsg = "Payment Mode cannot be null or empty";
        }
        if (request.getParameter("pFrequency").equals(null) || request.getParameter("pFrequency").equals("")) {
            errorMsg = "Payment Frequency cannot be null or empty";
        }

        if (errorMsg != null) {
            RequestDispatcher rd = request.getRequestDispatcher(
                    "/Insurance Policy Registration/HealthInsuranceScheme/HealthModifyPayment.jsp");
            request.setAttribute("msg", "This field cannot be null or empty");
            rd.forward(request, response);

        } else {
            boolean checkPolicyNum = false;

            HttpSession officerSession = request.getSession(true);
            String officer = (String) officerSession.getAttribute("userid");
            System.out.println(" The officer:" + officer);
            if (officer.substring(0, 2).equals("IO")) {
                String policyRefNum = request.getParameter("ID");

                System.out.println("In Modify Controller" + policyRefNum);
                ArrayList<HealthPolicy> policies = s.viewCustomerPolicy();
                for (HealthPolicy hp : policies) {

                    if (hp.getPolicyRefNum().equals(policyRefNum)) {

                        checkPolicyNum = true;
                        System.out.println("Show" + policyRefNum);
                    }
                }
                if (checkPolicyNum) {

                    HealthPolicy hp = new HealthPolicy();

                    hp.setPolicyRefNum(request.getParameter("ID"));

                    hp.setPaymentMode(request.getParameter("pMode"));
                    hp.setPaymentFreq(request.getParameter("pFrequency"));

                    boolean b = s.modifyHealthPolicy(hp);
                    System.out.println("show" + b);
                    if (b == true) {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/HealthInsuranceScheme/ModifyHealthResult.jsp");
                        rd.forward(request, response);
                    } else {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/HealthInsuranceScheme/HealthModifyPayment.jsp");
                        request.setAttribute("msg", "No Authority!!! You cannot modify this policy ");
                        rd.forward(request, response);
                    }

                } else {
                    RequestDispatcher rd = request.getRequestDispatcher(
                            "/Insurance Policy Registration/HealthInsuranceScheme/HealthModifyPayment.jsp");
                    request.setAttribute("msg", "Policy Reference Number does not exist");
                    rd.forward(request, response);

                }
            } else {
                RequestDispatcher rd = request.getRequestDispatcher(
                        "/Insurance Policy Registration/HealthInsuranceScheme/HealthModifyPayment.jsp");
                request.setAttribute("msg", "No rights to register");
                rd.forward(request, response);
            }
        }
    }

    // ///////////////////////// Modify Vehicle Policy /////////////

    else if ("modifyVehiclePolicy".equals(action)) {
        String errorMsg = null;
        if (request.getParameter("ID").equals(null) || request.getParameter("ID").equals("")) {
            errorMsg = "Policy Reference Number cannot be null or empty";
        }

        if (request.getParameter("pMode").equals(null) || request.getParameter("pMode").equals("")) {
            errorMsg = "Payment Mode cannot be null or empty";
        }
        if (request.getParameter("pFrequency").equals(null) || request.getParameter("pFrequency").equals("")) {
            errorMsg = "Payment Frequency cannot be null or empty";
        }

        if (errorMsg != null) {
            RequestDispatcher rd = request.getRequestDispatcher(
                    "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
            request.setAttribute("msg", "This field cannot be null or empty");
            rd.forward(request, response);

        } else {
            boolean checkPolicyNum = false;

            HttpSession officerSession = request.getSession(true);
            String officer = (String) officerSession.getAttribute("userid");
            System.out.println(" The officer:" + officer);
            if (officer.substring(0, 2).equals("FO")) {
                String policyRefNum = request.getParameter("ID");

                System.out.println("In Modify Controller" + policyRefNum);
                ArrayList<HealthPolicy> policies = s.viewCustomerPolicy();
                for (HealthPolicy hp : policies) {

                    if (hp.getPolicyRefNum().equals(policyRefNum)) {

                        checkPolicyNum = true;
                        System.out.println("Show" + policyRefNum);
                    }
                }
                if (checkPolicyNum) {

                    VehiclePolicy vp = new VehiclePolicy();

                    vp.setPolicyRefNum(request.getParameter("ID"));

                    vp.setPaymentMode(request.getParameter("pMode"));
                    vp.setPaymentFreq(request.getParameter("pFrequency"));

                    boolean b = s.modifyVehiclePolicy(vp);
                    System.out.println("show" + b);
                    if (b == true) {

                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/VehicleInsuranceScheme/ModifyVehicleResult.jsp");
                        rd.forward(request, response);
                    } else {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleModifyPayment.jsp");
                        request.setAttribute("msg", "No Authority!!! You cannot modify this policy");
                        rd.forward(request, response);
                    }

                } else {
                    RequestDispatcher rd = request.getRequestDispatcher(
                            "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleModifyPayment.jsp");
                    request.setAttribute("msg", "Policy Reference Number does not exist");
                    rd.forward(request, response);

                }
            } else {
                RequestDispatcher rd = request.getRequestDispatcher(
                        "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
                request.setAttribute("msg", "No rights to register");
                rd.forward(request, response);
            }
        }

    }
    // ///////////////////////// View Health Policy /////////////

    else if ("viewHealthPolicy".equals(action)) {
        String errorMsg = null;
        if (request.getParameter("id").equals(null) || request.getParameter("id").equals("")) {
            errorMsg = "CustomerId cannot be null or empty";
        }
        if (errorMsg != null) {
            RequestDispatcher rd = request.getRequestDispatcher(
                    "/Insurance Policy Registration/HealthInsuranceScheme/HealthInsuranceRegistration.jsp");
            request.setAttribute("msg", "This field cannot be null or empty");
            rd.forward(request, response);

        } else {
            HttpSession officerSession = request.getSession(true);
            String officer = (String) officerSession.getAttribute("userid");
            System.out.println("officer:" + officer);
            if (officer.substring(0, 2).equals("IO")) {

                int custId = Integer.parseInt(request.getParameter("id"));
                boolean checkCustId = false;

                ArrayList<Customer> customers = s.allCustomer();

                for (Customer customer : customers) {

                    if (customer.getCustomerId() == custId) {
                        checkCustId = true;
                        System.out.println("Show" + custId + checkCustId);
                    }
                }
                if (checkCustId) {

                    int customerId = Integer.parseInt(request.getParameter("id"));
                    // Call service layer to do customer search

                    Service service = new Service();

                    ArrayList<HealthPolicy> viewHealthPolicyList = service.viewHealthPolicy(customerId);

                    // Share the matched customers details with view
                    System.out.println(viewHealthPolicyList.size());
                    request.setAttribute("viewHealthPolicyList", viewHealthPolicyList);
                    if (viewHealthPolicyList.size() != 0) {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/HealthInsuranceScheme/viewHealthPolicyResult.jsp");
                        rd.forward(request, response);
                    } else {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/HealthInsuranceScheme/HealthViewDetails.jsp");
                        request.setAttribute("msg", "No Policy in the Database");
                        rd.forward(request, response);

                    }

                } else {
                    RequestDispatcher rd = request.getRequestDispatcher(
                            "/Insurance Policy Registration/HealthInsuranceScheme/HealthViewDetails.jsp");
                    request.setAttribute("msg", "Customer Id does not exist");
                    rd.forward(request, response);

                }
            } else {
                RequestDispatcher rd = request.getRequestDispatcher(
                        "/Insurance Policy Registration/HealthInsuranceScheme/HealthViewDetails.jsp");
                request.setAttribute("msg", "No rights to Field Officer");
                rd.forward(request, response);
            }
        }
    }
    // ///////////////////////// View Vehicle Policy /////////////
    else if ("viewVehiclePolicy".equals(action)) {
        String errorMsg = null;
        if (request.getParameter("ID").equals(null) || request.getParameter("ID").equals("")) {
            errorMsg = "CustomerId cannot be null or empty";
        }
        if (errorMsg != null) {
            RequestDispatcher rd = request.getRequestDispatcher(
                    "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
            request.setAttribute("msg", "This field cannot be null or empty");
            rd.forward(request, response);

        } else {
            HttpSession officerSession = request.getSession(true);
            String officer = (String) officerSession.getAttribute("userid");
            System.out.println("officer:" + officer);
            if (officer.substring(0, 2).equals("FO")) {

                int custId = Integer.parseInt(request.getParameter("ID"));
                boolean checkCustId = false;

                ArrayList<Customer> customers = s.allCustomer();

                for (Customer customer : customers) {

                    if (customer.getCustomerId() == custId) {
                        checkCustId = true;
                        System.out.println("Show" + custId + checkCustId);
                    }
                }
                if (checkCustId) {

                    int customerId = Integer.parseInt(request.getParameter("ID"));

                    // Call service layer to do customer search

                    Service service = new Service();

                    ArrayList<VehiclePolicy> viewVehiclePolicyList = service.viewVehiclePolicy(customerId);

                    // Share the matched customers details with view
                    System.out.println(viewVehiclePolicyList.size());
                    request.setAttribute("viewVehiclePolicyList", viewVehiclePolicyList);
                    if (viewVehiclePolicyList.size() != 0) {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/VehicleInsuranceScheme/viewVehiclePolicyResult.jsp");
                        rd.forward(request, response);

                    } else {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleViewDetails.jsp");
                        request.setAttribute("msg", "Customer Id does not exist");
                        rd.forward(request, response);

                    }
                } else {
                    RequestDispatcher rd = request.getRequestDispatcher(
                            "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleViewDetails.jsp");
                    request.setAttribute("msg", "No rights to Insurance Officer");
                    rd.forward(request, response);
                }
            }
        }
    }
    // ///////////////////////// Delete Policy Registration /////////////

    else if ("deleteHealthPolicy".equals(action)) {
        String errorMsg = null;
        if (request.getParameter("PID").equals(null) || request.getParameter("PID").equals("")) {
            errorMsg = "CustomerId cannot be null or empty";
        }
        if (errorMsg != null) {
            RequestDispatcher rd = request.getRequestDispatcher(
                    "/Insurance Policy Registration/HealthInsuranceScheme/HealthInsuranceRegistration.jsp");
            request.setAttribute("msg", "This field cannot be null or empty");
            rd.forward(request, response);

        } else {
            boolean checkPolicyNum = false;

            HttpSession officerSession = request.getSession(true);
            String officer = (String) officerSession.getAttribute("userid");
            System.out.println(" The officer:" + officer);
            if (officer.substring(0, 2).equals("IO")) {
                String policyRefNum = request.getParameter("PID");

                System.out.println("In DeleteController" + policyRefNum);
                ArrayList<HealthPolicy> policies = s.viewCustomerPolicy();
                for (HealthPolicy hp : policies) {

                    if (hp.getPolicyRefNum().equals(policyRefNum)) {

                        checkPolicyNum = true;
                        System.out.println("Show" + policyRefNum);
                    }
                }
                if (checkPolicyNum) {

                    HealthPolicy hp = new HealthPolicy();

                    String polNum = request.getParameter("PID");
                    hp.setPolicyRefNum(polNum);

                    boolean status = s.deleteHealthPolicy(hp);
                    System.out.println(status);

                    if (status == true) {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/HealthInsuranceScheme/DeleteHealthResult.jsp");
                        rd.forward(request, response);
                    } else {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/HealthInsuranceScheme/HealthDeletePolicy.jsp");
                        request.setAttribute("msg", "You cannot delete this policy");
                        rd.forward(request, response);
                    }
                } else {
                    RequestDispatcher rd = request.getRequestDispatcher(
                            "/Insurance Policy Registration/HealthInsuranceScheme/HealthDeletePolicy.jsp");
                    request.setAttribute("msg", "Policy Reference Number does not exist");
                    rd.forward(request, response);

                }
            } else {
                RequestDispatcher rd = request.getRequestDispatcher(
                        "/Insurance Policy Registration/HealthInsuranceScheme/HealthInsuranceRegistration.jsp");
                request.setAttribute("msg", "No rights to delete");
                rd.forward(request, response);

            }
        }
    }

    else if ("deleteVehiclePolicy".equals(action)) {
        String errorMsg = null;
        if (request.getParameter("PID").equals(null) || request.getParameter("PID").equals("")) {
            errorMsg = "CustomerId cannot be null or empty";
        }
        if (errorMsg != null) {
            RequestDispatcher rd = request.getRequestDispatcher(
                    "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
            request.setAttribute("msg", "This field cannot be null or empty");
            rd.forward(request, response);

        } else {
            boolean checkPolicyNum = false;

            HttpSession officerSession = request.getSession(true);
            String officer = (String) officerSession.getAttribute("userid");
            System.out.println(" SHow officer:" + officer);
            if (officer.substring(0, 2).equals("FO")) {
                String policyRefNum = request.getParameter("PID");
                System.out.println("IN CONTROLLER" + policyRefNum);
                ArrayList<HealthPolicy> policies = s.viewCustomerPolicy();
                for (HealthPolicy hp : policies) {

                    if (hp.getPolicyRefNum().equals(policyRefNum)) {

                        checkPolicyNum = true;
                        System.out.println("Show" + policyRefNum);
                    }
                }
                if (checkPolicyNum) {
                    VehiclePolicy vp = new VehiclePolicy();

                    String polNum = request.getParameter("PID");
                    vp.setPolicyRefNum(polNum);

                    boolean status = s.deleteVehiclePolicy(vp);
                    System.out.println(status);
                    if (status == true) {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/VehicleInsuranceScheme/DeleteVehicleResult.jsp");
                        rd.forward(request, response);

                    } else {
                        RequestDispatcher rd = request.getRequestDispatcher(
                                "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleDeletePolicy.jsp");
                        request.setAttribute("msg", "No Authority!!!You cannot delete health policy");
                        rd.forward(request, response);
                    }
                } else {
                    RequestDispatcher rd = request.getRequestDispatcher(
                            "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleDeletePolicy.jsp");
                    request.setAttribute("msg", "Policy Reference Number does not exist");
                    rd.forward(request, response);

                }
            } else {
                RequestDispatcher rd = request.getRequestDispatcher(
                        "/Insurance Policy Registration/VehicleInsuranceScheme/VehicleInsuranceRegistration.jsp");
                request.setAttribute("msg", "No rights to delete");
                rd.forward(request, response);

            }
        }
    }
}