Java Code Examples for org.springframework.ui.Model#asMap()

The following examples show how to use org.springframework.ui.Model#asMap() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void givenZOSMFProviderWithOneInstance_whenHomePageCalled_thenHomePageModelShouldContain() {
    ServiceInstance serviceInstance = new DefaultServiceInstance("instanceId", "serviceId",
        "host", 10000, true);
    when(discoveryClient.getInstances("zosmf")).thenReturn(
        Arrays.asList(serviceInstance)
    );

    authConfigurationProperties.setProvider("zosmf");
    authConfigurationProperties.setZosmfServiceId("zosmf");

    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("authIconName", "success"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("authStatusText", "The Authentication service is running"));
}
 
Example 2
Source File: BounceFilterController.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "/list.action")
public Pollable<ModelAndView> list(ComAdmin admin, HttpSession session, BounceFilterListForm form, Model model) {
    FormUtils.syncNumberOfRows(webStorage, ComWebStorage.BOUNCE_FILTER_OVERVIEW, form);

    PollingUid uid = PollingUid.builder(session.getId(), "bounceFilterList")
        .arguments(form.getSort(), form.getOrder(), form.getPage(), form.getNumberOfRows())
        .build();

    Callable<ModelAndView> worker = () -> {
        model.addAttribute("bounceFilterList",
                bounceFilterService.getPaginatedBounceFilterList(
                        admin,
                        form.getSort(),
                        form.getOrder(),
                        form.getPage(),
                        form.getNumberOfRows()));

        writeUserActivityLog(admin, "bounce filter list", "active submenu item - overview");

        return new ModelAndView("bounce_filter_list", model.asMap());
    };

    return new Pollable<>(uid, DEFAULT_TIMEOUT, new ModelAndView("redirect:/administration/bounce/list.action", model.asMap()), worker);
}
 
Example 3
Source File: GoodsController.java    From SecKillShop with MIT License 6 votes vote down vote up
@RequestMapping("/to_list")
@ResponseBody
public String toList(Model model, MiaoshaUser user, HttpServletRequest request, HttpServletResponse response) {
    model.addAttribute("user", user);
    //取缓存
    String html = redisService.get(GoodsKey.getGoodList, "", String.class);
    if (!StringUtils.isEmpty(html)) {
        return html;
    }
    List<GoodsVo> listGoodsVo = goodsService.listGoodsVo();
    model.addAttribute("listGoodsVo", listGoodsVo);

    WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
    html = thymeleafViewResolver.getTemplateEngine().process("goodlist", ctx);
    if (!StringUtils.isEmpty(html)) {
        redisService.set(GoodsKey.getGoodList, "", html);
    }
    return html;
}
 
Example 4
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenBuildVersionNull_whenHomePageCalled_thenBuildInfoShouldStaticText() {
    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("buildInfoText", "Build information is not available"));
}
 
Example 5
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenZOSMFProviderWithEmptyInstances_whenHomePageCalled_thenHomePageModelShouldContain() {
    when(discoveryClient.getInstances("zosmf")).thenReturn(Collections.EMPTY_LIST);

    authConfigurationProperties.setProvider("zosmf");
    authConfigurationProperties.setZosmfServiceId("zosmf");

    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("authIconName", "warning"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("authStatusText", "The Authentication service is not running"));
}
 
Example 6
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenZOSMFProviderWithNullInstances_whenHomePageCalled_thenHomePageModelShouldContain() {
    authConfigurationProperties.setProvider("zosmf");
    authConfigurationProperties.setZosmfServiceId("zosmf");

    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("authIconName", "warning"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("authStatusText", "The Authentication service is not running"));
}
 
Example 7
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenDummyProvider_whenHomePageCalled_thenHomePageModelShouldContain() {
    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("authIconName", "success"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("authStatusText", "The Authentication service is running"));
}
 
Example 8
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenDiscoveryServiceWithMoreThanOneInstance_whenHomePageCalled_thenHomePageModelShouldContain() {
    ServiceInstance serviceInstance = new DefaultServiceInstance("instanceId", "serviceId",
        "host", 10000, true);

    when(discoveryClient.getInstances("discovery")).thenReturn(Arrays.asList(serviceInstance, serviceInstance));

    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("discoveryIconName", "success"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("discoveryStatusText", "2 Discovery Service instances are running"));
}
 
