org.springframework.web.bind.annotation.CookieValue Java Examples

The following examples show how to use org.springframework.web.bind.annotation.CookieValue. 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: ReactAppController.java    From mojito with Apache License 2.0 6 votes vote down vote up
@RequestMapping({
    "/",
    "/login",
    "repositories",
    "project-requests",
    "workbench",
    "branches",
    "settings",
    "screenshots"
})
@ResponseBody
ModelAndView getIndex(
        HttpServletRequest httpServletRequest,
        @CookieValue(value = "locale", required = false, defaultValue = "en") String localeCookieValue) throws MalformedURLException, IOException {

    ModelAndView index = new ModelAndView("index");

    index.addObject("locale", getValidLocaleFromCookie(localeCookieValue));
    index.addObject("ict", httpServletRequest.getHeaders("X-Mojito-Ict").hasMoreElements());
    index.addObject("csrfToken", csrfTokenController.getCsrfToken(httpServletRequest));
    index.addObject("username", getUsername());
    index.addObject("contextPath", contextPath);
    index.addObject("appConfig", objectMapper.writeValueAsStringUnchecked(reactAppConfig));

    return index;
}
 
Example #2
Source File: HandlerMethodResolverWrapper.java    From summerframework with Apache License 2.0 6 votes vote down vote up
public static MethodParameter interfaceMethodParameter(MethodParameter parameter) {
    boolean hasAnnotations =
        parameter.hasParameterAnnotation(RequestParam.class) || parameter.hasParameterAnnotation(PathVariable.class)
            || parameter.hasParameterAnnotation(RequestHeader.class)
            || parameter.hasParameterAnnotation(CookieValue.class)
            || parameter.hasParameterAnnotation(RequestBody.class);
    if (!hasAnnotations) {
        for (Class<?> itf : parameter.getDeclaringClass().getInterfaces()) {
            try {
                Method method =
                    itf.getMethod(parameter.getMethod().getName(), parameter.getMethod().getParameterTypes());
                return new InterfaceMethodParameter(method, parameter.getParameterIndex());
            } catch (NoSuchMethodException e) {
                continue;
            }
        }
    }
    return parameter;
}
 
Example #3
Source File: DiskController.java    From lemon with Apache License 2.0 6 votes vote down vote up
/**
 * 详情.
 */
@RequestMapping("disk-view")
public String view(
        @RequestParam("id") Long id,
        @CookieValue(value = "share", required = false) String sharePassword,
        Model model) {
    DiskShare diskShare = diskShareManager.get(id);

    if ("private".equals(diskShare.getShareType())) {
        if (!diskShare.getSharePassword().equals(sharePassword)) {
            return "disk/disk-code";
        }
    }

    model.addAttribute("diskShare", diskShare);

    return "disk/disk-view";
}
 
Example #4
Source File: ErrorController.java    From LodView with MIT License 5 votes vote down vote up
@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE, reason = "unhandled encoding")
@RequestMapping(value = "/406")
public String error406(HttpServletResponse res, ModelMap model, @CookieValue(value = "colorPair") String colorPair) {
	System.out.println("not acceptable");
	model.addAttribute("statusCode", "406");
	model.addAttribute("conf", conf);
	colors(colorPair, res, model);
	res.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
	return "error";
}
 
Example #5
Source File: Portlet20AnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@RequestMapping("EDIT")
@RenderMapping
public void myHandle(@RequestParam("param1") String p1, @RequestParam("param2") int p2,
		@RequestHeader("header1") long h1, @CookieValue("cookie1") Cookie c1,
		RenderResponse response) throws IOException {
	response.getWriter().write("test-" + p1 + "-" + p2 + "-" + h1 + "-" + c1.getValue());
}
 
Example #6
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public void handle(@CookieValue("date") Date date, Writer writer) throws IOException {
	assertEquals("Invalid path variable value", new GregorianCalendar(2008, 10, 18).getTime(), date);
	Calendar c = new GregorianCalendar();
	c.setTime(date);
	writer.write("test-" + c.get(Calendar.YEAR));
}
 
