Example usage for org.springframework.ui ModelMap ModelMap

List of usage examples for org.springframework.ui ModelMap ModelMap

Introduction

In this page you can find the example usage for org.springframework.ui ModelMap ModelMap.

Prototype

public ModelMap() 

Source Link

Document

Construct a new, empty ModelMap .

Usage

From source file:com.virtusa.akura.student.controller.StudentClassController.java

/**
 * handle POST requests for StudentClass view with data.
 * //from  ww  w .j a va 2 s  .  co  m
 * @param request - HttpServletRequest
 * @return the name of the view.
 * @throws AkuraException throws when exception occurs.
 */
@RequestMapping(value = ACTION_FOR_SEARCH_STUDENT, method = RequestMethod.POST)
public ModelAndView searchStudentByGradeYear(HttpServletRequest request) throws AkuraException {

    String grade = request.getParameter(PARAM_NAME_SELECTED_GRADE);
    String year = request.getParameter(PARAM_NAME_SELECTED_YEAR);
    Map<String, Object> finalMap = new TreeMap<String, Object>();
    ModelMap modelMap = new ModelMap();
    Grade gradeObj = null;
    int intYear = 0;
    if (grade != null && !grade.equals("") && !grade.equals(PARAM_NAME_FOR_NEW_STUDENTS)) {
        int intGrade = Integer.parseInt(grade);
        gradeObj = commonService.findGradeById(intGrade);
    }
    if (year != null && !year.equals("")) {
        intYear = Integer.parseInt(year);

        if (intYear > 0) {
            modelMap.addAttribute(PARAM_NAME_SELECTED_YEAR, intYear);
        }
    }
    if (gradeObj != null) {
        modelMap.addAttribute(MODEL_GRADE_ID, gradeObj.getGradeId());

    }

    if (grade.equals(PARAM_NAME_FOR_NEW_STUDENTS)) {
        modelMap.addAttribute(PARAM_NAME_FOR_NEW_STUDENTS, Boolean.TRUE);
    }

    // starts validations
    if (!grade.equals("") && !year.equals("")) {

        if (grade.equals(PARAM_NAME_FOR_NEW_STUDENTS)) {
            List<Object> studentList = studentService.getNewStudentForYear(intYear);
            finalMap.put(EMPTY, new TreeList(studentList));

            // if the students list is empty set the error message.
            if (studentList.isEmpty()) {
                modelMap.addAttribute(ERROR_MESSAGE,
                        new ErrorMsgLoader().getErrorMessage(REF_UI_STUDENT_CLASS_NEW_STUDENT_NODATA));
            }
        } else {
            modelMap.addAttribute(MODEL_GRADE, gradeObj.getDescription());

            finalMap = this.getStudentListWithCurrentAllocation(intYear, gradeObj);

            // if the students list is empty set the error message.
            if (finalMap.values().isEmpty()) {
                modelMap.addAttribute(ERROR_MESSAGE,
                        new ErrorMsgLoader().getErrorMessage(REF_UI_STUDENT_CLASS_STUDENT_NODATA));
            }
        }

    } else {
        // error message
        String message = new ErrorMsgLoader().getErrorMessage(MANDATORY_FIELD_ERROR_CODE);
        modelMap.addAttribute(MESSAGE, message);
    }

    modelMap.addAttribute(MODEL_LAST_LIST, finalMap);
    return new ModelAndView(VIEW_STUDENT_CLASS_PAGE, modelMap);
}

From source file:org.esupportail.portlet.filemanager.portlet.PortletControllerAjax.java

@ResourceMapping("createFile")
public ModelAndView createFile(String parentDir, String title, String type, ResourceRequest request,
        ResourceResponse response) {//  www .  j a v  a  2s. c om
    String parentDirDecoded = pathEncodingUtils.decodeDir(parentDir);
    String fileDir = this.serverAccess.createFile(parentDirDecoded, title, type, userParameters);
    if (fileDir != null) {
        return this.fileTree(parentDir, null, request, response);
    }

    //Added for GIP Recia : Error handling 
    //Usually a duplicate name problem.  Tell the ajax handler that
    //there is a problem and send the translated error message
    Locale locale = request.getLocale();
    ModelMap modelMap = new ModelMap();
    modelMap.put("errorText", context.getMessage("ajax.fileOrFolderCreate.failed", null, locale));
    return new ModelAndView("ajax_error", modelMap);
}

