コード例 #1
0
public class PersonControllerTest {

  private static final MediaType FORM_URL =
      MediaType.parseMediaType("application/x-www-form-urlencoded");
  private static final MediaType JSON_UTF8 =
      MediaType.parseMediaType("application/json;charset=UTF-8");

  private MockMvc mockMvc;

  @Before
  public void setup() {
    this.mockMvc = MockMvcBuilders.standaloneSetup(new PersonController()).build();
  }

  @Test
  public void testPostAndGet() throws Exception {
    mockMvc
        .perform(
            post("/")
                .contentType(FORM_URL)
                .param("forename", "Buzz")
                .param("surname", "Aldrin")
                .param("age", "85"))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(status().isCreated());

    mockMvc
        .perform(get("/").contentType(JSON_UTF8))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(jsonPath("$.forename", is("Buzz")))
        .andExpect(jsonPath("$.surname", is("Aldrin")))
        .andExpect(jsonPath("$.age", is(85)));
  }
}
コード例 #2
0
  @Test
  public void compareToConsistentWithEquals() {
    MediaType m1 = MediaType.parseMediaType("text/html; q=0.7; charset=iso-8859-1");
    MediaType m2 = MediaType.parseMediaType("text/html; charset=iso-8859-1; q=0.7");

    assertEquals("Media types not equal", m1, m2);
    assertEquals("compareTo() not consistent with equals", 0, m1.compareTo(m2));
    assertEquals("compareTo() not consistent with equals", 0, m2.compareTo(m1));

    m1 = MediaType.parseMediaType("text/html; q=0.7; charset=iso-8859-1");
    m2 = MediaType.parseMediaType("text/html; Q=0.7; charset=iso-8859-1");
    assertEquals("Media types not equal", m1, m2);
    assertEquals("compareTo() not consistent with equals", 0, m1.compareTo(m2));
    assertEquals("compareTo() not consistent with equals", 0, m2.compareTo(m1));
  }
コード例 #3
0
public class ResultFormatterFactory {

  private static final Map<MediaType, ResultFormatter> TYPE_TO_FORMATTER_MAP =
      new HashMap<MediaType, ResultFormatter>() {
        {
          put(
              MediaType.parseMediaType("application/json;charset=UTF-8"),
              new ResultFormatterJSON());
          put(
              MediaType.parseMediaType("application/ld+json;charset=UTF-8"),
              new ResultFormatterJSONLD());
          put(MediaType.parseMediaType("text/csv;charset=UTF-8"), new ResultFormatterCSV());
          put(
              MediaType.parseMediaType("text/tab-separated-values;charset=UTF-8"),
              new ResultFormatterTSV());
          // a trick to distinguish JSONv2 from JSON
          put(MediaType.parseMediaType("text/html;charset=UTF-8"), new ResultFormatterJSONv2());
          put(
              MediaType.parseMediaType("text/vnd.graphviz;charset=UTF-8"),
              new ResultFormatterDOT());
          put(MediaType.parseMediaType("image/svg+xml;charset=UTF-8"), new ResultFormatterSVG());
        }
      };
  public static final MediaType JSON = MediaType.parseMediaType("application/json;charset=UTF-8");

  public ResultFormatter create(MediaType type) {
    return TYPE_TO_FORMATTER_MAP.get(type == null ? JSON : type);
  }
}
コード例 #4
0
 private View getBestView(List<View> candidateViews, List<MediaType> requestedMediaTypes) {
   for (View candidateView : candidateViews) {
     if (candidateView instanceof SmartView) {
       SmartView smartView = (SmartView) candidateView;
       if (smartView.isRedirectView()) {
         if (logger.isDebugEnabled()) {
           logger.debug("Returning redirect view [" + candidateView + "]");
         }
         return candidateView;
       }
     }
   }
   for (MediaType mediaType : requestedMediaTypes) {
     for (View candidateView : candidateViews) {
       if (StringUtils.hasText(candidateView.getContentType())) {
         MediaType candidateContentType = MediaType.parseMediaType(candidateView.getContentType());
         if (mediaType.includes(candidateContentType)) {
           if (logger.isDebugEnabled()) {
             logger.debug(
                 "Returning ["
                     + candidateView
                     + "] based on requested media type '"
                     + mediaType
                     + "'");
           }
           return candidateView;
         }
       }
     }
   }
   return null;
 }
コード例 #5
0
 private Optional<MediaType> getContentType(HttpServletRequest request) {
   String contentType = request.getContentType();
   if (contentType != null) {
     return Optional.of(MediaType.parseMediaType(contentType));
   }
   return Optional.empty();
 }