Example #7
Source File: RequestMappingHandlerAdapterIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public String handle(
		@CookieValue("cookie") int cookieV,
		@PathVariable("pathvar") String pathvarV,
		@RequestHeader("header") String headerV,
		@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
		@RequestHeader Map<String, Object> headerMap,
		@RequestParam("dateParam") Date dateParam,
		@RequestParam Map<String, Object> paramMap,
		String paramByConvention,
		@Value("#{request.contextPath}") String value,
		@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
		Errors errors,
		TestBean modelAttrByConvention,
		Color customArg,
		HttpServletRequest request,
		HttpServletResponse response,
		@SessionAttribute TestBean sessionAttribute,
		@RequestAttribute TestBean requestAttribute,
		User user,
		@ModelAttribute OtherUser otherUser,
		Model model,
		UriComponentsBuilder builder) {

	model.addAttribute("cookie", cookieV).addAttribute("pathvar", pathvarV).addAttribute("header", headerV)
			.addAttribute("systemHeader", systemHeader).addAttribute("headerMap", headerMap)
			.addAttribute("dateParam", dateParam).addAttribute("paramMap", paramMap)
			.addAttribute("paramByConvention", paramByConvention).addAttribute("value", value)
			.addAttribute("customArg", customArg).addAttribute(user)
			.addAttribute("sessionAttribute", sessionAttribute)
			.addAttribute("requestAttribute", requestAttribute)
			.addAttribute("url", builder.path("/path").build().toUri());

	assertNotNull(request);
	assertNotNull(response);

	return "viewName";
}
 
Example #8
Source File: ErrorController.java    From LodView with MIT License 5 votes vote down vote up
@RequestMapping(value = "/404")
public String error404(HttpServletResponse res, ModelMap model, @RequestParam(value = "error", defaultValue = "") String error, @CookieValue(value = "colorPair", defaultValue = "") String colorPair, @RequestParam(value = "IRI", defaultValue = "") String IRI, @RequestParam(value = "endpoint", defaultValue = "") String endpoint) {
	System.out.println("not found " + error + " -- " + IRI + " -- " + endpoint);
	/* spring bug? */
	model.addAttribute("IRI", IRI);
	model.addAttribute("endpoint", endpoint);
	model.addAttribute("error", error);
	model.addAttribute("conf", conf);
	colors(colorPair, res, model);
	model.addAttribute("statusCode", "404");
	res.setStatus(HttpServletResponse.SC_NOT_FOUND);
	return "error";
}
 
Example #9
Source File: CookieValueMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public void params(
		@CookieValue("name") HttpCookie cookie,
		@CookieValue(name = "name", defaultValue = "bar") String cookieString,
		String stringParam,
		@CookieValue Mono<String> monoCookie) {
}
 
Example #10
Source File: LoginController.java    From MyCommunity with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                    @RequestParam("code") String code, @CookieValue("kaptchaOwner") String kaptchaOwner, Model model, HttpServletResponse response) {

    String kaptcha = null;
    if (StringUtils.isNotBlank(kaptchaOwner)){
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
    }

    if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)){
        model.addAttribute("codeMsg", "验证码不正确~");
        return "/site/login";
    }

    Map<String, Object> map = iUserService.login(username, password);
    if (map.containsKey("ticket")) {
        Cookie cookie = new Cookie("ticket", map.get(Const.ticket.TICKET).toString());
        cookie.setPath(contextPath);  // cookie 的生效范围
        cookie.setMaxAge(Const.loginStatus.DEFAULT_EXPIRED_SECONDS);
        response.addCookie(cookie);
        return "redirect:/index";
    }else {
        model.addAttribute("usernameMsg", map.get("usernameMsg"));
        model.addAttribute("passwordMsg", map.get("passwordMsg"));
        return "/site/login";
    }
}
 
Example #11
Source File: ResourceController.java    From LodView with MIT License 5 votes vote down vote up
@RequestMapping(value = { "{path:(?!staticResources).*$}", "{path:(?!staticResources).*$}/**" })
public Object resourceController(ModelMap model, HttpServletRequest req, HttpServletResponse res, Locale locale, @RequestParam(value = "output", defaultValue = "") String output, @CookieValue(value = "colorPair", defaultValue = "") String colorPair) throws UnsupportedEncodingException {
	if (colorPair.equals("")) {
		colorPair = conf.getRandomColorPair();
		Cookie c = new Cookie("colorPair", colorPair);
		c.setPath("/");
		res.addCookie(c);
	}
	return resource(conf, model, req, res, locale, output, "", colorPair);
}
 
