Example usage for org.springframework.web.servlet ModelAndView setView

List of usage examples for org.springframework.web.servlet ModelAndView setView

Introduction

In this page you can find the example usage for org.springframework.web.servlet ModelAndView setView.

Prototype

public void setView(@Nullable View view) 

Source Link

Document

Set a View object for this ModelAndView.

Usage

From source file:cherry.entree.secure.passwd.PasswdControllerImpl.java

@Override
public ModelAndView execute(PasswdForm form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, HttpServletRequest request, RedirectAttributes redirAttr) {

    if (binding.hasErrors()) {
        ModelAndView mav = new ModelAndView(PathDef.VIEW_PASSWD_INIT);
        return mav;
    }//  w ww.jav a  2 s. c  o m

    if (!validateForm(form, binding)) {
        ModelAndView mav = new ModelAndView(PathDef.VIEW_PASSWD_INIT);
        return mav;
    }

    if (!auth.getName().equals(form.getLoginId())) {
        rejectOnCurAuthFailed(binding);
        ModelAndView mav = new ModelAndView(PathDef.VIEW_PASSWD_INIT);
        return mav;
    }

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(auth.getName(),
            form.getPassword());
    try {
        Authentication a = authenticationManager.authenticate(token);
        checkNotNull(a, "AuthenticationManager#authenticate(token): null");
    } catch (AuthenticationException ex) {
        rejectOnCurAuthFailed(binding);
        ModelAndView mav = new ModelAndView(PathDef.VIEW_PASSWD_INIT);
        return mav;
    }

    String password = passwordEncoder.encode(form.getNewPassword());
    if (!passwdService.changePassword(auth.getName(), password)) {
        if (log.isDebugEnabled()) {
            log.debug("Password has not been updated: loginId={0}, password={1}", auth.getName(), password);
        }
        throw new IllegalStateException("");
    }

    UriComponents uc = fromMethodCall(on(PasswdController.class).finish(auth, locale, sitePref, request))
            .build();

    ModelAndView mav = new ModelAndView();
    mav.setView(new RedirectView(uc.toUriString(), true));
    return mav;
}

From source file:org.shareok.data.webserv.JournalDataController.java