コード例 #6
0
 /**
  * Determines the {@link MediaType} for the given filename.
  *
  * <p>The default implementation will check the {@linkplain #setMediaTypes(Map) media types}
  * property first for a defined mapping. If not present, and if the Java Activation Framework can
  * be found on the classpath, it will call {@link FileTypeMap#getContentType(String)}
  *
  * <p>This method can be overridden to provide a different algorithm.
  *
  * @param filename the current request file name (i.e. {@code hotels.html})
  * @return the media type, if any
  */
 protected MediaType getMediaTypeFromFilename(String filename) {
   String extension = StringUtils.getFilenameExtension(filename);
   if (!StringUtils.hasText(extension)) {
     return null;
   }
   extension = extension.toLowerCase(Locale.ENGLISH);
   MediaType mediaType = this.mediaTypes.get(extension);
   if (mediaType == null) {
     String mimeType = getServletContext().getMimeType(filename);
     if (StringUtils.hasText(mimeType)) {
       mediaType = MediaType.parseMediaType(mimeType);
     }
     if (this.useJaf
         && (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType))) {
       MediaType jafMediaType = ActivationMediaTypeFactory.getMediaType(filename);
       if (jafMediaType != null && !MediaType.APPLICATION_OCTET_STREAM.equals(jafMediaType)) {
         mediaType = jafMediaType;
       }
     }
     if (mediaType != null) {
       this.mediaTypes.putIfAbsent(extension, mediaType);
     }
   }
   return mediaType;
 }
コード例 #7
0
 @Test
 public void testWithConversionService() {
   ConversionService conversionService = new DefaultConversionService();
   assertTrue(conversionService.canConvert(String.class, MediaType.class));
   MediaType mediaType = MediaType.parseMediaType("application/xml");
   assertEquals(mediaType, conversionService.convert("application/xml", MediaType.class));
 }
コード例 #8
0
  /**
   * Generate http request entity from Spring Integration message.
   *
   * @param requestMessage
   * @param method
   * @return
   */
  private HttpEntity<?> generateRequest(Message<?> requestMessage, HttpMethod method) {
    HttpHeaders httpHeaders = new HttpHeaders();
    headerMapper.fromHeaders(requestMessage.getHeaders(), httpHeaders);

    Map<String, ?> messageHeaders = requestMessage.getHeaders();
    for (Entry<String, ?> header : messageHeaders.entrySet()) {
      if (!header.getKey().startsWith(CitrusMessageHeaders.PREFIX)
          && !MessageUtils.isSpringInternalHeader(header.getKey())
          && !httpHeaders.containsKey(header.getKey())) {
        httpHeaders.add(header.getKey(), header.getValue().toString());
      }
    }

    Object payload = requestMessage.getPayload();
    if (httpHeaders.getContentType() == null) {
      httpHeaders.setContentType(
          MediaType.parseMediaType(
              contentType.contains("charset") ? contentType : contentType + ";charset=" + charset));
    }

    if (HttpMethod.POST.equals(method) || HttpMethod.PUT.equals(method)) {
      return new HttpEntity<Object>(payload, httpHeaders);
    }

    return new HttpEntity<Object>(httpHeaders);
  }
コード例 #9
0
  public BufferedImageHttpMessageConverter() {
    String[] readerMediaTypes = ImageIO.getReaderMIMETypes();
    for (String mediaType : readerMediaTypes) {
      if (StringUtils.hasText(mediaType)) {
        this.readableMediaTypes.add(MediaType.parseMediaType(mediaType));
      }
    }

    String[] writerMediaTypes = ImageIO.getWriterMIMETypes();
    for (String mediaType : writerMediaTypes) {
      if (StringUtils.hasText(mediaType)) {
        this.defaultContentType = MediaType.parseMediaType(mediaType);
        break;
      }
    }
  }
コード例 #10
0
 private String determineEncoding(String contentTypeHeader, String defaultEncoding) {
   if (!StringUtils.hasText(contentTypeHeader)) {
     return defaultEncoding;
   }
   MediaType contentType = MediaType.parseMediaType(contentTypeHeader);
   Charset charset = contentType.getCharSet();
   return (charset != null ? charset.name() : defaultEncoding);
 }
コード例 #11
0
 @Test
 public void parseURLConnectionMediaType() throws Exception {
   String s = "*; q=.2";
   MediaType mediaType = MediaType.parseMediaType(s);
   assertEquals("Invalid type", "*", mediaType.getType());
   assertEquals("Invalid subtype", "*", mediaType.getSubtype());
   assertEquals("Invalid quality factor", 0.2D, mediaType.getQualityValue(), 0D);
 }