From source file:org.esupportail.dining.web.controllers.ViewController.java

@RequestMapping("/dish")
public ModelAndView renderDish(@RequestParam(value = "name", required = true) String name,
        @RequestParam(value = "ingredients", required = false) String ingredients,
        @RequestParam(value = "nutritionitems", required = false) String nutritionitems,
        @RequestParam(value = "code", required = false) String code,
        @RequestParam(value = "id", required = true) int id) throws Exception {

    User user = this.authenticator.getUser();
    ModelMap model = new ModelMap();

    model.put("restaurantId", id);
    model.put("name", name);
    model.put("ingredients", ingredients);
    model.put("code", code.substring(1, code.length() - 1).split(","));

    /* Awful code starts now */
    // Need to find an other solution... a cleaner one.

    String str = nutritionitems.substring(1, nutritionitems.length() - 1);
    List<Map<String, String>> listNutritionItems = new ArrayList<Map<String, String>>();
    Pattern p = Pattern.compile("\\[(.*?)\\]");
    Matcher m = p.matcher(str);// w w w .j  ava  2s. com
    while (m.find()) {
        Map<String, String> entry = new HashMap<String, String>();
        for (String s2 : m.group(1).split(",")) {
            String[] keyValue = s2.split("=");
            entry.put(keyValue[0], keyValue[1]);
        }
        listNutritionItems.add(entry);
    }

    /* Awful code ends now */

    model.put("nutritionitems", listNutritionItems);

    try {

        ResultSet prefUser = this.dc
                .executeQuery("SELECT NUTRITIONCODE FROM nutritionPreferences WHERE USERNAME='"
                        + StringEscapeUtils.escapeSql(user.getLogin()) + "';");
        Set<String> nutritionPrefs = new HashSet<String>();

        while (prefUser.next()) {
            nutritionPrefs.add(prefUser.getString("NUTRITIONCODE"));
        }

        model.put("nutritionPrefs", nutritionPrefs);

    } catch (SQLException e) { /**/
    } catch (NullPointerException e) { /*
                                       * Useful is the user isn't logged
                                       * in
                                       */
    }

    return new ModelAndView("dish", model);
}

From source file:se.vgregion.portal.iframe.controller.CSViewControllerTest.java

@Test
public void testShowView_WindowStateMaximized() throws ReadOnlyException {
    PortletPreferences prefs = new MockPortletPreferences();
    initPortletPreferences(prefs);//from w ww  .  j  av a 2 s.  co  m
    prefs.setValue("src", "http://www.google.com");
    prefs.setValue("auth", "true");
    prefs.setValue("auth-type", "form");
    prefs.setValue("site-key", "test-site-key");

    MockRenderRequest mockReq = new MockRenderRequest(PortletMode.VIEW);
    mockReq = (MockRenderRequest) initPortletRequest(mockReq);

    MockRenderResponse mockResp = new TestStubMockRenderResponse();
    mockResp.createResourceURL();

    ModelMap model = new ModelMap();

    // NORMAL
    mockReq.setWindowState(WindowState.NORMAL);
    controller.showView(prefs, mockReq, mockResp, model);
    assertEquals("300", model.get("iFrameHeight"));

    // MAXIMIZED
    mockReq.setWindowState(WindowState.MAXIMIZED);
    controller.showView(prefs, mockReq, mockResp, model);
    assertEquals("600", model.get("iFrameHeight"));
}

From source file:org.ngrinder.perftest.controller.PerfTestControllerTest.java

@Test
public void testGetReportData() {
    String testName = "test1";
    PerfTest test = createPerfTest(testName, Status.FINISHED, new Date());
    ModelMap model = new ModelMap();
    controller.getReport(model, test.getId());

    model.clear();// w ww .j av a  2s .  co m
    controller.getPerfGraph(test.getId(), "TPS,mean_time(ms)", true, 0);

    model.clear();
    controller.getReportSection(getTestUser(), model, test.getId(), 700);
}

