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

The following examples show how to use org.springframework.web.bind.annotation.CookieValue. These examples are extracted from open source projects. 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 Project: mojito   Source File: ReactAppController.java    License: 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 Project: lemon   Source File: DiskController.java    License: 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 3
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 4
Source Project: MyCommunity   Source File: LoginController.java    License: 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 5
Source Project: LodView   Source File: ResourceController.java    License: 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 6
@SuppressWarnings("unused")
public void params(
		@CookieValue("name") HttpCookie cookie,
		@CookieValue(name = "name", defaultValue = "bar") String cookieString,
		String stringParam,
		@CookieValue Mono<String> monoCookie) {
}
 
Example 7
Source Project: LodView   Source File: ErrorController.java    License: 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 8
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 9
Source Project: springdoc-openapi   Source File: AbstractRequestBuilder.java    License: 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 10
Source Project: springdoc-openapi   Source File: ParameterInfo.java    License: 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 11
Source Project: springdoc-openapi   Source File: ParameterInfo.java    License: 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 12
Source Project: NLIDB   Source File: Controller.java    License: 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 13
@SuppressWarnings("unused")
public void params(
		@CookieValue("name") HttpCookie cookie,
		@CookieValue(name = "name", defaultValue = "bar") String cookieString,
		String stringParam,
		@CookieValue Mono<String> monoCookie) {
}
 
Example 14
Source Project: LodView   Source File: ErrorController.java    License: 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 15
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 16
Source Project: NLIDB   Source File: Controller.java    License: 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 17
Source Project: NoteBlog   Source File: LoginController.java    License: 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 18
Source Project: proctor   Source File: TestSearchApiController.java    License: 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 19
@Override
public String getParameterName(CookieValue annotation) {
  String value = annotation.value();
  if (value.isEmpty()) {
    value = annotation.name();
  }
  return value;
}
 
Example 20
Source Project: karate   Source File: HeadersController.java    License: 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 21
Source Project: LodView   Source File: ErrorController.java    License: 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 22
@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 23
Source Project: LodView   Source File: ErrorController.java    License: 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 24
@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 25
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
	CookieValue ann = parameter.getParameterAnnotation(CookieValue.class);
	Assert.state(ann != null, "No CookieValue annotation");
	return new CookieValueNamedValueInfo(ann);
}
 
Example 26
private CookieValueNamedValueInfo(CookieValue annotation) {
	super(annotation.name(), annotation.required(), annotation.defaultValue());
}
 
Example 27
public void params(@CookieValue("name") Cookie cookie,
		@CookieValue(name = "name", defaultValue = "bar") String cookieString) {
}
 
Example 28
@RequestMapping("/myPath2.do")
public void myHandle(@RequestParam("param1") String p1, @RequestParam("param2") int p2,
		@RequestHeader("header1") long h1, @CookieValue(name = "cookie1") Cookie c1,
		HttpServletResponse response) throws IOException {
	response.getWriter().write("test-" + p1 + "-" + p2 + "-" + h1 + "-" + c1.getValue());
}
 
Example 29
@RequestMapping("/myPath2.do")
public void myHandle(@RequestParam("param1") String p1, int param2, HttpServletResponse response,
		@RequestHeader("header1") String h1, @CookieValue("cookie1") String c1) throws IOException {
	response.getWriter().write("test-" + p1 + "-" + param2 + "-" + h1 + "-" + c1);
}
 
Example 30
@RequestMapping("/myPath2.do")
public void myHandle(@RequestParam("param1") T p1, int param2, @RequestHeader Integer header1,
		@CookieValue int cookie1, HttpServletResponse response) throws IOException {
	response.getWriter().write("test-" + p1 + "-" + param2 + "-" + header1 + "-" + cookie1);
}