コード例 #12
0
 @Test
 public void parseCharset() throws Exception {
   String s = "text/html; charset=iso-8859-1";
   MediaType mediaType = MediaType.parseMediaType(s);
   assertEquals("Invalid type", "text", mediaType.getType());
   assertEquals("Invalid subtype", "html", mediaType.getSubtype());
   assertEquals("Invalid charset", Charset.forName("ISO-8859-1"), mediaType.getCharSet());
 }
コード例 #13
0
 @Test
 public void parseQuotedCharset() {
   String s = "application/xml;charset=\"utf-8\"";
   MediaType mediaType = MediaType.parseMediaType(s);
   assertEquals("Invalid type", "application", mediaType.getType());
   assertEquals("Invalid subtype", "xml", mediaType.getSubtype());
   assertEquals("Invalid charset", Charset.forName("UTF-8"), mediaType.getCharSet());
 }
コード例 #14
0
 /**
  * Set the mapping from file extensions to media types.
  *
  * <p>When this mapping is not set or when an extension is not present, this view resolver will
  * fall back to using a {@link FileTypeMap} when the Java Action Framework is available.
  */
 public void setMediaTypes(Map<String, String> mediaTypes) {
   Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
   for (Map.Entry<String, String> entry : mediaTypes.entrySet()) {
     String extension = entry.getKey().toLowerCase(Locale.ENGLISH);
     MediaType mediaType = MediaType.parseMediaType(entry.getValue());
     this.mediaTypes.put(extension, mediaType);
   }
 }
コード例 #15
0
 boolean isContentTypeMatch(HttpServletRequest request, MockData mock) {
   String mockContentType = mock.getRequestMediaType();
   if (mockContentType != null) {
     MediaType requestContentType = getContentType(request).orElse(MediaType.ALL);
     return MediaType.parseMediaType(mockContentType).includes(requestContentType);
   }
   return true;
 }
コード例 #16
0
 @Test
 public void resultsNonauthorizedExceptionForNoLoginRequiredLocaly() throws Exception {
   mvc.perform(get("/results-nonauthorized").accept(MediaType.APPLICATION_JSON))
       .andExpect(status().isOk())
       .andExpect(
           content()
               .contentTypeCompatibleWith(
                   MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE)));
 }
コード例 #17
0
 @Test
 public void invokePlugin() throws Exception {
   this.mockMvc
       .perform(
           get("/scala-plugin?parameter=test")
               .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
       .andExpect(status().isOk())
       .andExpect(content().string("scala-plugin with test"));
 }
コード例 #18
0
ファイル: HttpUtil.java プロジェクト: xmplatform/jnh
  /**
   * 发送post请求返回字符串
   *
   * @param url post-URL:
   * @param postData post的数据
   * @return 返回post请求响应的数据
   */
  public static String postUrl(String url, String postData) {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
    HttpEntity<String> formEntity = new HttpEntity<String>(postData, headers);

    return restTemplate.postForObject(url, formEntity, String.class);
  }
コード例 #19
0
  @Test
  public void resultsClientOnly() throws Exception {

    mvc.perform(get("/results").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(
            content()
                .contentTypeCompatibleWith(
                    MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE)));
  }
コード例 #20
0
 /** 处理JSR311 Validation异常. */
 @ExceptionHandler(value = {ConstraintViolationException.class})
 public final ResponseEntity<?> handleException(
     ConstraintViolationException ex, WebRequest request) {
   Map<String, String> errors =
       BeanValidators.extractPropertyAndMessage(ex.getConstraintViolations());
   String body = jsonMapper.toJson(errors);
   HttpHeaders headers = new HttpHeaders();
   headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8));
   return handleExceptionInternal(ex, body, headers, HttpStatus.BAD_REQUEST, request);
 }
 /**
  * Extends the base class {@link PathExtensionContentNegotiationStrategy#getMediaTypeForResource}
  * with the ability to also look up through the ServletContext.
  *
  * @param resource the resource to look up
  * @return the MediaType for the extension or {@code null}.
  * @since 4.3
  */
 public MediaType getMediaTypeForResource(Resource resource) {
   MediaType mediaType = super.getMediaTypeForResource(resource);
   if (mediaType == null) {
     String mimeType = this.servletContext.getMimeType(resource.getFilename());
     if (StringUtils.hasText(mimeType)) {
       mediaType = MediaType.parseMediaType(mimeType);
     }
   }
   if (MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) {
     mediaType = null;
   }
   return mediaType;
 }