Example #12
Source File: ErrorController.java    From LodView with MIT License 5 votes vote down vote up
@RequestMapping(value = { "/500", "/error" })
public String error500(HttpServletResponse res, ModelMap model, @RequestParam(value = "error", defaultValue = "") String error, @CookieValue(value = "colorPair", defaultValue = "") String colorPair, @RequestParam(value = "IRI", defaultValue = "") String IRI, @RequestParam(value = "endpoint", defaultValue = "") String endpoint) {
	System.out.println("error on " + error + " -- " + IRI + " -- " + endpoint);
	/* spring bug? */
	model.addAttribute("IRI", IRI);
	model.addAttribute("endpoint", endpoint);
	model.addAttribute("error", error);
	model.addAttribute("conf", conf);
	colors(colorPair, res, model);
	model.addAttribute("statusCode", "500");
	res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
	return "error";
}
 
Example #13
Source File: TestSearchApiController.java    From proctor with Apache License 2.0 5 votes vote down vote up
/**
 * API for proctor tests with filtering functionality
 *
 * @param branch           environment
 * @param limit            number of tests to return
 * @param q                query string to search
 * @param filterType       {@link FilterType}
 * @param filterActive     {@link FilterActive}
 * @param sort             {@link Sort}
 * @param favoriteTestsRaw comma-separated favorite tests saved in cookie
 * @return JSON of TestsResponse
 */
@ApiOperation(value = "Proctor tests with filters", response = List.class)
@GetMapping
public JsonView viewTestNames(
        @RequestParam(defaultValue = "trunk") final String branch,
        @RequestParam(defaultValue = "100") final int limit,
        @RequestParam(defaultValue = "") final String q,
        @RequestParam(defaultValue = "ALL") final FilterType filterType,
        @RequestParam(defaultValue = "ALL") final FilterActive filterActive,
        @RequestParam(defaultValue = "FAVORITESFIRST") final Sort sort,
        @CookieValue(value = "FavoriteTests", defaultValue = "") final String favoriteTestsRaw
) throws StoreException {
    final Set<String> favoriteTestNames = Sets.newHashSet(Splitter.on(",").split(favoriteTestsRaw));

    final Environment environment = determineEnvironmentFromParameter(branch);
    final TestMatrixDefinition testMatrixDefinition = getCurrentMatrix(environment).getTestMatrixDefinition();
    final Map<String, TestDefinition> allTestMatrix = testMatrixDefinition != null
            ? testMatrixDefinition.getTests()
            : Collections.emptyMap();

    final List<String> queries = Arrays.asList(q.split("\\s+"));
    final Map<String, TestDefinition> matchingTestMatrix = Maps.filterEntries(allTestMatrix,
            e -> e != null && matchesAllIgnoreCase(e.getKey(), e.getValue(), filterType, queries)
                    && matchesFilterActive(e.getValue().getAllocations(), filterActive)
    );

    final List<ProctorTest> searchResult =
            toProctorTests(matchingTestMatrix, determineStoreFromEnvironment(environment))
                    .stream()
                    .sorted(getComparator(sort, favoriteTestNames))
                    .limit(limit)
                    .collect(toList());

    return new JsonView(new TestsResponse(searchResult, allTestMatrix.size(), searchResult.size()));
}
 
Example #14
Source File: AbstractRequestBuilder.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build params parameter.
 *
 * @param parameterInfo the parameter info
 * @param components the components
 * @param requestMethod the request method
 * @param jsonView the json view
 * @return the parameter
 */
public Parameter buildParams(ParameterInfo parameterInfo, Components components,
		RequestMethod requestMethod, JsonView jsonView) {
	MethodParameter methodParameter = parameterInfo.getMethodParameter();
	RequestHeader requestHeader = parameterInfo.getRequestHeader();
	RequestParam requestParam = parameterInfo.getRequestParam();
	PathVariable pathVar = parameterInfo.getPathVar();
	CookieValue cookieValue = parameterInfo.getCookieValue();

	RequestInfo requestInfo;

	if (requestHeader != null) {
		requestInfo = new RequestInfo(ParameterIn.HEADER.toString(), parameterInfo.getpName(), requestHeader.required(),
				requestHeader.defaultValue());
		return buildParam(parameterInfo, components, requestInfo, jsonView);

	}
	else if (requestParam != null && !parameterBuilder.isFile(parameterInfo.getMethodParameter())) {
		requestInfo = new RequestInfo(ParameterIn.QUERY.toString(), parameterInfo.getpName(), requestParam.required() && !methodParameter.isOptional(),
				requestParam.defaultValue());
		return buildParam(parameterInfo, components, requestInfo, jsonView);
	}
	else if (pathVar != null) {
		requestInfo = new RequestInfo(ParameterIn.PATH.toString(), parameterInfo.getpName(), !methodParameter.isOptional(), null);
		return buildParam(parameterInfo, components, requestInfo, jsonView);
	}
	else if (cookieValue != null) {
		requestInfo = new RequestInfo(ParameterIn.COOKIE.toString(), parameterInfo.getpName(), cookieValue.required(),
				cookieValue.defaultValue());
		return buildParam(parameterInfo, components, requestInfo, jsonView);
	}
	// By default
	DelegatingMethodParameter delegatingMethodParameter = (DelegatingMethodParameter) methodParameter;
	if (RequestMethod.GET.equals(requestMethod)
			|| (parameterInfo.getParameterModel() != null && (ParameterIn.PATH.toString().equals(parameterInfo.getParameterModel().getIn())))
			|| delegatingMethodParameter.isParameterObject())
		return this.buildParam(QUERY_PARAM, components, parameterInfo, !methodParameter.isOptional(), null, jsonView);

	return null;
}
 