@RequestMapping(value = "/dspace/safpackage/{publisher}/upload", method = RequestMethod.POST)
public ModelAndView safPackageDataUpload(RedirectAttributes redirectAttrs,
        @RequestParam("file") MultipartFile file, @PathVariable("publisher") String publisher) {

    if (!file.isEmpty()) {
        try {/*from   www .java  2 s.c o m*/
            String[] filePaths = DspaceJournalServiceManager.getDspaceSafPackageDataService(publisher)
                    .getSafPackagePaths(file);
            if (null != filePaths && filePaths.length > 0) {

                ModelAndView model = new ModelAndView();
                RedirectView view = new RedirectView();
                view.setContextRelative(true);

                List<String> downloadLinks = new ArrayList<>();
                for (String path : filePaths) {
                    String link = DspaceJournalDataUtil.getDspaceSafPackageDataDownloadLinks(path);
                    downloadLinks.add(link);
                }
                ObjectMapper mapper = new ObjectMapper();
                String downloadLink = mapper.writeValueAsString(downloadLinks);
                //                    String uploadFileLink = downloadLink.split("/journal/"+publisher+"/")[1];
                //                    uploadFileLink = uploadFileLink.substring(0, uploadFileLink.length()-1);

                model.setViewName("journalDataUploadDisplay");
                model.addObject("safPackages", downloadLink);
                model.addObject("publisher", publisher);
                //                    model.addObject("uploadFile", uploadFileLink);
                view.setUrl("/dspace/safpackage/ouhistory/display");
                model.setView(view);

                return model;
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    } else {
        return null;
    }
    return null;
}

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

/**
 * Prepares the form view//from   www.j  a  v a  2 s. co  m
 */
public ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors)
        throws Exception {

    log.debug("In showForm method");

    ModelAndView mav = super.showForm(request, response, errors);

    // If a invalid age is submitted, give the user a useful error message.
    if (invalidAgeFormat) {
        mav = new ModelAndView(FORM_ENTRY_ERROR_URL);
        mav.addObject("errorTitle", "Person.age.error");
        mav.addObject("errorMessage", "Person.birthdate.required");
        return mav;
    }

    Object o = mav.getModel().get(this.getCommandName());

    List personList = (List) o;

    log.debug("Found list of size: " + personList.size());

    if (personList.size() < 1 && Context.isAuthenticated()) {
        Map<String, String> person = getParametersFromRequest(request);

        String name = person.get(NAME);
        String birthdate = person.get(BIRTH_DATE);
        String age = person.get(AGE);
        String gender = person.get(GENDER);
        String viewType = person.get(VIEW_TYPE);
        String personType = person.get(PERSON_TYPE);

        if (viewType == null) {
            viewType = "edit";
        }

        log.debug("name: " + name + " birthdate: " + birthdate + " age: " + age + " gender: " + gender);

        if (StringUtils.isNotEmpty(name) || StringUtils.isNotEmpty(birthdate) || StringUtils.isNotEmpty(age)
                || StringUtils.isNotEmpty(gender)) {
            mav.clear();
            mav.setView(new RedirectView(getPersonURL("", personType, viewType, request)));
        }
    }

    return mav;
}

From source file:com.devnexus.ting.web.controller.admin.RegistrationController.java

@RequestMapping(value = "/s/admin/{eventKey}/groupRegistration", method = RequestMethod.POST)
public ModelAndView downloadGroupRegistration(ModelAndView model, HttpServletRequest request,
        @PathVariable(value = "eventKey") String eventKey, @Valid RegisterForm form, BindingResult result)
        throws FileNotFoundException, IOException, InvalidFormatException {

    EventSignup signUp = eventSignupRepository.getByEventKey(eventKey);

    model.getModelMap().addAttribute("event", signUp.getEvent());
    model.getModelMap().addAttribute("registerForm", form);

    if (!result.hasErrors()) {
        Workbook workbook = WorkbookFactory
                .create(getClass().getResourceAsStream("/forms/registration_form.xlsx"));
        Sheet formSheet = workbook.getSheetAt(0);
        Sheet ticketTypeSheet = workbook.createSheet("ticket_types");

        Row contactNameRow = formSheet.getRow(0);
        Row contactEmailRow = formSheet.getRow(1);
        Row contactPhoneRow = formSheet.getRow(2);
        Row registrationReferenceRow = formSheet.getRow(3);

        String[] ticketTypes = formatTicketTypes(signUp);
        addTicketTypesToSheet(ticketTypes, ticketTypeSheet);

        contactNameRow.createCell(1).setCellValue(form.getContactName());
        contactEmailRow.createCell(1).setCellValue(form.getContactEmailAddress());
        contactPhoneRow.createCell(1).setCellValue(form.getContactPhoneNumber());
        registrationReferenceRow.createCell(1).setCellValue(UUID.randomUUID().toString());

        createTicketTypeDropDown(formSheet, ticketTypeSheet, ticketTypes);

        model.setView(new BulkRegistrationFormView(workbook,
                form.getContactName().replace(" ", "_") + "RegistrationFile.xlsx"));
    } else {//from  ww w .  j a  va  2 s . c  o  m
        model.setViewName("/admin/group-registration");
    }
    return model;
}

From source file:com.azprogrammer.qgf.controllers.HomeController.java

@RequestMapping(value = "/whiteboard")
public ModelAndView doWhiteboard(ModelMap model, HttpServletRequest req, String wbId) {

    ModelAndView mav = new ModelAndView();
    mav.addAllObjects(model);/* ww w . j  a va 2s.  c o m*/
    PersistenceManager pm = getPM();
    HttpSession session = req.getSession();
    WhiteBoard wb = null;
    List<WBMessage> messages = null;

    if ((wbId == null) || ("".equals(wbId))) {
        wbId = req.getParameter("wb");
    }

    if ((wbId != null) && (!"".equals(wbId.trim()))) {
        wbId = cleanupWbId(wbId);
        try {
            Key key = KeyFactory.stringToKey(wbId);
            wb = pm.getObjectById(WhiteBoard.class, key);
            //String query = "select from " + WBMessage.class.getName() + " where wbKey == KEY('" + wbId + "')";

            Query query = pm.newQuery(WBMessage.class, "this.wbKey == key");
            query.declareParameters("com.google.appengine.api.datastore.Key key");
            query.setOrdering("creationTime asc");
            //Collection result = (Collection)query.execute(date);

            messages = (List<WBMessage>) query.execute(key);// pm.newQuery(query).execute();

        } catch (Exception e) {
            model.put("errorMsg", e.getMessage());
        }
    } else {
        wb = new WhiteBoard();
        wb.setCreatedBySessionId(req.getSession().getId());
        wb.setCreationDate(new Date());
        wb.setReferer(req.getHeader("referer"));
        wb.setUserAgent(req.getHeader("user-agent"));
        pm.makePersistent(wb);

        ExternalRedirectView rv = new ExternalRedirectView(
                "/whiteboard/" + KeyFactory.keyToString(wb.getKey()));
        mav.setView(rv);
        return mav;

    }

    ChannelService channelService = ChannelServiceFactory.getChannelService();

    if (wb == null) {
        mav.setViewName("badWbId");
        return mav;
    }

    if (messages == null) {
        messages = new ArrayList<WBMessage>();
    }

    //don't need key data in JSON
    JsonConfig jsconfig = new JsonConfig();
    String[] exlcudes = new String[] { "key", "wbKey", "userList", "shapeId" };
    jsconfig.setExcludes(exlcudes);
    HashMap<String, Object> messagesMap = new HashMap<String, Object>();
    messagesMap.put("messages", messages);
    model.put("messageMapJSON", JSONObject.fromObject(messagesMap, jsconfig).toString());

    String wbKeyStr = KeyFactory.keyToString(wb.getKey());

    Object userNameObj = req.getSession().getAttribute("userName");
    String userName = null;
    if (userNameObj != null) {
        userName = userNameObj.toString();
        WBChannel wbc = null;
        try {
            //String query = "select from " + WBChannel.class.getName() + " where sessionId == '" + session.getId () + "' && wbKey == '" + wbKeyStr + "'";
            //List<WBChannel> channels = (List<WBChannel>) pm.newQuery(query).execute();

            Query query = pm.newQuery(WBChannel.class, "this.wbKey == key && this.sessionId == sessId");
            query.declareParameters("com.google.appengine.api.datastore.Key key, String sessId");

            List<WBChannel> channels = (List<WBChannel>) query.execute(wb.getKey(), session.getId());// pm.newQuery(query).execute();

            if ((channels != null) && (channels.size() > 0)) {
                wbc = channels.get(0);
                Transaction tx = pm.currentTransaction();
                tx.begin();
                wbc.setTime(System.currentTimeMillis());
                tx.commit();
            }
        } catch (Exception e) {

        }

        if (wbc == null) {
            wbc = new WBChannel();
            wbc.setSessionId(session.getId());
            wbc.setWbKey(wb.getKey());
            wbc.setUserName(userName);
            wbc.setTime(System.currentTimeMillis());
            wbc.setUserAgent(req.getHeader("user-agent"));
            pm.makePersistent(wbc);
        }

        pushNewUserList(wbId);

        model.put("userName", userName);
        String token = channelService.createChannel(session.getId());
        model.put("token", token);
    }

    model.put("wbId", wbKeyStr);
    if (WebUtil.isMobile(req)) {
        model.put("mobileTheme", WebUtil.getMobileTheme(req));
        mav.setViewName("mobileboard");
    } else {
        mav.setViewName("whiteboard");
    }
    return mav;
}

From source file:org.shareok.data.webserv.JournalDataController.java

@RequestMapping(value = "/dspace/safpackage/doi/generate", method = RequestMethod.POST)
public ModelAndView safPackageGenerateByDois(HttpServletRequest request, RedirectAttributes redirectAttrs,
        @RequestParam(value = "multiDoiUploadFile", required = false) MultipartFile file) {
    String singleDoi = (String) request.getParameter("singleDoi");
    String multiDoi = (String) request.getParameter("multiDoi");
    String safPaths = null;/*from   w w w  .  j ava 2  s  .  co  m*/
    ByteArrayInputStream stream = null;

    ModelAndView model = new ModelAndView();
    RedirectView view = new RedirectView();
    view.setContextRelative(true);

    if ((null != file && !file.isEmpty()) || null != singleDoi || null != multiDoi) {
        String safFilePath = null;
        try {
            String[] dois;
            if (null != singleDoi) {
                String doi = (String) request.getParameter("doiInput");
                if (null == doi || doi.equals("")) {
                    throw new EmptyDoiInformationException("Empty information from single DOI submission!");
                }
                dois = new String[] { doi };
            } else if (null != multiDoi) {
                String doi = (String) request.getParameter("multiDoiInput");
                if (null == doi || doi.equals("")) {
                    throw new EmptyDoiInformationException("Empty information from multiple DOI submission!");
                }
                dois = doi.trim().split("\\s*;\\s*");
            } else if (null != file && !file.isEmpty()) {
                stream = new ByteArrayInputStream(file.getBytes());
                String doiString = IOUtils.toString(stream, "UTF-8");
                dois = doiString.trim().split("\\s*\\r?\\n\\s*");
            } else {
                throw new EmptyDoiInformationException("Empty DOI information from unknown DOI submission!");
            }
            if (dois != null && dois.length > 0) {

            }
        } catch (Exception ex) {
            logger.error("Cannot generate the SAF packages by the DOIs", ex);
        } finally {
            if (null != stream) {
                try {
                    stream.close();
                } catch (IOException ex) {
                    logger.error("Cannot close the input stream when reading the file containing the DOIs", ex);
                }
            }
        }
        if (null != safFilePath && !safFilePath.equals("")) {
            redirectAttrs.addFlashAttribute("safFilePath", safFilePath);
            view.setUrl(".jsp");
            model.setView(view);
        } else {
            redirectAttrs.addFlashAttribute("errorMessage", "The saf file path is invalid");
            view.setUrl("journalDataUpload.jsp");
            model.setView(view);
        }
    } else {
        redirectAttrs.addFlashAttribute("errorMessage", "The server information is empty");
        view.setUrl("errors/serverError.jsp");
        model.setView(view);
    }
    return model;
}

From source file:org.shareok.data.webserv.UserController.java

@RequestMapping("/user/newPass")
public ModelAndView userNewPass(HttpServletRequest request) {

    ModelAndView model = new ModelAndView();

    String oldPass = (String) request.getParameter("oldPass");
    String newPass = (String) request.getParameter("newPass");
    String newPassConfirm = (String) request.getParameter("newPassConfirm");
    if (null != oldPass && !oldPass.equals("") && null != newPass && !newPass.equals("")
            && null != newPassConfirm && !newPassConfirm.equals("")) {
        if (!newPass.equals(newPassConfirm)) {
            try {
                throw new IncorrectUserCredentialInfoException("The two new passwords do not match!");
            } catch (IncorrectUserCredentialInfoException ex) {
                logger.error(ex);/*ww  w  .ja va  2 s.  c om*/
                model.addObject("errorMessage", "The two new passwords do not match!");
                model.setViewName("userError");
                return model;
            }
        }
        String email = (String) request.getSession().getAttribute("email");
        RedisUser user = userService.findUserByUserEmail(email);
        if (null == user || !pwAuthenService.authenticate(oldPass, user.getPassword())) {
            String message = null;
            try {
                if (null == user) {
                    message = "User information cannot by found by user email!";
                } else {
                    message = "User old password is incorrect!";
                }
                throw new UserRegisterInfoNotFoundException(message);
            } catch (UserRegisterInfoNotFoundException ex) {
                logger.error(ex);
                model.addObject("errorMessage", message);
                model.setViewName("userError");
                return model;
            }
        }
        // Check if the user is the current user in session
        String sessionId = (String) request.getSession().getId();
        String userSessionId = user.getSessionKey();
        if (null == userSessionId || !userSessionId.equals(sessionId)) {
            try {
                throw new UserRegisterInfoNotFoundException(
                        "The user session ID does not match the current session ID!");
            } catch (UserRegisterInfoNotFoundException ex) {
                logger.error(ex);
                model.addObject("errorMessage", "The user session ID does not match the current session ID!");
                model.setViewName("userError");
                return model;
            }
        }
        String password = pwAuthenService.hash(newPass);
        user.setPassword(password);
        userService.updateUser(user);
        RedirectView view = new RedirectView();
        view.setContextRelative(true);
        view.setUrl("/userProfile");
        model.setView(view);
        return model;
    } else {
        try {
            throw new IncorrectUserCredentialInfoException(
                    "Some password information is empty for resetting user password!");
        } catch (IncorrectUserCredentialInfoException ex) {
            logger.error(ex);
            model.addObject("errorMessage", "Some password information is empty for resetting user password!");
            model.setViewName("userError");
        }
    }
    return model;
}

From source file:org.shareok.data.webserv.RestDspaceDataController.java

@RequestMapping(value = "/rest/{repoTypeStr}/{jobType}", method = RequestMethod.POST)
public ModelAndView sshDspaceSaFImporter(HttpServletRequest request, RedirectAttributes redirectAttrs,
        @PathVariable("repoTypeStr") String repoTypeStr,
        @RequestParam(value = "localFile", required = false) MultipartFile file,
        @PathVariable("jobType") String jobType, @ModelAttribute("SpringWeb") DspaceApiJob job) {
    ModelAndView model = new ModelAndView();

    String filePath = "";

    logger.debug("Start to process the DSpace Rest API request...");

    try {/*  w ww  .ja v a 2 s  .  com*/
        if (null == file || file.isEmpty()) {
            String localFile = (String) request.getParameter("localFile");
            if (!DocumentProcessorUtil.isEmptyString(localFile)) {
                filePath = localFile;
                String safDir = (String) request.getParameter("localSafDir");
                if (!DocumentProcessorUtil.isEmptyString(safDir)) {
                    filePath = safDir + File.separator + filePath;
                }
                String folder = (String) request.getParameter("localFolder");
                if (!DocumentProcessorUtil.isEmptyString(folder)) {
                    filePath = folder + File.separator + filePath;
                }
                String journalSearch = (String) request.getParameter("journalSearch");
                if (null != journalSearch && journalSearch.equals("1")) {
                    filePath = ShareokdataManager.getDspaceUploadPath() + File.separator + filePath;
                } else {
                    filePath = ShareokdataManager.getOuhistoryUploadPath() + File.separator + filePath;
                }
            } else {
                filePath = (String) request.getParameter("remoteFileUri");
            }
        } else {
            filePath = ServiceUtil.saveUploadedFile(file,
                    ShareokdataManager.getDspaceRestImportPath(jobType + "-" + repoTypeStr));
        }
    } catch (Exception ex) {
        logger.error("Cannot upload the file for DSpace import using REST API.", ex);
        model.addObject("errorMessage", "Cannot get the server list");
        model.setViewName("serverError");
        return model;
    }

    DspaceRepoServer server = (DspaceRepoServer) serverService.findServerById(job.getServerId());
    String userId = String.valueOf(request.getSession().getAttribute("userId"));
    job.setUserId(Long.valueOf(userId));
    job.setCollectionId(server.getPrefix() + "/" + job.getCollectionId());
    job.setRepoType(DataUtil.getRepoTypeIndex(repoTypeStr));
    job.setType(DataUtil.getJobTypeIndex(jobType, repoTypeStr));
    job.setStatus(Arrays.asList(RedisUtil.REDIS_JOB_STATUS).indexOf("created"));
    job.setFilePath(filePath);
    job.setStartTime(new Date());
    job.setEndTime(null);

    try {
        RedisJob returnedJob = taskManager.execute(job);

        if (null == returnedJob) {
            throw new JobProcessingException("Null job object returned after processing!");
        }

        int statusIndex = job.getStatus();
        String isFinished = (statusIndex == 2 || statusIndex == 6) ? "true" : "false";

        RedirectView view = new RedirectView();
        view.setContextRelative(true);
        view.setUrl("/report/job/" + String.valueOf(returnedJob.getJobId()));
        model.setView(view);
        redirectAttrs.addFlashAttribute("host",
                serverService.findServerById(returnedJob.getServerId()).getHost());
        redirectAttrs.addFlashAttribute("collection",
                DspaceDataUtil.DSPACE_REPOSITORY_HANDLER_ID_PREFIX + job.getCollectionId());
        redirectAttrs.addFlashAttribute("isFinished", isFinished);
        redirectAttrs.addFlashAttribute("reportPath", DataHandlersUtil
                .getJobReportFilePath(DataUtil.JOB_TYPES[returnedJob.getType()], returnedJob.getJobId()));
        WebUtil.outputJobInfoToModel(redirectAttrs, returnedJob);
    } catch (Exception ex) {
        logger.error("Cannot process the job of DSpace import using REST API.", ex);
        model.addObject("errorMessage", "Cannot process the job of DSpace import using REST API.");
        model.setViewName("serverError");
    }
    return model;
}

From source file:org.alfresco.wcm.client.exceptionresolver.RepositoryExceptionResolver.java

@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
    // Log the exception
    if (!(ex instanceof RepositoryUnavailableException)) {
        // Don't bother to log these for every request. It will be logged 
        // by GuestSessionFactoryImpl. 
        log.error(ex, ex);//from   w w w.j  a  va 2  s.c o m
    }

    // Determine the http status code from the exception
    Integer statusCode;
    if (ex instanceof PageNotFoundException) {
        statusCode = HttpStatus.NOT_FOUND.value();
    } else {
        statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
    }

    // Get the current website from the request
    RequestContext requestContext = ThreadLocalRequestContext.getRequestContext();
    if (requestContext != null) {
        Section rootSection = (Section) requestContext.getValue("rootSection");
        if (rootSection != null) {
            // Determine the error page asset name and fetch it from the
            // repository
            String errorPage = statusCode + errorPageSuffix + ".html";

            Asset errorAsset = rootSection.getAsset(errorPage);

            String template = null;
            if (errorAsset != null) {
                // A generic Surf error page will be used with the
                // repository asset html inserted within it.
                template = "errorpage";
            } else {
                // If no asset exists in the repository for the status code
                // then look for a specific Surf page.
                String pageName = statusCode + errorPageSuffix;
                if (lookupPage(pageName) != null) {
                    template = pageName;
                }
            }

            // If there is an editorially configured error page or a
            // specific Surf one then use it
            if (template != null) {
                // Apply HTTP status code for error views.
                // Only apply it if we're processing a top-level request.
                applyStatusCodeIfPossible(request, response, statusCode);

                PageView view = new PageView(requestContext.getServiceRegistry());
                view.setPage(lookupPage(template));
                view.setUrl(template);

                ModelAndView mv = new ModelAndView();
                mv.setView(view);

                // Store website, section and asset on spring model too for
                // use in page meta data
                // When exceptions are encountered a new model is created by
                // Spring so any data loaded
                // by the the controller interceptors is lost.
                try {
                    modelDecorator.populate(request, mv);
                } catch (Exception e) {
                    // ignore any errors on trying to populate the model
                }

                // Store error details on model
                mv.addObject("exception", ex);
                mv.addObject("errorAsset", errorAsset);
                return mv;
            }
        }
    }

    // If we couldn't determine an editorially configured error page or a
    // specific Surf one
    // then use a static page
    return super.doResolveException(request, response, handler, ex);
}

From source file:org.ambraproject.wombat.controller.SearchController.java

private ModelAndView getFeedModelAndView(Site site, String feedType, String title,
        Map<String, ?> searchResults) {
    ModelAndView mav = new ModelAndView();
    FeedMetadataField.SITE.putInto(mav, site);
    FeedMetadataField.FEED_INPUT.putInto(mav, searchResults.get("docs"));
    FeedMetadataField.TITLE.putInto(mav, title);
    mav.setView(FeedType.getView(articleFeedView, feedType));
    return mav;//  w w w. ja  v a2  s  . co m
}