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:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private void serveRequest(RequestMethod method, HttpServletRequest req, HttpServletResponse rsp)
        throws IOException, ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]");
    }// w  w  w  .j av a 2 s  .c  o m

    if ((loopRetryTimeout > 0L) && (!loopDetected)) {
        long now = System.currentTimeMillis(), diff = now - initTimestamp;
        if ((diff > 0L) && (diff < loopRetryTimeout)) {
            try {
                MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(new ObjectName(
                        "net.community.chest.gitcloud.facade.backend.git:name=BackendRepositoryResolver"));
                if (mbeanInfo != null) {
                    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " detected loop: " + mbeanInfo.getClassName() + "["
                            + mbeanInfo.getDescription() + "]");
                    loopDetected = true;
                }
            } catch (JMException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " failed " + e.getClass().getSimpleName()
                            + " to detect loop: " + e.getMessage());
                }
            }
        }
    }

    ResolvedRepositoryData repoData = resolveTargetRepository(method, req);
    if (repoData == null) {
        throw ExtendedLogUtils.thrownLogging(logger, Level.WARNING,
                "serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]",
                new NoSuchElementException("Failed to resolve repository"));
    }

    String username = authenticate(req);
    // TODO check if the user is allowed to access the repository via the resolve operation (push/pull) if at all (e.g., private repo)
    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "] user="
            + username);

    /*
     * NOTE: this feature requires enabling cross-context forwarding.
     * In Tomcat, the 'crossContext' attribute in 'Context' element of
     * 'TOMCAT_HOME\conf\context.xml' must be set to true, to enable cross-context 
     */
    if (loopDetected) {
        // TODO see if can find a more efficient way than splitting and re-constructing
        URI uri = repoData.getRepoLocation();
        ServletContext curContext = req.getServletContext();
        String urlPath = uri.getPath(), urlQuery = uri.getQuery();
        String[] comps = StringUtils.split(urlPath, '/');
        String appName = comps[0];
        ServletContext loopContext = Validate.notNull(curContext.getContext("/" + appName),
                "No cross-context for %s", appName);
        // build the relative path in the re-directed context
        StringBuilder sb = new StringBuilder(
                urlPath.length() + 1 + (StringUtils.isEmpty(urlQuery) ? 0 : urlQuery.length()));
        for (int index = 1; index < comps.length; index++) {
            sb.append('/').append(comps[index]);
        }
        if (!StringUtils.isEmpty(urlQuery)) {
            sb.append('?').append(urlQuery);
        }

        String redirectPath = sb.toString();
        RequestDispatcher dispatcher = Validate.notNull(loopContext.getRequestDispatcher(redirectPath),
                "No dispatcher for %s", redirectPath);
        dispatcher.forward(req, rsp);
        if (logger.isDebugEnabled()) {
            logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                    + "]" + " forwarded to " + loopContext.getContextPath() + "/" + redirectPath);
        }
    } else {
        executeRemoteRequest(method, repoData.getRepoLocation(), req, rsp);
    }
}

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

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    try {/*  w  w w.  ja v  a 2 s . com*/
        super.doGet(req, res);
        Object obj = req.getAttribute("entity");
        if (obj == null || !(obj instanceof Individual))
            throw new HelpException(
                    "EntityMergedPropertyListController requires request.attribute 'entity' to be of" + " type "
                            + Individual.class.getName());
        Individual subject = (Individual) obj;

        String groupForUngroupedProperties = null;
        String unassignedStr = req.getParameter("unassignedPropsGroupName");
        if (unassignedStr != null && unassignedStr.length() > 0) {
            groupForUngroupedProperties = unassignedStr;
            // pass this on to dashboardPropsList.jsp
            req.setAttribute("unassignedPropsGroupName", unassignedStr);
            log.debug("found temp group parameter \"" + unassignedStr + "\" for unassigned properties");
        }

        boolean groupedMode = false;
        String groupedStr = req.getParameter("grouped");
        if (groupedStr != null && groupedStr.equalsIgnoreCase("true")) {
            groupedMode = true;
        }

        boolean onlyPopulatedProps = true;
        String allPossiblePropsStr = req.getParameter("allProps");
        if (allPossiblePropsStr != null && allPossiblePropsStr.length() > 0) {
            log.debug("found props inclusion parameter \"" + allPossiblePropsStr + "\"");
            if (allPossiblePropsStr.equalsIgnoreCase("true")) {
                onlyPopulatedProps = false;
            }
        }

        VitroRequest vreq = new VitroRequest(req);
        WebappDaoFactory wdf = vreq.getWebappDaoFactory();

        PropertyGroupDao pgDao = null;
        List<PropertyGroup> groupsList = null;
        if (groupedMode) {
            pgDao = wdf.getPropertyGroupDao();
            groupsList = pgDao.getPublicGroups(false); // may be returned empty but not null
        }

        PropertyInstanceDao piDao = wdf.getPropertyInstanceDao();
        ObjectPropertyDao opDao = wdf.getObjectPropertyDao();

        // set up a new list for the combined object and data properties
        List<Property> mergedPropertyList = new ArrayList<Property>();

        if (onlyPopulatedProps) {
            // now first get the properties this entity actually has, presumably populated with statements 
            List<ObjectProperty> objectPropertyList = subject.getObjectPropertyList();
            for (ObjectProperty op : objectPropertyList) {
                op.setLabel(op.getDomainPublic());
                mergedPropertyList.add(op);
            }
        } else {
            log.debug("getting all possible object property choices");
            Collection<PropertyInstance> allPropInstColl = piDao
                    .getAllPossiblePropInstForIndividual(subject.getURI());
            if (allPropInstColl != null) {
                for (PropertyInstance pi : allPropInstColl) {
                    if (pi != null) {
                        ObjectProperty op = opDao.getObjectPropertyByURI(pi.getPropertyURI());
                        op.setLabel(op.getDomainPublic()); // no longer relevant: pi.getSubjectSide() ? op.getDomainPublic() : op.getRangePublic());
                        mergedPropertyList.add(op);
                    } else {
                        log.error(
                                "a property instance in the Collection created by PropertyInstanceDao.getAllPossiblePropInstForIndividual() is unexpectedly null");
                    }
                }
            } else {
                log.error(
                        "a null Collection is returned from PropertyInstanceDao.getAllPossiblePropInstForIndividual()");
            }
        }

        DataPropertyDao dpDao = wdf.getDataPropertyDao();
        if (onlyPopulatedProps) {
            // now do much the same with data properties: get the list of populated data properties, then add in placeholders for missing ones
            List<DataProperty> dataPropertyList = subject.getDataPropertyList();
            for (DataProperty dp : dataPropertyList) {
                dp.setLabel(dp.getPublicName());
                mergedPropertyList.add(dp);
            }
        } else {
            log.debug("getting all possible data property choices");
            Collection<DataProperty> allDatapropColl = dpDao
                    .getAllPossibleDatapropsForIndividual(subject.getURI());
            if (allDatapropColl != null) {
                for (DataProperty dp : allDatapropColl) {
                    if (dp != null) {
                        dp.setLabel(dp.getPublicName());
                        mergedPropertyList.add(dp);
                    } else {
                        log.error(
                                "a data property in the Collection created in DataPropertyDao.getAllPossibleDatapropsForIndividual() is unexpectedly null)");
                    }
                }
            } else {
                log.error(
                        "a null Collection is returned from DataPropertyDao.getAllPossibleDatapropsForIndividual())");
            }
        }

        if (mergedPropertyList != null) {
            try {
                Collections.sort(mergedPropertyList, new PropertyRanker(vreq));
            } catch (Exception ex) {
                log.error("Exception sorting merged property list: " + ex.getMessage());
            }
            if (groupedMode) {
                int groupsCount = 0;
                try {
                    groupsCount = populateGroupsListWithProperties(pgDao, groupsList, mergedPropertyList,
                            groupForUngroupedProperties);
                } catch (Exception ex) {
                    log.error(
                            "Exception on trying to populate groups list with properties: " + ex.getMessage());
                    ex.printStackTrace();
                }
                try {
                    int removedCount = pgDao.removeUnpopulatedGroups(groupsList);
                    if (removedCount == 0) {
                        log.warn("Of " + groupsCount + " groups, none removed by removeUnpopulatedGroups");
                        /*  } else {
                                log.warn("Of "+groupsCount+" groups, "+removedCount+" removed by removeUnpopulatedGroups"); */
                    }
                    groupsCount -= removedCount;
                    req.setAttribute("groupsCount", new Integer(groupsCount));
                    if (groupsCount > 0) { //still
                        for (PropertyGroup g : groupsList) {
                            int statementCount = 0;
                            if (g.getPropertyList() != null && g.getPropertyList().size() > 0) {
                                for (Property p : g.getPropertyList()) {
                                    if (p instanceof ObjectProperty) {
                                        ObjectProperty op = (ObjectProperty) p;
                                        if (op.getObjectPropertyStatements() != null
                                                && op.getObjectPropertyStatements().size() > 0) {
                                            statementCount += op.getObjectPropertyStatements().size();
                                        }
                                    }
                                }
                            }
                            g.setStatementCount(statementCount);
                        }
                    }
                } catch (Exception ex) {
                    log.error("Exception on trying to prune groups list with properties: " + ex.getMessage());
                }
                mergedPropertyList.clear();
            }
            if (groupedMode) {
                req.setAttribute("groupsList", groupsList);
            } else {
                req.setAttribute("dashboardPropertyList", mergedPropertyList);
            }
        }
        req.setAttribute("entity", subject);

        RequestDispatcher rd = req.getRequestDispatcher(Controllers.DASHBOARD_PROP_LIST_JSP);
        rd.include(req, res);
    } catch (HelpException help) {
        doHelp(res);
    } catch (Throwable e) {
        req.setAttribute("javax.servlet.jsp.jspException", e);
        RequestDispatcher rd = req.getRequestDispatcher("/error.jsp");
        rd.forward(req, res);
    }
}

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

