Example usage for org.springframework.web.servlet.view RedirectView RedirectView

List of usage examples for org.springframework.web.servlet.view RedirectView RedirectView

Introduction

In this page you can find the example usage for org.springframework.web.servlet.view RedirectView RedirectView.

Prototype

public RedirectView(String url) 

Source Link

Document

Create a new RedirectView with the given URL.

Usage

From source file:org.jasig.cas.support.oauth.OAuthUtils.java

/**
 * Return a view which is a redirection to an url.
 *
 * @param url redirect url//from w w  w  .  j  a v a  2 s. co  m
 * @return A view which is a redirection to an url
 */
public static ModelAndView redirectTo(final String url) {
    return new ModelAndView(new RedirectView(url));
}

From source file:com.rr.wabshs.ui.fundingSource.fundingSourceController.java

/**
 * The '' request will display the list of funding sources.
 *
 * @param request/*from   w  w  w . j  a  v a 2s.c  om*/
 * @param response
 * @return   the funding source list view
 * @throws Exception
 */
@RequestMapping(value = "", method = RequestMethod.GET)
public ModelAndView listFundingSources(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) throws Exception {

    /* Get a list of completed surveys the logged in user has access to */
    User userDetails = (User) session.getAttribute("userDetails");

    if (userDetails.getRoleId() != 2) {
        ModelAndView mav = new ModelAndView(new RedirectView("/fundingsources/allocation"));
        return mav;
    }

    ModelAndView mav = new ModelAndView();
    mav.setViewName("/fundingSources");

    /* Get user permissions */
    userProgramModules modulePermissions = usermanager.getUserModulePermissions(programId, userDetails.getId(),
            moduleId);
    Integer userId = 0;
    if (userDetails.getRoleId() == 2) {
        allowCreate = true;
        allowEdit = true;
        allowDelete = true;
    } else {
        allowCreate = modulePermissions.isAllowCreate();
        allowDelete = modulePermissions.isAllowDelete();
        allowEdit = modulePermissions.isAllowEdit();
        userId = userDetails.getId();
    }

    mav.addObject("allowCreate", allowCreate);
    mav.addObject("allowDelete", allowDelete);
    mav.addObject("allowEdit", allowEdit);

    // Get a list of program profiles for the registry
    List<fundingSource> fundingSources = fundingsourcemanager.getfundingSources(programId);

    if (fundingSources != null && fundingSources.size() > 0) {
        for (fundingSource fundingSource : fundingSources) {

            User enteredByDetails = usermanager.getUserById(fundingSource.getSystemUserId());
            fundingSource.setFirstName(enteredByDetails.getFirstName());
            fundingSource.setLastName(enteredByDetails.getLastName());

            encryptObject encrypt = new encryptObject();
            Map<String, String> map;

            //Encrypt the use id to pass in the url
            map = new HashMap<String, String>();
            map.put("id", Integer.toString(fundingSource.getId()));
            map.put("topSecret", topSecret);

            String[] encrypted = encrypt.encryptObject(map);

            fundingSource.setEncryptedId(encrypted[0]);
            fundingSource.setEncryptedSecret(encrypted[1]);
        }
    }

    mav.addObject("fundingSources", fundingSources);

    return mav;
}

From source file:org.openmrs.web.controller.form.FieldFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db/* w  ww.j  a va 2  s  .  co m*/
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();
    String action = request.getParameter("action");

    if (Context.isAuthenticated()) {
        Field field = (Field) obj;
        field = setObjects(field, request);

        if (action != null && action.equals(Context.getMessageSourceService().getMessage("general.delete"))) {
            try {
                Context.getFormService().purgeField(field);
            } catch (DataIntegrityViolationException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
                return new ModelAndView(new RedirectView("field.form?fieldId=" + field.getFieldId()));
            }
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Field.Deleted");
        } else {
            Context.getFormService().saveField(field);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Field.saved");
        }
    }

    view = getSuccessView();
    view = view + "?phrase=" + request.getParameter("phrase");

    return new ModelAndView(new RedirectView(view));
}

From source file:org.schedoscope.metascope.controller.MetascopeTableController.java

/**
 * Detail view of a table; path = '/table'
 *
 * @param request the HTTPServletRequest from the client
 * @return the table detail view// w  w  w  .j  av a2  s.  c o  m
 */