コード例 #22
0
 @Override
 public Object extractData(ClientHttpResponse response) throws IOException {
   if (MediaType.IMAGE_JPEG.includes(response.getHeaders().getContentType())
       || MediaType.parseMediaType(AUDIO_CONTENT_TYPE)
           .includes(response.getHeaders().getContentType())) {
     return new MediaMultipartFile(response);
   } else if (stringHttpMessageConverter.canRead(
       String.class, response.getHeaders().getContentType())) {
     return MessageMapper.fromJson(
         stringHttpMessageConverter.read(String.class, (HttpInputMessage) response),
         MpResponse.class);
   }
   return null;
 }
コード例 #23
0
 @Override
 public ProfilePhoto readUserProfilePhoto(long userId) {
   InputStream fileInputSteam = null;
   try {
     User user = findById(userId);
     fileInputSteam = new FileInputStream(fileForPhoto(userId));
     byte[] data = IOUtils.toByteArray(fileInputSteam);
     return new ProfilePhoto(
         userId, data, MediaType.parseMediaType(user.getProfilePhotoMediaType()));
   } catch (Exception e) {
     throw new UserProfilePhotoReadException(userId, e);
   } finally {
     IOUtils.closeQuietly(fileInputSteam);
   }
 }
コード例 #24
0
  @RequestMapping(value = IMAGES + "/{fileName}.{fileType}")
  public void getImage(
      @PathVariable String fileName,
      @PathVariable String fileType,
      @RequestParam(required = false) String version,
      HttpServletResponse response)
      throws IOException {

    FileImageFinder.FileInfo file = imageFinder.getFile(fileName + "." + fileType, version);

    response.setContentType(MediaType.parseMediaType("image/" + fileType).toString());
    response.setContentLength(file.bytes.length);
    response.setHeader("Last-Modified", file.modifyTime);
    response.setHeader("Cache-Control", "public, max-age=3153600");
    response.getOutputStream().write(file.bytes);
  }
  /**
   * Resolve file extension via {@link ServletContext#getMimeType(String)} and also delegate to base
   * class for a potential JAF lookup.
   */
  @Override
  protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension)
      throws HttpMediaTypeNotAcceptableException {

    MediaType mediaType = null;
    if (this.servletContext != null) {
      String mimeType = this.servletContext.getMimeType("file." + extension);
      if (StringUtils.hasText(mimeType)) {
        mediaType = MediaType.parseMediaType(mimeType);
      }
    }
    if (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) {
      MediaType superMediaType = super.handleNoMatch(webRequest, extension);
      if (superMediaType != null) {
        mediaType = superMediaType;
      }
    }
    return mediaType;
  }
コード例 #26
0
 {
   put(
       MediaType.parseMediaType("application/json;charset=UTF-8"),
       new ResultFormatterJSON());
   put(
       MediaType.parseMediaType("application/ld+json;charset=UTF-8"),
       new ResultFormatterJSONLD());
   put(MediaType.parseMediaType("text/csv;charset=UTF-8"), new ResultFormatterCSV());
   put(
       MediaType.parseMediaType("text/tab-separated-values;charset=UTF-8"),
       new ResultFormatterTSV());
   // a trick to distinguish JSONv2 from JSON
   put(MediaType.parseMediaType("text/html;charset=UTF-8"), new ResultFormatterJSONv2());
   put(
       MediaType.parseMediaType("text/vnd.graphviz;charset=UTF-8"),
       new ResultFormatterDOT());
   put(MediaType.parseMediaType("image/svg+xml;charset=UTF-8"), new ResultFormatterSVG());
 }
コード例 #27
0
  @RequestMapping(value = "/image/{id}", method = RequestMethod.GET)
  public ResponseEntity<byte[]> getImage(
      @PathVariable long id, HttpServletRequest request, HttpServletResponse response) {
    checkRequiredEntity(appFileService, id);
    AppFile appFile = appFileService.get(id);

    if (!ContentType.IMAGE.equals(MimeType.getForFilename(appFile.getName()).getContentType())) {
      throw new RuntimeException(
          String.format("Attempted to pull file which wasn't an image: %s", id));
    }

    response.setHeader(
        "Cache-Control", String.format("public, max-age=%s", 31556900 /*Seconds in a year*/));
    response.setDateHeader("Last-Modified", appFile.getLastUpdate().getTime());

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(appFile.getLastUpdate());
    calendar.add(Calendar.YEAR, 1);
    response.setHeader("Expires", httpDateFormat.format(calendar.getTime()));

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType(appFile.getType()));

    StorageService storageService =
        storageServiceFactory.getStorageService(appFile.getStorageType());

    long requestIfModifiedSince = request.getDateHeader("If-Modified-Since");
    if (requestIfModifiedSince >= appFile.getLastUpdate().getTime()) {
      response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
      return null;
    }

    if (storageService instanceof RemoteStorageService) {
      byte[] bytes = readImageFromUrl(appFile, (RemoteStorageService) storageService);

      return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
    } else {
      byte[] bytes = readImageFromFile(appFile);

      return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
    }
  }