Example 9
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenDiscoveryServiceWithOneInstance_whenHomePageCalled_thenHomePageModelShouldContain() {
    ServiceInstance serviceInstance = new DefaultServiceInstance("instanceId", "serviceId",
        "host", 10000, true);

    when(discoveryClient.getInstances("discovery")).thenReturn(Arrays.asList(serviceInstance));

    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("discoveryIconName", "success"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("discoveryStatusText", "The Discovery Service is running"));
}
 
Example 10
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenDiscoveryServiceWithEmptyInstances_whenHomePageCalled_thenHomePageModelShouldContain() {
    when(discoveryClient.getInstances("apicatalog")).thenReturn(Collections.EMPTY_LIST);

    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("discoveryIconName", "danger"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("discoveryStatusText", "The Discovery Service is not running"));
}
 
Example 11
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenDiscoveryServiceWithNullInstances_whenHomePageCalled_thenHomePageModelShouldContain() {
    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("discoveryIconName", "danger"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("discoveryStatusText", "The Discovery Service is not running"));
}
 
Example 12
Source File: WidgetStoreControllerTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Test
public void searchWidgets() {
    Model model = new ExtendedModelMap();

    String searchTerm = "gAdGet";

    int offset = 0;
    int pagesize = 10;
    int totalResults = 2;
    WidgetImpl widget = new WidgetImpl();
    widget.setId("1");
    List<Widget> widgets = new ArrayList<Widget>();
    widgets.add(widget);
    SearchResult<Widget> result = new SearchResult<Widget>(widgets, totalResults);
    result.setPageSize(pagesize);

    expect(widgetService.getPublishedWidgetsByFreeTextSearch(searchTerm, offset, pagesize)).andReturn(result);
    expect(widgetService.getAllWidgetStatistics(validUser.getId())).andReturn(allWidgetStatisticsMap);
    replay(widgetService);

    String view = controller.viewSearchResult(model, REFERRER_ID, searchTerm, offset);
    verify(widgetService);

    assertEquals(ViewNames.STORE, view);
    final Map<String, Object> modelMap = model.asMap();
    assertEquals(searchTerm, modelMap.get(ModelKeys.SEARCH_TERM));
    assertTrue(model.containsAttribute(ModelKeys.WIDGETS));
    assertThat(model.containsAttribute(ModelKeys.WIDGETS_STATISTICS), is(true));
    assertEquals(offset, modelMap.get(ModelKeys.OFFSET));
    assertEquals(result, modelMap.get(ModelKeys.WIDGETS));
    assertThat(model.containsAttribute(ModelKeys.TAGS), is(true));
    assertThat(model.containsAttribute(ModelKeys.CATEGORIES), is(true));

}
 
Example 13
Source File: BlacklistController.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@RequestMapping(value = "/list.action", method = {RequestMethod.GET, RequestMethod.POST})
public Pollable<ModelAndView> list(ComAdmin admin, HttpSession session, Model model,
                                   @ModelAttribute(BLACKLIST_LIST_FORM_KEY) BlacklistListForm listForm) {

    int companyId = admin.getCompanyID();
    String sessionId = session.getId();

    FormUtils.syncNumberOfRows(webStorage, ComWebStorage.BLACKLIST_OVERVIEW, listForm);

    PollingUid pollingUid = PollingUid.builder(sessionId, BLACKLISTS_DTO_KEY)
            .arguments(listForm.getSort(), listForm.getOrder(), listForm.getPage(), listForm.getNumberOfRows())
            .build();

    Callable<ModelAndView> worker = () -> {
        model.addAttribute(DATE_TIME_FORMAT_KEY, admin.getDateTimeFormat());
        model.addAttribute(BLACKLISTS_DTO_KEY,
                blacklistService.getAll(companyId,
                        listForm.getSort(),
                        listForm.getOrder(),
                        listForm.getPage(),
                        listForm.getNumberOfRows(),
                        listForm.getSearchQuery()));

        return new ModelAndView("settings_blacklist_list", model.asMap());
    };

    ModelAndView modelAndView = new ModelAndView("redirect:/recipients/blacklist/list.action", listForm.toMap());

    return new Pollable<>(pollingUid, Pollable.DEFAULT_TIMEOUT, modelAndView, worker);
}
 
Example 14
Source File: VetController.java    From enhanced-pet-clinic with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showVets(Model model) {
	return new ModelAndView("redirect:/vets/list.html", model.asMap());
}
 
