コード例 #1
0
 // curl -X POST -i http://localhost:8080/todo-app/api/todo?text=TodoItem1
 @RequestMapping(value = "todo", method = RequestMethod.POST)
 @ResponseStatus(HttpStatus.CREATED)
 @ResponseBody
 public void create(@RequestParam String text, HttpServletRequest req, HttpServletResponse resp) {
   Todo todo = todoService.createNewTodo(text);
   StringBuffer url = req.getRequestURL().append("/{id}");
   UriTemplate uriTemplate = new UriTemplate(url.toString());
   resp.addHeader("location", uriTemplate.expand(todo.getId()).toASCIIString());
 }
コード例 #2
0
 /**
  * Return a context-aware URl for the given relative URL with placeholders (named keys with braces
  * {@code {}}). For example, send in a relative URL {@code foo/{bar}?spam={spam}} and a parameter
  * map {@code {bar=baz,spam=nuts}} and the result will be {@code [contextpath]/foo/baz?spam=nuts}.
  *
  * @param relativeUrl the relative URL part
  * @param params a map of parameters to insert as placeholders in the url
  * @return a URL that points back to the server with an absolute path (also URL-encoded
  *     accordingly)
  */
 public String getContextUrl(String relativeUrl, Map<String, ?> params) {
   String url = getContextPath() + relativeUrl;
   UriTemplate template = new UriTemplate(url);
   url = template.expand(params).toASCIIString();
   if (this.response != null) {
     url = this.response.encodeURL(url);
   }
   return url;
 }
コード例 #3
0
  public <T> T execute(
      String url,
      HttpMethod method,
      RequestCallback requestCallback,
      ResponseExtractor<T> responseExtractor,
      Map<String, ?> urlVariables)
      throws RestClientException {

    UriTemplate uriTemplate = new HttpUrlTemplate(url);
    URI expanded = uriTemplate.expand(urlVariables);
    return doExecute(expanded, method, requestCallback, responseExtractor);
  }
コード例 #4
0
  /*
   * (non-Javadoc)
   * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(java.lang.Object)
   */
  @Override
  public ControllerLinkBuilder linkTo(Object invocationValue) {

    Assert.isInstanceOf(LastInvocationAware.class, invocationValue);
    LastInvocationAware invocations = (LastInvocationAware) invocationValue;

    MethodInvocation invocation = invocations.getLastInvocation();
    Iterator<Object> classMappingParameters = invocations.getObjectParameters();
    Method method = invocation.getMethod();

    String mapping = DISCOVERER.getMapping(method);
    UriComponentsBuilder builder = ControllerLinkBuilder.getBuilder().path(mapping);

    UriTemplate template = new UriTemplate(mapping);
    Map<String, Object> values = new HashMap<String, Object>();

    Iterator<String> names = template.getVariableNames().iterator();
    while (classMappingParameters.hasNext()) {
      values.put(names.next(), classMappingParameters.next());
    }

    for (BoundMethodParameter parameter : PATH_VARIABLE_ACCESSOR.getBoundParameters(invocation)) {
      values.put(parameter.getVariableName(), parameter.asString());
    }

    for (BoundMethodParameter parameter : REQUEST_PARAM_ACCESSOR.getBoundParameters(invocation)) {

      Object value = parameter.getValue();
      String key = parameter.getVariableName();

      if (value instanceof Collection) {
        for (Object element : (Collection<?>) value) {
          builder.queryParam(key, element);
        }
      } else {
        builder.queryParam(key, parameter.asString());
      }
    }

    UriComponents components =
        applyUriComponentsContributer(builder, invocation).buildAndExpand(values);
    return new ControllerLinkBuilder(UriComponentsBuilder.fromUri(components.toUri()));
  }
コード例 #5
0
 public String getProductIdFromUri(String productURI) {
   UriTemplate uriTemplate = new UriTemplate("/products/{productId}");
   Map<String, String> variables = uriTemplate.match(productURI);
   return variables.get("productId");
 }
コード例 #6
0
 private URI childLocation(StringBuffer parentUri, Object childId) {
   UriTemplate uri = new UriTemplate(parentUri.append("/{childId}").toString());
   return uri.expand(childId);
 }
コード例 #7
0
 /**
  * determines URL of child resource based on the full URL of the given request, appending the path
  * info with the given childIdentifier using a UriTemplate.
  */
 private URI getLocationForChildResource(StringBuffer url, Object childIdentifier) {
   UriTemplate template = new UriTemplate(url.append("/{childId}").toString());
   return template.expand(childIdentifier);
 }
コード例 #8
0
  @RequestMapping(value = "/addphoto.jsp", method = RequestMethod.POST)
  @PreAuthorize("hasRole('ROLE_ANONYMOUS')")
  public ModelAndView addPhoto(
      @RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {

    if (file == null || file.isEmpty()) {
      return new ModelAndView("addphoto", "error", "изображение не задано");
    }

    try {
      File uploadedFile =
          File.createTempFile(
              "userpic", "", new File(siteConfig.getPathPrefix() + "/linux-storage/tmp/"));

      file.transferTo(uploadedFile);

      ImageParam param = userService.checkUserPic(uploadedFile);
      String extension = param.getExtension();

      Random random = new Random();

      String photoname;
      File photofile;

      do {
        photoname =
            Integer.toString(AuthUtil.getCurrentUser().getId())
                + ':'
                + random.nextInt()
                + '.'
                + extension;
        photofile = new File(siteConfig.getHTMLPathPrefix() + "/photos", photoname);
      } while (photofile.exists());

      if (!uploadedFile.renameTo(photofile)) {
        logger.warn("Can't move photo to " + photofile);
        throw new ScriptErrorException("Can't move photo: internal error");
      }

      userDao.setPhoto(AuthUtil.getCurrentUser(), photoname);

      logger.info("Установлена фотография пользователем " + AuthUtil.getCurrentUser().getNick());

      return new ModelAndView(
          new RedirectView(
              UriComponentsBuilder.fromUri(
                      PROFILE_NOCACHE_URI_TEMPLATE.expand(AuthUtil.getCurrentUser().getNick()))
                  .queryParam("nocache", Integer.toString(random.nextInt()) + '=')
                  .build()
                  .encode()
                  .toString()));
    } catch (IOException ex) {
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return new ModelAndView("addphoto", "error", ex.getMessage());
    } catch (BadImageException ex) {
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return new ModelAndView("addphoto", "error", ex.getMessage());
    } catch (UserErrorException ex) {
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return new ModelAndView("addphoto", "error", ex.getMessage());
    }
  }