From source file:fragment.web.AbstractConnectorControllerTest.java

@Test
public void testSaveInstanceWithoutCode() throws Exception {
    map = new ModelMap();
    String classType = "com.citrix.cpbm.platform.spi.CloudServiceConnector";
    String filter = "(org.springframework.osgi.bean.name=OsgiServiceRef1)";
    prepareMock(classType, filter, true);
    String configProperties = "[{\"name\":\"instancename\",\"value\":\"MyCPIN\"},{\"name\":\"instancedescription\",\"value\":\"Test\"},{\"name\":\"country\",\"value\":\"India\"},{\"name\":\"password\",\"value\":\"password\"},{\"name\":\"accountid\",\"value\":\"456783\"},{\"name\":\"username\",\"value\":\"cpbm\"},{\"name\":\"endpoint\",\"value\":\"http://google.com\"}]";
    map = controller.saveInstance("b1c9fbb0-8dab-42dc-ae0a-ce1384a1e6", "add", configProperties, null, map,
            new MockHttpServletRequest());
    EasyMock.reset(mockServiceRef, bc);/* w  w w . j a  v  a  2s. co m*/
}

From source file:org.esupportail.portlet.filemanager.portlet.PortletControllerAjax.java

@ResourceMapping("renameFile")
public ModelAndView renameFile(String parentDir, String dir, String title, ResourceRequest request,
        ResourceResponse response) {/*  w  w  w  .  j  a  v  a2  s.  c  o  m*/
    parentDir = pathEncodingUtils.decodeDir(parentDir);
    dir = pathEncodingUtils.decodeDir(dir);
    if (this.serverAccess.renameFile(dir, title, userParameters)) {
        return this.fileTree(pathEncodingUtils.encodeDir(parentDir), null, request, response);
    }

    //Usually means file does not exist
    Locale locale = request.getLocale();
    ModelMap modelMap = new ModelMap();
    modelMap.put("errorText", context.getMessage("ajax.rename.failed", null, locale));
    return new ModelAndView("ajax_error", modelMap);
}

From source file:com.trenako.web.controllers.RollingStocksControllerTests.java

@Test
public void shouldRedirectAfterValidationErrorsDuringSave() {
    when(mockResult.hasErrors()).thenReturn(true);
    RollingStockForm form = rsForm(null);
    ModelMap model = new ModelMap();

    String viewName = controller.save(form, mockResult, model, mockRedirect);

    assertEquals("rollingstock/edit", viewName);
    assertNotNull("Form is null", model.get("rollingStockForm"));
}

From source file:fragment.web.AbstractManageResourceControllerTest.java

/**
 * @author Abhaik/*from w  ww  .  ja  v  a  2  s. co  m*/
 * @description : Test to get the SSO Cmd for a New Tenant through the same Tenant only
 */
@Test
public void testSSOFromSelfForNewTenant() {

    setSSOHandler();
    Tenant tenant = createTestTenant(accountTypeDAO.getDefaultRegistrationAccountType());
    User user = tenant.getOwner();
    asUser(user);
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    map = new ModelMap();
    ServiceInstance instance = serviceInstanceDao.find(1L);
    request.setAttribute("effectiveTenant", tenant);
    request.setAttribute("isSurrogatedTenant", isSurrogatedTenant(tenant, tenant.getParam()));

    Map<String, String> resultMap = controller.getSSOCmdString(tenant, tenant.getParam(), instance.getUuid(),
            map, request, response);
    Assert.assertNotNull(resultMap);

    String status = resultMap.get("status");
    Assert.assertEquals("fail", status);

    String cmdString = resultMap.get("cmdString");
    Assert.assertNull("Tenant is New State", cmdString);

    String url = resultMap.get("url");
    Assert.assertEquals("/portal/portal/tenants/editcurrent", url);

}

From source file:com.virtusa.akura.student.controller.StudentSearchController.java

/**
 * This method handles the GET requests for Student_search view.
 * It returns a List of {@link Object} objects.
 * /*from   w w w .  j ava  2s  . c om*/
 * @param criteria - StudentSearchCritiria
 * @param request - HttpServletRequest.
 * @param model - ModelMap.
 * @param session - HttpSession
 * @return ModelAndView.
 * @throws AkuraAppException AkuraAppException.
 */