Example 15
Source File: DefaultRendering.java    From spring-analysis-note with MIT License 4 votes vote down vote up
DefaultRendering(Object view, @Nullable Model model, @Nullable HttpStatus status, @Nullable HttpHeaders headers) {
	this.view = view;
	this.model = (model != null ? model.asMap() : Collections.emptyMap());
	this.status = status;
	this.headers = (headers != null ? headers : EMPTY_HEADERS);
}
 
Example 16
Source File: GoodsController.java    From goods-seckill with Apache License 2.0 4 votes vote down vote up
/**
	 * 商品列表展示
	 * 
	 * QPS: 500
	 * 
	 * 模拟:5000个并发 * 10次循环 = 50000个请求
	 * 
	 * 耗时:1分40秒
	 * 
	 * 分析:在并发访问过程中,数据库服务器CPU占用率达到了95%,负载最高到了3(mysql装在单核cpu的虚拟机上,内存1GB),
	 * 可见,并发访问中,造成QPS低的瓶颈在数据库。
	 * 
	 * 关于负载介绍: https://zhidao.baidu.com/question/186962244.html
	 * 
	 * @param model
	 * @param response
	 * @param miaoshaUserEntity
	 * @return
	 */
	@RequestMapping(value = "to_list", produces = "text/html")	// produces,指定返回thml页面
	@ResponseBody
	public String toList(
			Model model, HttpServletResponse response, HttpServletRequest request
//			@CookieValue(value = MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN, required = false) String cookieToken,
//			@RequestParam(value = MiaoshaUserServiceImpl.COOKIE_NAME_TOKEN, required = false) String paramToken
//			MiaoshaUserEntity miaoshaUserEntity
			) {

//		String token = null;
//
//		if (StringUtils.isEmpty(paramToken)) {
//			if (!StringUtils.isEmpty(cookieToken)) {
//				token = cookieToken;
//			}
//		} else {
//			token = paramToken;
//		}
////		
//		if (StringUtils.isEmpty(token)) {
//			return "/login";
//		}
//
//		MiaoshaUserEntity miaoshaUserEntity = miaoshaUserService.getByToken(token, response);
//
//		if (miaoshaUserEntity == null) {
//			return "/login";
//		}
//
//		model.addAttribute("user", miaoshaUserEntity);
		
		// 添加html页面缓存到redis,也就是redis中缓存已经被渲染好的html静态页面
		// -------------------------------------------------
		
		// 取缓存redis缓存中的thymeleaf渲染好的html页面
		String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
		if (!StringUtils.isEmpty(html)) {
			return html;
		}
		
		List<GoodsVo> list = goodsService.selectGoodsVoList();
		model.addAttribute("goodsList", list);
		
		// 手动渲染thymeleaf模板
		SpringWebContext swc = new SpringWebContext(request, response, request.getServletContext(), 
				request.getLocale(), model.asMap(), applicationContext);	// 将model中数据放到SpringWebContext
		SpringTemplateEngine templateEngine = thymeleafViewResolver.getTemplateEngine();	
		html = templateEngine.process("goods_list", swc);	// thymeleaf模板引擎手动渲染出html页面
//		if (!StringUtils.isEmpty(html)) {
//			redisService.set(GoodsKey.getGoodsList, "", html);	// 将渲染好的html页面放进缓存
//		}
		return html;
		
		// -------------------------------------------------
	}
 
Example 17
Source File: GoodsController.java    From SecKillShop with MIT License 4 votes vote down vote up
@RequestMapping("/details/{goodsId}")
@ResponseBody
public String goodsDetails(Model model, MiaoshaUser user, @PathVariable("goodsId") long id, HttpServletResponse response, HttpServletRequest request) {
    model.addAttribute("user", user);

    String html = redisService.get(GoodsKey.getGoodDetails, "" + id, String.class);
    if (!StringUtils.isEmpty(html)) {
        return html;
    }
    GoodsVo goodsVo = goodsService.getGoodsVoById(id);
    model.addAttribute("goodVo", goodsVo);

    //判断秒杀状态
    Long startDate = goodsVo.getStartDate().getTime();
    Long endData = goodsVo.getEndDate().getTime();
    Long now = System.currentTimeMillis();

    int miaoshaStatus = 0;
    int remainSeconds = 0;
    if (now < startDate) {
        miaoshaStatus = 0;
        remainSeconds = (int) ((startDate - now) / 1000);
    } else if (now > endData) {
        miaoshaStatus = 2;
        remainSeconds = -1;
    } else {
        miaoshaStatus = 1;
        remainSeconds = 0;
    }

    model.addAttribute("miaoshaStatus", miaoshaStatus);
    model.addAttribute("remainSeconds", remainSeconds);

    //加入到缓存中
    WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
    html = thymeleafViewResolver.getTemplateEngine().process("goods_details", ctx);

    if (!StringUtils.isEmpty(html)) {
        redisService.set(GoodsKey.getGoodDetails, "" + id, html);
    }
    return html;
}
 