Example #15
Source File: ParameterInfo.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new Parameter info.
 *
 * @param pName the p name
 * @param methodParameter the method parameter
 */
public ParameterInfo(String pName, MethodParameter methodParameter) {
	this.methodParameter = methodParameter;
	this.requestHeader = methodParameter.getParameterAnnotation(RequestHeader.class);
	this.requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
	this.pathVar = methodParameter.getParameterAnnotation(PathVariable.class);
	this.cookieValue = methodParameter.getParameterAnnotation(CookieValue.class);
	this.pName = calculateName(pName, requestHeader, requestParam, pathVar, cookieValue);
}
 
Example #16
Source File: HeadersController.java    From karate with MIT License 5 votes vote down vote up
@GetMapping("/{token:.+}")
public ResponseEntity validateToken(@CookieValue("time") String time,
        @RequestHeader("Authorization") String[] authorization, @PathVariable String token,
        @RequestParam String url) {
    String temp = tokens.get(token);
    String auth = authorization[0];
    if (auth.equals("dummy")) {
        auth = authorization[1];
    }
    if (temp.equals(time) && auth.equals(token + time + url)) {
        return ResponseEntity.ok().build();
    } else {
        return ResponseEntity.badRequest().build();
    }
}
 
Example #17
Source File: ParameterInfo.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate name string.
 *
 * @param pName the p name
 * @param requestHeader the request header
 * @param requestParam the request param
 * @param pathVar the path var
 * @param cookieValue the cookie value
 * @return the string
 */
private String calculateName(String pName, RequestHeader requestHeader, RequestParam requestParam, PathVariable pathVar, CookieValue cookieValue) {
	String name = pName;
	if (requestHeader != null && StringUtils.isNotEmpty(requestHeader.value()))
		name = requestHeader.value();
	else if (requestParam != null && StringUtils.isNotEmpty(requestParam.value()))
		name = requestParam.value();
	else if (pathVar != null && StringUtils.isNotEmpty(pathVar.value()))
		name = pathVar.value();
	else if (cookieValue != null && StringUtils.isNotEmpty(cookieValue.value()))
		name = cookieValue.value();
	return name;
}
 
Example #18
Source File: Controller.java    From NLIDB with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/api/translate/nl")
public ResponseEntity translateNL(
        @CookieValue(value = COOKIE_NAME, defaultValue = USER_NONE) String userId,
        @RequestBody TranslateNLRequest req
) {

    if (userId.equals(USER_NONE) || !redisService.hasUser(userId)) {
        return ResponseEntity.status(401).body(new MessageResponse("You are not connected to a Database."));
    }
    return ResponseEntity.ok(new TranslateResponse(
            "We are still writing the code to translate your natural language input..."
    ));
}
 
Example #19
Source File: CookieValueMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public void params(
		@CookieValue("name") HttpCookie cookie,
		@CookieValue(name = "name", defaultValue = "bar") String cookieString,
		String stringParam,
		@CookieValue Mono<String> monoCookie) {
}
 
Example #20
Source File: ErrorController.java    From LodView with MIT License 5 votes vote down vote up
@RequestMapping(value = "/400")
public String error400(HttpServletResponse res, ModelMap model, @RequestParam(value = "IRI", defaultValue = "") String IRI, @CookieValue(value = "colorPair", defaultValue = "") String colorPair) {
	System.out.println("error on " + IRI);
	/* spring bug? */
	model.addAttribute("IRI", IRI.replaceAll("(http://.+),http://.+", "$1"));
	model.addAttribute("conf", conf);
	colors(colorPair, res, model);
	model.addAttribute("statusCode", "400");
	res.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
	return "error";
}
 