@RequestMapping(REQ_MAP_VALUE_SEARCH)
public ModelAndView studentSearch(@ModelAttribute(CRITIRIA) StudentSearchCritiria criteria,
        final HttpServletRequest request, ModelMap model, final HttpSession session) throws AkuraAppException {

    String actionType = request.getParameter(ACTION_TYPE);
    String strFrom = request.getParameter(START_FROM);
    int startFrom = Integer.parseInt(strFrom == null ? AkuraWebConstant.STRING_ZERO : strFrom);
    int year = Calendar.getInstance().get(Calendar.YEAR);
    model.addAttribute(YEAR_STRING, year);
    criteria.setStartFrom(startFrom);

    int numberOfRecords;

    UserInfo userInfo = null;
    if (session.getAttribute(USER_STRING) != null) {
        userInfo = (UserInfo) session.getAttribute(USER_STRING);
    }

    int logginUserRoleId = userInfo != null ? userInfo.getUserRoleId() : 0;

    DateFormat dateFormat = new SimpleDateFormat(YEAR_PATTERN);
    DateFormat lastDateFormat = new SimpleDateFormat(LAST_DAY_OF_YEAR_PATTERN);
    Date date = new Date();

    try {
        model.addAttribute(CURRENT_DATE_STRING, DateUtil.convertStringToDate(dateFormat.format(date)));
        model.addAttribute(LAST_DATE_OF_YEAR_PATTERN,
                DateUtil.convertStringToDate(lastDateFormat.format(date)));
    } catch (ParseException e) {

        e.printStackTrace();
    }
    model.addAttribute(USER_ID_STRING, logginUserRoleId);

    if (SEARCH.equals(actionType)) {

        model.addAttribute(ACTION_TYPE, SEARCH);

        if (!criteria.getGrade().equals(AkuraWebConstant.STRING_ZERO)) {
            criteria.setYear(year);
        } else {
            criteria.setGrade(AkuraWebConstant.EMPTY_STRING);
        }
        if (criteria.getGrade().equals(NEW)) {
            model.addAttribute(IS_SELECT_NEW, BOOLEAN_VALUE_TRUE);
        }

        studentList = studentService.studentSearch(criteria);

    } else if (ADVANCED_SEARCH.equals(actionType)) {

        model.addAttribute(ACTION_TYPE, ADVANCED_SEARCH);

        if (criteria.getClazzId() == 0 && criteria.getSportId() == 0 && criteria.getSubjectId() == 0
                && criteria.getPrefectTypeId() == 0 && criteria.getWorkingSegmentId() == 0) {

            String message = new ErrorMsgLoader().getErrorMessage(STUDENT_ADVANCE_SEARCH_ERR);

            model.addAttribute(SHOW_EDIT_SECTION, SHOW_EDIT_SECTION);
            model.addAttribute(CRITIRIA, criteria);
            model.addAttribute(NOCRITERIA, message);
            return new ModelAndView(VIEW_GET_STUDENT_SEARCH_PAGE, model);
        }

        criteria.setYear(year);
        studentList = studentService.studentAdvanceSearch(criteria);

        // show the advanced search section if it returns no results.
        model.addAttribute(SHOW_EDIT_SECTION, SHOW_EDIT_SECTION);
    }
    numberOfRecords = studentList.size();
    int maxNumber = startFrom + AkuraConstant.PARAM_INDEX_TEN;
    criteria.setMaxNumber(maxNumber);

    List<?> searchReultsForPage = studentList;
    ModelMap modelMap = new ModelMap();

    if (searchReultsForPage.isEmpty()) {
        modelMap.addAttribute(STUDENT_LIST, EMPTY);
    } else {
        modelMap.addAttribute(STUDENT_LIST, searchReultsForPage);
    }

    modelMap.addAttribute(NUMBER_OF_RECORDS, numberOfRecords);
    modelMap.addAttribute(CRITIRIA, criteria);

    return new ModelAndView(VIEW_GET_STUDENT_SEARCH_PAGE, modelMap);
}