Example 18
Source File: DefaultRendering.java    From java-technology-stack with MIT License 4 votes vote down vote up
DefaultRendering(Object view, @Nullable Model model, @Nullable HttpStatus status, @Nullable HttpHeaders headers) {
	this.view = view;
	this.model = (model != null ? model.asMap() : Collections.emptyMap());
	this.status = status;
	this.headers = (headers != null ? headers : EMPTY_HEADERS);
}
 
Example 19
Source File: UserActivityLogController.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@RequestMapping(value = "/list.action", method = {RequestMethod.GET, RequestMethod.POST})
public Pollable<ModelAndView> list(ComAdmin admin, UserActivityLogForm listForm, Model model, HttpSession session) {
    String sessionId = session.getId();
    DateTimeFormatter datePickerFormatter = admin.getDateFormatter();
    SimpleDateFormat localTableFormat = admin.getDateTimeFormat();

    FormUtils.syncNumberOfRows(webStorage, ComWebStorage.USERLOG_OVERVIEW, listForm);

    List<AdminEntry> admins = adminService.getAdminEntriesForUserActivityLog(admin);
    List<AdminEntry> adminsFilter = admin.permissionAllowed(Permission.MASTERLOG_SHOW) ? null : admins;

    model.addAttribute("userActions", Arrays.asList(UserActivityLogActions.values()));
    model.addAttribute("admins", admins);
    model.addAttribute("localeTableFormat", localTableFormat);
    AgnUtils.setAdminDateTimeFormatPatterns(admin, model);
    model.addAttribute("defaultDate", LocalDate.now().format(datePickerFormatter));

    LocalDate dateFrom = listForm.getDateFrom().get(LocalDate.now(), datePickerFormatter);
    LocalDate dateTo = listForm.getDateTo().get(LocalDate.now(), datePickerFormatter);

    Map<String, Object> argumentsMap = new HashMap<>();
    argumentsMap.put("sort", listForm.getSort());
    argumentsMap.put("order", listForm.getDir());
    argumentsMap.put("page", listForm.getPage());
    argumentsMap.put("numberOfRows", listForm.getNumberOfRows());
    argumentsMap.put("username", listForm.getUsername());
    argumentsMap.put("dateFrom.date", listForm.getDateFrom().getDate());
    argumentsMap.put("dateTo.date", listForm.getDateTo().getDate());
    argumentsMap.put("description", listForm.getDescription());

    PollingUid pollingUid = PollingUid.builder(sessionId, USER_ACTIVITY_LOG_KEY)
            .arguments(argumentsMap.values().toArray(ArrayUtils.EMPTY_OBJECT_ARRAY))
            .build();

    Callable<ModelAndView> worker = () -> {
        PaginatedListImpl<LoggedUserAction> loggedUserActions =
                userActivityLogService.getUserActivityLogByFilter(
                        admin,
                        listForm.getUsername(),
                        listForm.getUserAction(),
                        dateFrom,
                        dateTo,
                        listForm.getDescription(),
                        listForm.getPage(),
                        listForm.getNumberOfRows(),
                        listForm.getSort(),
                        listForm.getDir(),
                        adminsFilter);
        model.addAttribute(USER_ACTIVITY_LOG_KEY, loggedUserActions);

        return new ModelAndView("useractivitylog_list", model.asMap());
    };

    ModelAndView modelAndView = new ModelAndView("redirect:/administration/useractivitylog/list.action",
            argumentsMap);

    return new Pollable<>(pollingUid, Pollable.DEFAULT_TIMEOUT, modelAndView, worker);
}
 
Example 20
Source File: OwnerController.java    From enhanced-pet-clinic with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showOwners(Model model) {
	return new ModelAndView("redirect:/owners/list.html", model.asMap());
}