/**
 * The get will present a form to the user. 
 *//*  www. ja  v  a 2 s . c om*/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    try {
        super.doGet(req, res);
        log.debug("In doGet");

        VitroRequest vreq = new VitroRequest(req);
        OntModel sessionOntModel = ModelAccess.on(getServletContext()).getOntModel();

        synchronized (FedoraDatastreamController.class) {
            if (fedoraUrl == null) {
                setup(sessionOntModel, getServletContext());
                if (fedoraUrl == null)
                    throw new FdcException("Connection to the file repository is "
                            + "not setup correctly.  Could not read fedora.properties file");
            } else {
                if (!canConnectToFedoraServer()) {
                    fedoraUrl = null;
                    throw new FdcException("Could not connect to Fedora.");
                }
            }
        }
        FedoraClient fedora;
        try {
            fedora = new FedoraClient(fedoraUrl, adminUser, adminPassword);
        } catch (MalformedURLException e) {
            throw new FdcException("Malformed URL for fedora Repository location: " + fedoraUrl);
        }

        FedoraAPIM apim;
        try {
            apim = fedora.getAPIM();
        } catch (Exception e) {
            throw new FdcException("could not create fedora APIM:" + e.getMessage());
        }

        //check if logged in

        //get URI for file individual
        if (req.getParameter("uri") == null || "".equals(req.getParameter("uri")))
            throw new FdcException("No file uri specified in request");

        boolean isDelete = (req.getParameter("delete") != null && "true".equals(req.getParameter("delete")));

        String fileUri = req.getParameter("uri");
        //check if file individual has a fedora:PID for a data stream                        
        IndividualDao iwDao = vreq.getWebappDaoFactory().getIndividualDao();
        Individual entity = iwDao.getIndividualByURI(fileUri);

        if (entity == null)
            throw new FdcException("No entity found in system for file uri " + fileUri);
        //System.out.println("Entity == null:" + (entity == null));                
        //get the fedora PID
        //System.out.println("entity data property " + entity.getDataPropertyMap().get(VitroVocabulary.FEDORA_PID));
        if (entity.getDataPropertyMap().get(VitroVocabulary.FEDORA_PID) == null)
            throw new FdcException("No fedora:pid found in system for file uri " + fileUri);
        List<DataPropertyStatement> stmts = entity.getDataPropertyMap().get(VitroVocabulary.FEDORA_PID)
                .getDataPropertyStatements();
        if (stmts == null || stmts.size() == 0)
            throw new FdcException("No fedora:pid found in system for file uri " + fileUri);
        String pid = null;
        for (DataPropertyStatement stmt : stmts) {
            if (stmt.getData() != null && stmt.getData().length() > 0) {
                pid = stmt.getData();
                break;
            }
        }
        //System.out.println("pid is " + pid + " and comparison is " + (pid == null));
        if (pid == null)
            throw new FdcException("No fedora:pid found in system for file uri " + fileUri);
        req.setAttribute("pid", pid);
        req.setAttribute("fileUri", fileUri);
        //get current file name to use on form
        req.setAttribute("fileName", entity.getName());

        if (isDelete) {
            //Execute a 'deletion', i.e. unlink dataset and file, without removing file
            //Also save deletion as a deleteEvent entity which can later be queried

            String datasetUri = null;
            //Get dataset uri by getting the fromDataSet property
            edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty fromDataSet = entity.getObjectPropertyMap()
                    .get(fedoraNs + "fromDataSet");
            if (fromDataSet != null) {
                List<ObjectPropertyStatement> fromDsStmts = fromDataSet.getObjectPropertyStatements();
                if (fromDsStmts.size() > 0) {
                    datasetUri = fromDsStmts.get(0).getObjectURI();
                    //System.out.println("object uri should be " + datasetUri);
                } else {
                    //System.out.println("No matching dataset uri could be found");
                }
            } else {
                //System.out.println("From dataset is null");
            }

            req.setAttribute("dataseturi", datasetUri);
            boolean success = deleteFile(req, entity, iwDao, sessionOntModel);
            req.setAttribute("deletesuccess", (success) ? "success" : "error");
            req.setAttribute("bodyJsp", "/edit/fileDeleteConfirm.jsp");
            RequestDispatcher rd = req.getRequestDispatcher(Controllers.BASIC_JSP);
            rd.forward(req, res);
        } else {
            //check if the data stream exists in the fedora repository
            Datastream ds = apim.getDatastream(pid, DEFAULT_DSID, null);
            if (ds == null)
                throw new FdcException(
                        "There was no datastream in the " + "repository for " + pid + " " + DEFAULT_DSID);
            req.setAttribute("dsid", DEFAULT_DSID);

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

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

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

    VitroRequest request = new VitroRequest(req);

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

    VClassDao vcwDao = ModelAccess.on(getServletContext()).getWebappDaoFactory(ASSERTIONS_ONLY).getVClassDao();
    VClass vcl = (VClass) vcwDao.getVClassByURI(request.getParameter("uri"));

    if (vcl == null) {
        vcl = request.getUnfilteredWebappDaoFactory().getVClassDao().getTopConcept();
    }

    request.setAttribute("VClass", vcl);

    ArrayList results = new ArrayList();
    results.add("class"); // 1
    results.add("class label"); // 2
    results.add("class group"); // 3
    results.add("ontology"); // 4
    results.add("RDF local name"); // 5
    results.add("short definition"); // 6
    results.add("example"); // 7
    results.add("editor description"); // 8
    //results.add("curator comments"); 
    results.add("display level"); // 9
    results.add("update level"); // 10
    results.add("display rank"); // 11
    results.add("custom entry form"); // 12
    results.add("URI"); // 13
    results.add("publish level"); // 14

    String ontologyName = null;
    if (vcl.getNamespace() != null) {
        Ontology ont = request.getUnfilteredWebappDaoFactory().getOntologyDao()
                .getOntologyByURI(vcl.getNamespace());
        if ((ont != null) && (ont.getName() != null)) {
            ontologyName = ont.getName();
        }
    }

    WebappDaoFactory wadf = request.getUnfilteredWebappDaoFactory();
    String groupURI = vcl.getGroupURI();
    String groupName = "none";
    if (groupURI != null) {
        VClassGroupDao groupDao = wadf.getVClassGroupDao();
        VClassGroup classGroup = groupDao.getGroupByURI(groupURI);
        if (classGroup != null) {
            groupName = classGroup.getPublicName();
        }
    }

    String shortDef = (vcl.getShortDef() == null) ? "" : vcl.getShortDef();
    String example = (vcl.getExample() == null) ? "" : vcl.getExample();
    String description = (vcl.getDescription() == null) ? "" : vcl.getDescription();

    boolean foundComment = false;
    StringBuffer commSb = null;
    for (Iterator<String> commIt = request.getUnfilteredWebappDaoFactory().getCommentsForResource(vcl.getURI())
            .iterator(); commIt.hasNext();) {
        if (commSb == null) {
            commSb = new StringBuffer();
            foundComment = true;
        }
        commSb.append(commIt.next()).append(" ");
    }
    if (!foundComment) {
        commSb = new StringBuffer("no comments yet");
    }

    String hiddenFromDisplay = (vcl.getHiddenFromDisplayBelowRoleLevel() == null ? "(unspecified)"
            : vcl.getHiddenFromDisplayBelowRoleLevel().getDisplayLabel());
    String ProhibitedFromUpdate = (vcl.getProhibitedFromUpdateBelowRoleLevel() == null ? "(unspecified)"
            : vcl.getProhibitedFromUpdateBelowRoleLevel().getUpdateLabel());
    String hiddenFromPublish = (vcl.getHiddenFromPublishBelowRoleLevel() == null ? "(unspecified)"
            : vcl.getHiddenFromPublishBelowRoleLevel().getDisplayLabel());

    String customEntryForm = (vcl.getCustomEntryForm() == null ? "(unspecified)" : vcl.getCustomEntryForm());

    //String lastModified = "<i>not implemented yet</i>"; // TODO

    String uri = (vcl.getURI() == null) ? "" : vcl.getURI();

    results.add(vcl.getPickListName()); // 1
    results.add(vcl.getName() == null ? "(no public label)" : vcl.getName()); // 2
    results.add(groupName); // 3
    results.add(ontologyName == null ? "(not identified)" : ontologyName); // 4
    results.add(vcl.getLocalName()); // 5
    results.add(shortDef); // 6
    results.add(example); // 7
    results.add(description); // 8
    //results.add(commSb.toString());    // 
    results.add(hiddenFromDisplay); // 9
    results.add(ProhibitedFromUpdate); // 10
    results.add(String.valueOf(vcl.getDisplayRank())); // 11
    results.add(customEntryForm); // 12
    results.add(uri); // 13
    results.add(hiddenFromPublish); // 14
    request.setAttribute("results", results);
    request.setAttribute("columncount", NUM_COLS);
    request.setAttribute("suppressquery", "true");

    epo.setDataAccessObject(vcl);
    FormObject foo = new FormObject();
    HashMap OptionMap = new HashMap();

    HashMap formSelect = new HashMap(); // tells the JSP what select lists are populated, and thus should be displayed
    request.setAttribute("formSelect", formSelect);

    // if supported, we want to show only the asserted superclasses and subclasses.
    VClassDao vcDao = ModelAccess.on(getServletContext()).getWebappDaoFactory(ASSERTIONS_ONLY).getVClassDao();
    VClassDao displayVcDao = ModelAccess.on(getServletContext()).getWebappDaoFactory().getVClassDao();

    List<VClass> superVClasses = getVClassesForURIList(vcDao.getSuperClassURIs(vcl.getURI(), false),
            displayVcDao);
    sortForPickList(superVClasses, request);
    request.setAttribute("superclasses", superVClasses);

    List<VClass> subVClasses = getVClassesForURIList(vcDao.getSubClassURIs(vcl.getURI()), displayVcDao);
    sortForPickList(subVClasses, request);
    request.setAttribute("subclasses", subVClasses);

    List<VClass> djVClasses = getVClassesForURIList(vcDao.getDisjointWithClassURIs(vcl.getURI()), displayVcDao);
    sortForPickList(djVClasses, request);
    request.setAttribute("disjointClasses", djVClasses);

    List<VClass> eqVClasses = getVClassesForURIList(vcDao.getEquivalentClassURIs(vcl.getURI()), displayVcDao);
    sortForPickList(eqVClasses, request);
    request.setAttribute("equivalentClasses", eqVClasses);

    // add the options
    foo.setOptionLists(OptionMap);
    epo.setFormObject(foo);

    boolean instantiable = (vcl.getURI().equals(OWL.Nothing.getURI())) ? false : true;

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("vclassWebapp", vcl);
    request.setAttribute("instantiable", instantiable);
    request.setAttribute("bodyJsp", "/templates/edit/specific/classes_edit.jsp");
    request.setAttribute("title", "Class Control Panel");
    //request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""+request.getAppBean().getThemeDir()+"css/edit.css\"/>");

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

}

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

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

    threads = Integer.valueOf(request.getParameter("threadNo"));
    requests = Integer.valueOf(request.getParameter("requestNo"));
    String imgornot = request.getParameter("imgornot");
    boolean showImage = false;
    if (imgornot != null && imgornot.equals("displayimg"))
        showImage = true;//  ww  w .  j  a  va 2 s .  c  o  m

    // process the request asynchronously
    String capab = (String) request.getSession().getAttribute("capab");
    Map<String, String> paramsSet = (HashMap<String, String>) request.getSession().getAttribute("paramsSet");

    Thread t = new Thread(new Processing(request.getSession(), threads, requests, capab, paramsSet, showImage));
    t.start();

    RequestDispatcher dispatcher = request.getRequestDispatcher("/status.jsp");

    HttpSession session = request.getSession();

    // set session attributes
    session.setAttribute("applicationState", "wait");
    session.setAttribute("operationInProgress", "WPVS");

    // send attributes to jsp page
    request.setAttribute("applicationState", "wait");
    request.setAttribute("operationInProgress", "WPVS");
    dispatcher.forward(request, response);

}

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

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

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

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