@RequestMapping(value = "/table", method = RequestMethod.GET)
@Transactional
public ModelAndView getTable(HttpServletRequest request) {
    ModelAndView mav = new ModelAndView("body/table/table");

    /* load table from repository */
    String fqdn = getParameter(request, "fqdn");
    MetascopeTable tableEntity = metascopeTableService.findByFqdn(fqdn);
    if (tableEntity == null) {
        return new ModelAndView(new RedirectView("/notfound"));
    }

    /* retrieve requested page for partitions section */
    String partitionPageParameter = getParameter(request, "partitionPage");
    int partitionPage = 1;
    if (partitionPageParameter != null) {
        Integer p = ParseUtil.tryParse(partitionPageParameter);
        if (p != null && p > 0) {
            partitionPage = p;
        }
    }

    /* get all taxonomies */
    Iterable<MetascopeTaxonomy> taxonomies = metascopeTaxonomyService.getTaxonomies();
    List<String> taxonomyNames = new ArrayList<String>();
    for (MetascopeTaxonomy taxonomyEntity : taxonomies) {
        taxonomyNames.add(taxonomyEntity.getName());
    }

    Map<String, Map<String, List<MetascopeField>>> fieldDeps = metascopeTableService
            .getFieldDependencies(tableEntity);
    Map<String, Map<String, List<MetascopeField>>> fieldSucs = metascopeTableService
            .getFieldSuccessors(tableEntity);

    Map<String, CategoryMap> tableTaxonomies = metascopeTableService.getTableTaxonomies(tableEntity);

    /* get all users for user management and owner auto completion */
    Iterable<MetascopeUser> users = metascopeUserService.getAllUser();

    /* get all registered table owners for auto completion */
    Set<String> owner = metascopeTableService.getAllOwner();
    owner.remove(null);
    for (MetascopeUser user : users) {
        if (!owner.contains(user.getFullname())) {
            owner.add(user.getFullname());
        }
    }

    /* check data distribution calculation status */
    MetascopeDataDistributionService.Status dataDistStatus = metascopeDataDistributionService
            .checkStatus(tableEntity);
    if (dataDistStatus.equals(MetascopeDataDistributionService.Status.Finished)) {
        mav.addObject("ddMap", metascopeDataDistributionService.getDataDistribution(tableEntity));
    }

    /* check if this user is an admin */
    boolean isAdmin = metascopeUserService.isAdmin();

    /* check if this table is favourised */
    boolean isFavourite = metascopeUserService.isFavourite(tableEntity);

    boolean transitive = getParameter(request, "transitive") != null;
    if (transitive) {
        /* get transitive dependencies and successors */
        List<MetascopeTable> transitiveDependencies = metascopeTableService
                .getTransitiveDependencies(tableEntity);
        List<MetascopeTable> transitiveSuccessors = metascopeTableService.getTransitiveSuccessors(tableEntity);
        mav.addObject("transitiveDependencies", transitiveDependencies);
        mav.addObject("transitiveSuccessors", transitiveSuccessors);
    }

    /*
     * if table is partitioned, get the first parameter (see 'Data Distribution'
     * section)
     */
    Set<MetascopeField> parameters = tableEntity.getParameters();
    if (parameters.size() > 0) {
        mav.addObject("firstParam", parameters.iterator().next().getFieldName());
    }

    /* check if a draft autosave is available */
    boolean metascopeAutoSave = metascopeDocumentationService.checkForDraft(tableEntity,
            metascopeUserService.getUser());

    /* check if the responsible person has been changed */
    String personResponsible = getParameter(request, "personResponsible");

    /* check if the docuemntation has been changed */
    String documentation = getParameter(request, "documentation");

    /* check if a comment has been created/edited/deleted */
    String comment = getParameter(request, "comment");

    /* check if the taxonomy has been changed */
    String taxonomy = getParameter(request, "taxonomy");

    /*
     * local parameter indicates if the css and javascript should be containted
     * in the html. this can be useful when displaying views in third party
     * sites and apps
     */
    boolean local = getParameter(request, "local") != null;

    /* search result breadcrumb */
    String referer = request.getHeader("Referer");
    String searchResultBreadcrumb = null;
    if (referer != null) {
        String refererSplit[] = request.getHeader("Referer").split("\\?");
        if (refererSplit.length == 2 && refererSplit[0].contains("home")
                && hasSearchParameters(refererSplit[1])) {
            searchResultBreadcrumb = referer;
        }
    }

    /* make objects accessible for thymeleaf to render final view */
    mav.addObject("table", tableEntity);
    mav.addObject("userEntityService", metascopeUserService);
    mav.addObject("util", htmlUtil);
    mav.addObject("local", local);
    mav.addObject("partitionPage", partitionPage);
    mav.addObject("users", users);
    mav.addObject("owner", owner);
    mav.addObject("fieldDependencyMap", fieldDeps);
    mav.addObject("fieldSuccessorMap", fieldSucs);
    mav.addObject("taxonomies", taxonomies);
    mav.addObject("taxonomyNames", taxonomyNames);
    mav.addObject("tableTaxonomies", tableTaxonomies);
    mav.addObject("admin", isAdmin);
    mav.addObject("draft", metascopeAutoSave);
    mav.addObject("isFavourite", isFavourite);
    mav.addObject("personResponsible", personResponsible);
    mav.addObject("documentation", documentation);
    mav.addObject("comment", comment);
    mav.addObject("taxonomy", taxonomy);
    mav.addObject("dataDistStatus", dataDistStatus.name().toLowerCase());
    mav.addObject("searchResultBreadcrumb", searchResultBreadcrumb);
    mav.addObject("userMgmnt", config.withUserManagement());

    return mav;
}