コード例 #28
0
  @RequestMapping(
      value = "/saveAsZip/filename/{uuid}/{filename}",
      method = RequestMethod.GET,
      produces = "application/zip")
  public ResponseEntity<InputStreamResource> saveAsZip(
      @PathVariable String uuid, @PathVariable String filename) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    headers.add("Content-Disposition", "attachment; filename=" + filename + ".zip");
    headers.add("Set-Cookie", "fileDownload=true; path=/");

    byte[] data = createZip(uuid);
    routeRepository.clearRoutes(uuid);
    return ResponseEntity.ok()
        .headers(headers)
        .contentLength(data.length)
        .contentType(MediaType.parseMediaType("application/zip"))
        .body(new InputStreamResource(new ByteArrayInputStream(data)));
  }
コード例 #29
0
  /**
   * Generates the Http response message from given Spring Integration message.
   *
   * @param responseMessage message received from the message handler
   * @return an HTTP entity as response
   */
  private ResponseEntity<String> generateResponse(Message<?> responseMessage) {
    if (responseMessage == null) {
      return new ResponseEntity<String>(HttpStatus.OK);
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    headerMapper.fromHeaders(responseMessage.getHeaders(), httpHeaders);

    Map<String, ?> messageHeaders = responseMessage.getHeaders();
    for (Entry<String, ?> header : messageHeaders.entrySet()) {
      if (!header.getKey().startsWith(CitrusMessageHeaders.PREFIX)
          && !MessageUtils.isSpringInternalHeader(header.getKey())
          && !httpHeaders.containsKey(header.getKey())) {
        httpHeaders.add(header.getKey(), header.getValue().toString());
      }
    }

    if (httpHeaders.getContentType() == null) {
      httpHeaders.setContentType(
          MediaType.parseMediaType(
              contentType.contains("charset") ? contentType : contentType + ";charset=" + charset));
    }

    HttpStatus status = HttpStatus.OK;
    if (responseMessage.getHeaders().containsKey(CitrusHttpMessageHeaders.HTTP_STATUS_CODE)) {
      status =
          HttpStatus.valueOf(
              Integer.valueOf(
                  responseMessage
                      .getHeaders()
                      .get(CitrusHttpMessageHeaders.HTTP_STATUS_CODE)
                      .toString()));
    }

    responseCache =
        new ResponseEntity<String>(responseMessage.getPayload().toString(), httpHeaders, status);

    return responseCache;
  }
コード例 #30
0
 @Override
 protected HttpHeaders initHeaders() {
   HttpHeaders headers = new HttpHeaders();
   for (Enumeration<?> names = getServletRequest().getHeaderNames(); names.hasMoreElements(); ) {
     String name = (String) names.nextElement();
     for (Enumeration<?> values = getServletRequest().getHeaders(name);
         values.hasMoreElements(); ) {
       headers.add(name, (String) values.nextElement());
     }
   }
   MediaType contentType = headers.getContentType();
   if (contentType == null) {
     String requestContentType = getServletRequest().getContentType();
     if (StringUtils.hasLength(requestContentType)) {
       contentType = MediaType.parseMediaType(requestContentType);
       headers.setContentType(contentType);
     }
   }
   if (contentType != null && contentType.getCharset() == null) {
     String encoding = getServletRequest().getCharacterEncoding();
     if (StringUtils.hasLength(encoding)) {
       Charset charset = Charset.forName(encoding);
       Map<String, String> params = new LinkedCaseInsensitiveMap<>();
       params.putAll(contentType.getParameters());
       params.put("charset", charset.toString());
       headers.setContentType(
           new MediaType(contentType.getType(), contentType.getSubtype(), params));
     }
   }
   if (headers.getContentLength() == -1) {
     int contentLength = getServletRequest().getContentLength();
     if (contentLength != -1) {
       headers.setContentLength(contentLength);
     }
   }
   return headers;
 }