From source file:net.openkoncept.vroom.VroomController.java

private void processRequestSubmit(HttpServletRequest request, HttpServletResponse response, Map paramMap)
        throws ServletException {
    // change the URI below with the actual page who invoked the request.

    String uri = request.getParameter(CALLER_URI);
    String id = request.getParameter(ID);
    String method = request.getParameter(METHOD);
    String beanClass = request.getParameter(BEAN_CLASS);
    String var = request.getParameter(VAR);
    String scope = request.getParameter(SCOPE);

    if (paramMap != null) {
        uri = (String) ((ArrayList) paramMap.get(CALLER_URI)).get(0);
        id = (String) ((ArrayList) paramMap.get(ID)).get(0);
        method = (String) ((ArrayList) paramMap.get(METHOD)).get(0);
        beanClass = (String) ((ArrayList) paramMap.get(BEAN_CLASS)).get(0);
        var = (String) ((ArrayList) paramMap.get(VAR)).get(0);
        scope = (String) ((ArrayList) paramMap.get(SCOPE)).get(0);
    }/*  w  ww . j av a 2s .com*/

    Object beanObject;
    String outcome = null;

    // call form method...

    try {
        Class clazz = Class.forName(beanClass);
        Class elemClass = clazz;
        String eId, eProperty, eBeanClass, eVar, eScope, eFormat;
        // Setting values to beans before calling the method...
        List<Element> elements = VroomConfig.getInstance().getElements(uri, id, method, beanClass, var, scope);
        for (Element e : elements) {
            eId = e.getId();
            eProperty = (e.getProperty() != null) ? e.getProperty() : eId;
            eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass;
            eVar = (e.getVar() != null) ? e.getVar() : var;
            eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope;
            eFormat = e.getFormat();
            if (!elemClass.getName().equals(eBeanClass)) {
                try {
                    elemClass = Class.forName(eBeanClass);
                } catch (ClassNotFoundException ex) {
                    throw new ServletException("Failed to load class for element [" + eId + "]", ex);
                }
            }
            if (elemClass != null) {
                try {
                    Object obj = getObjectFromScope(request, elemClass, eVar, eScope);
                    if (PropertyUtils.isWriteable(obj, eProperty)) {
                        Class propType = PropertyUtils.getPropertyType(obj, eProperty);
                        Object[] paramValues = request.getParameterValues(eId);
                        Object value = null;
                        value = getParameterValue(propType, eId, paramValues, eFormat, paramMap);
                        PropertyUtils.setProperty(obj, eProperty, value);
                    }
                } catch (InstantiationException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                } catch (IllegalAccessException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                }
            }
        }
        // Calling the method...
        beanObject = getObjectFromScope(request, clazz, var, scope);
        Class[] signature = new Class[] { HttpServletRequest.class, HttpServletResponse.class };
        Method m = clazz.getMethod(method, signature);
        Object object = m.invoke(beanObject, new Object[] { request, response });
        // Getting updating values from beans to pass as postback for the forward calls.
        Map<String, Object> postbackMap = new HashMap<String, Object>();
        for (Element e : elements) {
            eId = e.getId();
            eProperty = (e.getProperty() != null) ? e.getProperty() : eId;
            eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass;
            eVar = (e.getVar() != null) ? e.getVar() : var;
            eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope;
            eFormat = e.getFormat();
            if (!elemClass.getName().equals(eBeanClass)) {
                try {
                    elemClass = Class.forName(eBeanClass);
                } catch (ClassNotFoundException ex) {
                    throw new ServletException("Failed to load class for element [" + eId + "]", ex);
                }
            }
            if (elemClass != null) {
                try {
                    Object obj = getObjectFromScope(request, elemClass, eVar, eScope);
                    if (PropertyUtils.isReadable(obj, eProperty)) {
                        //                            Class propType = PropertyUtils.getPropertyType(obj, eProperty);
                        //                            Object[] paramValues = request.getParameterValues(eId);
                        //                            Object value = null;
                        //                            value = getParameterValue(propType, eId, paramValues, eFormat, paramMap);
                        //                            PropertyUtils.setProperty(obj, eProperty, value);
                        Object value = PropertyUtils.getProperty(obj, eProperty);
                        postbackMap.put(eId, value);
                    }
                } catch (InstantiationException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                } catch (IllegalAccessException ex) {
                    throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex);
                }
            }
        }
        if (object == null || object instanceof String) {
            outcome = (String) object;
            Navigation n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope,
                    outcome);
            if (n == null) {
                n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope, "default");
            }
            if (n != null) {
                String url = n.getUrl();
                if (url == null) {
                    url = "/";
                }
                url = url.replaceAll("#\\{contextPath}", request.getContextPath());
                if (n.isForward()) {
                    String ctxPath = request.getContextPath();
                    if (url.startsWith(ctxPath)) {
                        url = url.substring(ctxPath.length());
                    }
                    PrintWriter pw = response.getWriter();
                    VroomResponseWrapper responseWrapper = new VroomResponseWrapper(response);
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, responseWrapper);
                    StringBuffer sbHtml = new StringBuffer(responseWrapper.toString());
                    VroomHtmlProcessor.addHeadMetaTags(sbHtml, uri, VroomConfig.getInstance());
                    VroomHtmlProcessor.addHeadLinks(sbHtml, uri, VroomConfig.getInstance());
                    VroomHtmlProcessor.addRequiredScripts(sbHtml, request);
                    VroomHtmlProcessor.addInitScript(sbHtml, uri, request);
                    VroomHtmlProcessor.addHeadScripts(sbHtml, uri, VroomConfig.getInstance(), request);
                    VroomHtmlProcessor.addStylesheets(sbHtml, uri, VroomConfig.getInstance(), request);
                    // Add postback values to webpage through javascript...
                    VroomHtmlProcessor.addPostbackScript(sbHtml, uri, request, postbackMap);
                    String html = sbHtml.toString().replaceAll("#\\{contextPath}", request.getContextPath());
                    response.setContentLength(html.length());
                    pw.print(html);
                } else {
                    response.sendRedirect(url);
                }
            } else {
                throw new ServletException("No navigation found for outcome [" + outcome + "]");
            }
        }

    } catch (ClassNotFoundException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (InstantiationException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (IllegalAccessException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (NoSuchMethodException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (InvocationTargetException ex) {
        throw new ServletException("Invocation Failed for method [" + method + "]", ex);
    } catch (IOException ex) {
        throw new ServletException("Navigation Failed for outcome [" + outcome + "]", ex);
    }
}

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

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

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

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

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

From source file:Controller.login.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* www .  ja  v  a2 s. c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String email = request.getParameter("inputEmail");
    String password = request.getParameter("inputPassword");
    String remember = request.getParameter("remember");

    System.out.println("remember ne mnow " + email);

    LoginImplementation loginCheckObject = new LoginImplementation();

    JSONObject userData = (loginCheckObject.loginNow(email, password, remember));
    System.out.println(userData);
    if (userData.has("error")) {
        RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
        request.setAttribute("loginError", "error");
        rd.include(request, response);

    } else {

        if ("yes".equals(remember)) {
            System.out.println("apples");
            HttpSession session = request.getSession();
            session.setAttribute("user", userData);
            //setting session to expiry in 30 mins
            session.setMaxInactiveInterval(30 * 60);
            Cookie userName = new Cookie("user", email);
            userName.setMaxAge(30 * 60);
            response.addCookie(userName);
        }
        request.setAttribute("userData", userData);
        RequestDispatcher rd = request.getRequestDispatcher("views/home.jsp");
        rd.forward(request, response);
        return;
    }

    out.close();
}

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

@Override
public void doPost(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
        return;/*  www  .  ja  va  2s .c  o  m*/
    }

    VitroRequest request = new VitroRequest(req);

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

    /*for testing*/
    ObjectProperty testMask = new ObjectProperty();
    epo.setBeanClass(ObjectProperty.class);
    epo.setBeanMask(testMask);

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

    ObjectPropertyDao propDao = ModelAccess.on(getServletContext()).getWebappDaoFactory()
            .getObjectPropertyDao();
    epo.setDataAccessObject(propDao);
    OntologyDao ontDao = request.getUnfilteredWebappDaoFactory().getOntologyDao();

    ObjectProperty propertyForEditing = null;
    if (!epo.getUseRecycledBean()) {
        String uri = request.getParameter("uri");
        if (uri != null) {
            try {
                propertyForEditing = propDao.getObjectPropertyByURI(uri);
                action = "update";
                epo.setAction("update");
            } catch (NullPointerException e) {
                log.error("Need to implement 'record not found' error message.");
                throw (e);
            }
        } else {
            propertyForEditing = new ObjectProperty();
            if (request.getParameter("parentId") != null) {
                propertyForEditing.setParentURI(request.getParameter("parentId"));
            }
            if (request.getParameter("domainClassUri") != null) {
                propertyForEditing.setDomainVClassURI(request.getParameter("domainClassUri"));
            }
        }
        epo.setOriginalBean(propertyForEditing);
    } else {
        propertyForEditing = (ObjectProperty) epo.getNewBean();
    }

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

    //set any validators
    List<Validator> localNameValidatorList = new ArrayList<>();
    localNameValidatorList.add(new XMLNameValidator());
    List<Validator> localNameInverseValidatorList = new ArrayList<>();
    localNameInverseValidatorList.add(new XMLNameValidator(true));
    epo.getValidatorMap().put("LocalName", localNameValidatorList);
    epo.getValidatorMap().put("LocalNameInverse", localNameInverseValidatorList);
    List<Validator> displayRankValidatorList = new ArrayList<Validator>();
    displayRankValidatorList.add(new IntValidator());
    epo.getValidatorMap().put("DisplayRank", displayRankValidatorList);

    //set up any listeners
    List<ChangeListener> changeListenerList = new ArrayList<>();
    changeListenerList.add(new PropertyRestrictionListener());
    epo.setChangeListenerList(changeListenerList);

    //make a postinsert pageforwarder that will send us to a new class's fetch screen
    epo.setPostInsertPageForwarder(new PropertyInsertPageForwarder());
    //make a postdelete pageforwarder that will send us to the list of properties
    epo.setPostDeletePageForwarder(new UrlForwarder("listPropertyWebapps"));

    //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(propDao.getClass().getDeclaredMethod("getObjectPropertyByURI", args));
    } catch (NoSuchMethodException e) {
        log.error(
                "PropertyRetryController could not find the getPropertyByURI method in the PropertyWebappDao");
    }

    FormObject foo = new FormObject();
    foo.setErrorMap(epo.getErrMsgMap());

    HashMap<String, List<Option>> optionMap = new HashMap<String, List<Option>>();
    try {
        populateOptionMap(optionMap, propertyForEditing, request, ontDao, propDao);
    } catch (Exception e) {
        log.error(e, e);
        throw new RuntimeException(e);
    }

    optionMap.put("HiddenFromDisplayBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getDisplayOptionsList(propertyForEditing));
    optionMap.put("ProhibitedFromUpdateBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getUpdateOptionsList(propertyForEditing));
    optionMap.put("HiddenFromPublishBelowRoleLevelUsingRoleUri",
            RoleLevelOptionsSetup.getPublishOptionsList(propertyForEditing));

    List<Option> groupOptList = FormUtils.makeOptionListFromBeans(
            request.getUnfilteredWebappDaoFactory().getPropertyGroupDao().getPublicGroups(true), "URI", "Name",
            ((propertyForEditing.getGroupURI() == null) ? "" : propertyForEditing.getGroupURI()), null,
            (propertyForEditing.getGroupURI() != null));
    HashMap<String, Option> hashMap = new HashMap<String, Option>();
    groupOptList = getSortedList(hashMap, groupOptList, request);
    groupOptList.add(0, new Option("", "none"));
    optionMap.put("GroupURI", groupOptList);

    foo.setOptionLists(optionMap);

    request.setAttribute("transitive", propertyForEditing.getTransitive());
    request.setAttribute("symmetric", propertyForEditing.getSymmetric());
    request.setAttribute("functional", propertyForEditing.getFunctional());
    request.setAttribute("inverseFunctional", propertyForEditing.getInverseFunctional());
    request.setAttribute("selectFromExisting", propertyForEditing.getSelectFromExisting());
    request.setAttribute("offerCreateNewOption", propertyForEditing.getOfferCreateNewOption());
    request.setAttribute("objectIndividualSortPropertyURI",
            propertyForEditing.getObjectIndividualSortPropertyURI());
    request.setAttribute("domainEntitySortDirection", propertyForEditing.getDomainEntitySortDirection());
    request.setAttribute("collateBySubclass", propertyForEditing.getCollateBySubclass());

    //checkboxes are pretty annoying : we don't know if someone *unchecked* a box, so we have to default to false on updates.
    if (propertyForEditing.getURI() != null) {
        propertyForEditing.setTransitive(false);
        propertyForEditing.setSymmetric(false);
        propertyForEditing.setFunctional(false);
        propertyForEditing.setInverseFunctional(false);
        propertyForEditing.setSelectFromExisting(false);
        propertyForEditing.setOfferCreateNewOption(false);
        //propertyForEditing.setStubObjectRelation(false);
        propertyForEditing.setCollateBySubclass(false);
    }

    epo.setFormObject(foo);

    FormUtils.populateFormFromBean(propertyForEditing, action, foo, epo.getBadValueMap());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
    request.setAttribute("colspan", "5");
    request.setAttribute("formJsp", "/templates/edit/specific/property_retry.jsp");
    request.setAttribute("scripts", "/templates/edit/formBasic.js");
    request.setAttribute("title", "Property Editing Form");
    request.setAttribute("_action", action);
    setRequestAttributes(request, epo);

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

}