From source file:org.openmrs.web.controller.program.PatientProgramFormController.java

public ModelAndView enroll(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String returnPage = request.getParameter("returnPage");
    if (returnPage == null) {
        throw new IllegalArgumentException("must specify a returnPage parameter in a call to enroll()");
    }// w  ww.  jav  a 2  s .  c om

    String patientIdStr = request.getParameter("patientId");
    String programIdStr = request.getParameter("programId");
    String enrollmentDateStr = request.getParameter("dateEnrolled");
    String locationIdStr = request.getParameter("locationId");
    String completionDateStr = request.getParameter("dateCompleted");

    log.debug("enroll " + patientIdStr + " in " + programIdStr + " on " + enrollmentDateStr);

    ProgramWorkflowService pws = Context.getProgramWorkflowService();

    // make sure we parse dates the same was as if we were using the initBinder + property editor method 
    CustomDateEditor cde = new CustomDateEditor(Context.getDateFormat(), true, 10);
    cde.setAsText(enrollmentDateStr);
    Date enrollmentDate = (Date) cde.getValue();
    cde.setAsText(completionDateStr);
    Date completionDate = (Date) cde.getValue();
    Patient patient = Context.getPatientService().getPatient(Integer.valueOf(patientIdStr));

    Location location;
    try {
        location = Context.getLocationService().getLocation(Integer.valueOf(locationIdStr));
    } catch (Exception e) {
        location = null;
    }

    Program program;
    try {
        program = pws.getProgram(Integer.valueOf(programIdStr));
    } catch (NumberFormatException e) {
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Program.error.programRequired");
        return new ModelAndView(new RedirectView(returnPage));
    }
    if (enrollmentDate == null) {
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "Program.error.enrollmentDateRequired");
    } else if (!pws.getPatientPrograms(patient, program, null, completionDate, enrollmentDate, null, false)
            .isEmpty()) {
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Program.error.already");
    } else {
        PatientProgram pp = new PatientProgram();
        pp.setPatient(patient);
        pp.setLocation(location);
        pp.setProgram(program);
        pp.setDateEnrolled(enrollmentDate);
        pp.setDateCompleted(completionDate);

        // Set any initial states if passed in
        for (ProgramWorkflow workflow : program.getAllWorkflows()) {
            String stateIdStr = request.getParameter("initialState." + workflow.getProgramWorkflowId());
            if (StringUtils.hasText(stateIdStr)) {
                Integer stateId = Integer.valueOf(stateIdStr);
                ProgramWorkflowState state = workflow.getState(stateId);
                log.debug("Transitioning to state: " + state);
                pp.transitionToState(state, enrollmentDate);
            }
        }
        try {
            String message = validateWithErrorCodes(pp);
            if (message != null) {
                request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
            } else {
                Context.getProgramWorkflowService().savePatientProgram(pp);
            }
        } catch (APIException e) {
            request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
        }
    }
    return new ModelAndView(new RedirectView(returnPage));
}