Example #21
Source File: RequestMappingHandlerAdapterIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
public String handle(
		@CookieValue("cookie") int cookieV,
		@PathVariable("pathvar") String pathvarV,
		@RequestHeader("header") String headerV,
		@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
		@RequestHeader Map<String, Object> headerMap,
		@RequestParam("dateParam") Date dateParam,
		@RequestParam Map<String, Object> paramMap,
		String paramByConvention,
		@Value("#{request.contextPath}") String value,
		@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
		Errors errors,
		TestBean modelAttrByConvention,
		Color customArg,
		HttpServletRequest request,
		HttpServletResponse response,
		@SessionAttribute TestBean sessionAttribute,
		@RequestAttribute TestBean requestAttribute,
		User user,
		@ModelAttribute OtherUser otherUser,
		Model model,
		UriComponentsBuilder builder) {

	model.addAttribute("cookie", cookieV).addAttribute("pathvar", pathvarV).addAttribute("header", headerV)
			.addAttribute("systemHeader", systemHeader).addAttribute("headerMap", headerMap)
			.addAttribute("dateParam", dateParam).addAttribute("paramMap", paramMap)
			.addAttribute("paramByConvention", paramByConvention).addAttribute("value", value)
			.addAttribute("customArg", customArg).addAttribute(user)
			.addAttribute("sessionAttribute", sessionAttribute)
			.addAttribute("requestAttribute", requestAttribute)
			.addAttribute("url", builder.path("/path").build().toUri());

	assertNotNull(request);
	assertNotNull(response);

	return "viewName";
}
 
Example #22
Source File: CookieValueAnnotationProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public String getParameterName(CookieValue annotation) {
  String value = annotation.value();
  if (value.isEmpty()) {
    value = annotation.name();
  }
  return value;
}
 
Example #23
Source File: Controller.java    From NLIDB with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/api/connect/user")
public ResponseEntity connectUser(
        @CookieValue(value = COOKIE_NAME, defaultValue = USER_NONE) String userId,
        HttpServletResponse res
) throws IOException {
    if (userId.equals(USER_NONE) || !redisService.hasUser(userId)) {
        return ResponseEntity.ok(new StatusMessageResponse(false, "No user session found"));
    } else {
        redisService.refreshUser(userId);
        UserSession session = redisService.getUserSession(userId);
        cookieService.setUserIdCookie(res, userId);
        return ResponseEntity.ok(new ConnectResponse(true, session.getDbConnectionConfig().getUrl()));
    }
}
 
Example #24
Source File: LoginController.java    From NoteBlog with MIT License 5 votes vote down vote up
@GetMapping("/login")
public String login(@CookieValue(value = SessionParam.SESSION_ID_COOKIE, required = false) String uuid) {
    if (StringUtils.isEmpty(uuid)) {
        return "management/login";
    }
    User u = blogContext.getSessionUser(uuid);
    if (u != null && u.getDefaultRoleId() == 1) {
        return "management/index";
    }
    return "management/login";
}
 
Example #25
Source File: DataTypeSpringmvcSchema.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@GetMapping("floatCookie")
public float floatCookie(@CookieValue("input") float input) {
  return input;
}
 
Example #26
Source File: DataTypeSpringmvcSchema.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@GetMapping("stringCookie")
public String stringCookie(@CookieValue("input") String input) {
  return input;
}
 
Example #27
Source File: DataTypeSpringmvcSchema.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@GetMapping("doubleCookie")
public double doubleCookie(@CookieValue("input") double input) {
  return input;
}
 
Example #28
Source File: DataTypeSpringmvcSchema.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@GetMapping("intCookie")
public int intCookie(@CookieValue("input") int input) {
  return input;
}
 
Example #29
Source File: CodeFirstSpringmvcSimplifiedMappingAnnotation.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@GetMapping(path = "/reduce")
@ApiImplicitParams({@ApiImplicitParam(name = "a", dataType = "integer", format = "int32", paramType = "query")})
@Override
public int reduce(HttpServletRequest request, @CookieValue(name = "b") int b) {
  return super.reduce(request, b);
}
 
Example #30
Source File: CodeFirstSpringmvc.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@RequestMapping(path = "/reduce", method = RequestMethod.GET)
@ApiImplicitParams({@ApiImplicitParam(name = "a", dataType = "integer", format = "int32", paramType = "query")})
@Override
public int reduce(HttpServletRequest request, @CookieValue(name = "b") int b) {
  return super.reduce(request, b);
}