From source file:org.openmrs.web.controller.person.AddPersonController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *//*w  ww . j  av  a2 s .  co m*/
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    Map<String, String> person = getParametersFromRequest(request);

    String personId = person.get(PERSON_ID);
    String viewType = person.get(VIEW_TYPE);
    String personType = person.get(PERSON_TYPE);

    if (StringUtils.isEmpty(personId)) {
        // if they didn't pick a person, continue on to the edit screen no matter what type of view was requested)
        if ("view".equals(viewType) || "shortEdit".equals(viewType)) {
            viewType = "shortEdit";
        } else {
            viewType = "edit";
        }

        return new ModelAndView(new RedirectView(getPersonURL("", personType, viewType, request)));
    } else {
        // if they picked a person, go to the type of view that was requested

        // if they selected view, do a double check to make sure that type of person already exists
        if ("view".equals(viewType) && "patient".equals(personType)) {
            // TODO Do we even want to ever redirect to a 'view'.  I'm torn between jumping the DAs right to the 
            // dashboard or jumping them to the short edit screen to make (potential) adjustments
            try {
                if (Context.getPatientService().getPatient(Integer.valueOf(personId)) == null) {
                    viewType = "shortEdit";
                }
            } catch (Exception noPatientEx) {
                // if there is no patient yet, they must go through those motions
                viewType = "shortEdit";
            }
        }

        // redirect to the appropriate url
        return new ModelAndView(new RedirectView(getPersonURL(personId, personType, viewType, request)));
    }
}

From source file:org.openmrs.notification.web.controller.AlertListController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db// w  w w . j a  v a  2 s  .  c o  m
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    Locale locale = Context.getLocale();

    if (Context.isAuthenticated()) {
        AlertService as = Context.getAlertService();

        MessageSourceAccessor msa = getMessageSourceAccessor();
        String msg = "";

        // expire the selected alerts
        String[] alertIds = request.getParameterValues("alertId");
        if (alertIds != null) {
            for (String alertIdString : alertIds) {
                Integer alertId = Integer.parseInt(alertIdString);
                Alert a = as.getAlert(alertId);
                a.setDateToExpire(new Date());
                as.saveAlert(a);
            }

            msg = msa.getMessage("Alert.expired", new Object[] { alertIds.length }, locale);
        } else {
            msg = msa.getMessage("Alert.select");
        }

        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, msg);
        return new ModelAndView(new RedirectView(getSuccessView()));
    }

    // The user isn't authenticated or their session has expired
    return showForm(request, response, errors);
}

From source file:fm.last.citrine.web.ChildTasksFormController.java

@Override
public ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object command, BindException errors) throws Exception {
    if (request.getParameter(PARAM_CANCEL) != null) {
        TaskChildCandidatesDTO dto = ((TaskChildCandidatesDTO) command);
        return new ModelAndView(new RedirectView(getSuccessView(dto.getSelectedGroupName())));
    }/*w  ww  .ja v a 2s . c  o m*/
    return super.processFormSubmission(request, response, command, errors);
}

From source file:org.tsm.concharto.web.wiki.UserWikiPageController.java

@SuppressWarnings("unchecked")
@Override/*from w  ww  .ja v  a  2 s.c  om*/
protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors)
        throws Exception {

    if (isEventPage(request)) {
        //ok we simply redirect to the search page
        return new ModelAndView(
                new RedirectView("/search/eventsearch.htm?_what=%22" + getEvent(request) + "%22"));
    } else {
        Map model = errors.getModel();
        String username = getUsername(request);
        //if the user doesn't exist, it means this is an anonymous user page
        if (null == getUser(request)) {
            model.put("isAnonymous", true);
        }

        //If this is my talk page and there are notifications, then we can clear
        //the notifications
        if (iAmWritingOnMyPage(request) && isUserTalkPage(request)) {
            if (null != WebUtils.getSessionAttribute(request, NotificationFilter.SESSION_MESSAGES_PENDING)) {
                //clear the notifications
                notificationService.clearNotifications(username, NotificationType.TALK);
                //clear the session variable
                WebUtils.setSessionAttribute(request, NotificationFilter.SESSION_MESSAGES_PENDING, null);
                //if the page didn't exist before, we should make it so the link shows
                //that the page now exists
                WebUtils.setSessionAttribute(request, WikiConstants.SESSION_MYTALK_EXISTS, true);
            }
        }
        return new ModelAndView(getFormView(), model);
    }
}

From source file:net.mindengine.oculus.frontend.web.controllers.project.ProjectCreateController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    Project project = (Project) command;
    if (project == null)
        throw new UnexistentResource("");

    User user = getAuthorizedUser(request);
    project.setAuthorId(user.getId());/*from  w  w  w . j a v  a 2s.  c o  m*/
    project.setDate(new Date());
    if (project.getParentId() == null || project.getParentId().equals(0)) {
        user.verifyPermission("project_managment");
    } else if (project.getParentId() != null && project.getParentId() > 0) {
        user.verifyPermission("subproject_managment");
    }

    project.setId(projectDAO.createProject(project));
    updateProjectCustomizationValues(request, project);

    return new ModelAndView(new RedirectView("../project/display-" + project.getPath()));
}