コード例 #1
0
  @Override
  public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage)
      throws IOException, HttpMessageNotReadableException {

    ImageInputStream imageInputStream = null;
    ImageReader imageReader = null;
    try {
      imageInputStream = createImageInputStream(inputMessage.getBody());
      MediaType contentType = inputMessage.getHeaders().getContentType();
      Iterator<ImageReader> imageReaders =
          ImageIO.getImageReadersByMIMEType(contentType.toString());
      if (imageReaders.hasNext()) {
        imageReader = imageReaders.next();
        ImageReadParam irp = imageReader.getDefaultReadParam();
        process(irp);
        imageReader.setInput(imageInputStream, true);
        return imageReader.read(0, irp);
      } else {
        throw new HttpMessageNotReadableException(
            "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]");
      }
    } finally {
      if (imageReader != null) {
        imageReader.dispose();
      }
      if (imageInputStream != null) {
        try {
          imageInputStream.close();
        } catch (IOException ex) {
          // ignore
        }
      }
    }
  }
コード例 #2
0
 private boolean isWritable(MediaType mediaType) {
   if (mediaType == null || MediaType.ALL.equals(mediaType)) {
     return true;
   }
   Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(mediaType.toString());
   return imageWriters.hasNext();
 }
コード例 #3
0
 private boolean isReadable(MediaType mediaType) {
   if (mediaType == null) {
     return true;
   }
   Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(mediaType.toString());
   return imageReaders.hasNext();
 }
  @Test
  @SuppressWarnings("unchecked")
  public void Can_create_a_user_for_a_specific_content_type() {

    final MediaType contentTypeOne = APPLICATION_FORM_URLENCODED;
    final MediaType contentTypeTwo = APPLICATION_JSON;
    final UserFactory<HttpServletRequest> userFactoryOne = mock(UserFactory.class);
    final UserFactory<HttpServletRequest> userFactoryTwo = mock(UserFactory.class);
    final Map<MediaType, UserFactory<HttpServletRequest>> factories =
        new HashMap<MediaType, UserFactory<HttpServletRequest>>() {
          {
            put(contentTypeOne, userFactoryOne);
            put(contentTypeTwo, userFactoryTwo);
          }
        };

    final HttpServletRequest request = mock(HttpServletRequest.class);

    final User expected = mock(PersistedUser.class);

    // Given
    given(request.getContentType()).willReturn(contentTypeTwo.toString());
    given(userFactoryTwo.create(request)).willReturn(expected);

    // When
    final User actual = new ContentTypeUserFactory(factories).create(request);

    // Then
    assertThat(actual, equalTo(expected));
  }
コード例 #5
0
  @Test
  public void headers() throws URISyntaxException {
    MediaType accept = MediaType.TEXT_PLAIN;
    Charset charset = Charset.forName("UTF-8");
    long ifModifiedSince = 12345L;
    String ifNoneMatch = "\"foo\"";
    long contentLength = 67890;
    MediaType contentType = MediaType.TEXT_PLAIN;

    RequestEntity<Void> responseEntity =
        RequestEntity.post(new URI("http://example.com"))
            .accept(accept)
            .acceptCharset(charset)
            .ifModifiedSince(ifModifiedSince)
            .ifNoneMatch(ifNoneMatch)
            .contentLength(contentLength)
            .contentType(contentType)
            .build();

    assertNotNull(responseEntity);
    assertEquals(HttpMethod.POST, responseEntity.getMethod());
    assertEquals(new URI("http://example.com"), responseEntity.getUrl());
    HttpHeaders responseHeaders = responseEntity.getHeaders();

    assertEquals("text/plain", responseHeaders.getFirst("Accept"));
    assertEquals("utf-8", responseHeaders.getFirst("Accept-Charset"));
    assertEquals("Thu, 01 Jan 1970 00:00:12 GMT", responseHeaders.getFirst("If-Modified-Since"));
    assertEquals(ifNoneMatch, responseHeaders.getFirst("If-None-Match"));
    assertEquals(String.valueOf(contentLength), responseHeaders.getFirst("Content-Length"));
    assertEquals(contentType.toString(), responseHeaders.getFirst("Content-Type"));

    assertNull(responseEntity.getBody());
  }
コード例 #6
0
  /**
   * Sets the default {@code Content-Type} to be used for writing.
   *
   * @throws IllegalArgumentException if the given content type is not supported by the Java Image
   *     I/O API
   */
  public void setDefaultContentType(MediaType defaultContentType) {
    Assert.notNull(defaultContentType, "'contentType' must not be null");
    Iterator<ImageWriter> imageWriters =
        ImageIO.getImageWritersByMIMEType(defaultContentType.toString());
    if (!imageWriters.hasNext()) {
      throw new IllegalArgumentException(
          "Content-Type [" + defaultContentType + "] is not supported by the Java Image I/O API");
    }

    this.defaultContentType = defaultContentType;
  }
  @Test(expected = HttpMediaTypeNotSupportedException.class)
  public void resolveArgumentNotReadable() throws Exception {
    MediaType contentType = MediaType.TEXT_PLAIN;
    servletRequest.addHeader("Content-Type", contentType.toString());

    expect(messageConverter.canRead(String.class, contentType)).andReturn(false);
    replay(messageConverter);

    processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);

    fail("Expected exception");
  }
コード例 #8
0
 @Override
 protected View createView(String viewName, Locale locale) throws Exception {
   View view = super.createView(viewName, locale);
   if (viewName.startsWith(FORWARD_URL_PREFIX) || viewName.startsWith(REDIRECT_URL_PREFIX)) {
     if (view instanceof AbstractView) {
       MediaType requestedMediaType = getRequestedMediaType();
       if (requestedMediaType != null) {
         ((AbstractView) view).setContentType(requestedMediaType.toString());
       }
     }
   }
   return view;
 }
  @Test(expected = HttpMediaTypeNotAcceptableException.class)
  public void handleReturnValueNotAcceptableProduces() throws Exception {
    MediaType accepted = MediaType.TEXT_PLAIN;
    servletRequest.addHeader("Accept", accepted.toString());

    expect(messageConverter.canWrite(String.class, null)).andReturn(true);
    expect(messageConverter.getSupportedMediaTypes())
        .andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
    expect(messageConverter.canWrite(String.class, accepted)).andReturn(false);
    replay(messageConverter);

    processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest);

    fail("Expected exception");
  }
コード例 #10
0
 @Override
 protected void applyHeaders() {
   for (Map.Entry<String, List<String>> entry : getHeaders().entrySet()) {
     String headerName = entry.getKey();
     for (String headerValue : entry.getValue()) {
       this.response.addHeader(headerName, headerValue);
     }
   }
   MediaType contentType = getHeaders().getContentType();
   if (this.response.getContentType() == null && contentType != null) {
     this.response.setContentType(contentType.toString());
   }
   Charset charset = (contentType != null ? contentType.getCharset() : null);
   if (this.response.getCharacterEncoding() == null && charset != null) {
     this.response.setCharacterEncoding(charset.name());
   }
 }
  @Test
  public void resolveArgument() throws Exception {
    MediaType contentType = MediaType.TEXT_PLAIN;
    servletRequest.addHeader("Content-Type", contentType.toString());

    String body = "Foo";
    expect(messageConverter.canRead(String.class, contentType)).andReturn(true);
    expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body);
    replay(messageConverter);

    Object result =
        processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);

    assertEquals("Invalid argument", body, result);
    assertTrue("The ResolveView flag shouldn't change", mavContainer.isResolveView());
    verify(messageConverter);
  }
  @Test
  public void handleReturnValue() throws Exception {
    MediaType accepted = MediaType.TEXT_PLAIN;
    servletRequest.addHeader("Accept", accepted.toString());

    String body = "Foo";
    expect(messageConverter.canWrite(String.class, null)).andReturn(true);
    expect(messageConverter.getSupportedMediaTypes())
        .andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
    expect(messageConverter.canWrite(String.class, accepted)).andReturn(true);
    messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
    replay(messageConverter);

    processor.handleReturnValue(body, returnTypeString, mavContainer, webRequest);

    assertFalse("The ResolveView flag wasn't turned off", mavContainer.isResolveView());
    verify(messageConverter);
  }
コード例 #13
0
  @Override
  public void writeUserProfilePhoto(long userId, MediaType ext, byte[] bytesForProfilePhoto) {

    User user = findById(userId);
    user.setProfilePhotoMediaType(ext.toString());
    user.setProfilePhotoImported(true);
    userRepository.save(user);

    ByteArrayInputStream byteArrayInputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
      fileOutputStream = new FileOutputStream(fileForPhoto(userId));
      byteArrayInputStream = new ByteArrayInputStream(bytesForProfilePhoto);
      IOUtils.copy(byteArrayInputStream, fileOutputStream);
    } catch (IOException e) {
      throw new UserProfilePhotoWriteException(userId, e);
    } finally {
      IOUtils.closeQuietly(fileOutputStream);
      IOUtils.closeQuietly(byteArrayInputStream);
    }
  }
コード例 #14
0
  private void writeInternal(
      BufferedImage image, MediaType contentType, HttpHeaders headers, OutputStream body)
      throws IOException, HttpMessageNotWritableException {

    if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
      contentType = getDefaultContentType();
    }
    Assert.notNull(
        contentType,
        "Count not determine Content-Type, set one using the 'defaultContentType' property");
    headers.setContentType(contentType);
    ImageOutputStream imageOutputStream = null;
    ImageWriter imageWriter = null;
    try {
      Iterator<ImageWriter> imageWriters =
          ImageIO.getImageWritersByMIMEType(contentType.toString());
      if (imageWriters.hasNext()) {
        imageWriter = imageWriters.next();
        ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
        process(iwp);
        imageOutputStream = createImageOutputStream(body);
        imageWriter.setOutput(imageOutputStream);
        imageWriter.write(null, new IIOImage(image, null, null), iwp);
      } else {
        throw new HttpMessageNotWritableException(
            "Could not find javax.imageio.ImageWriter for Content-Type [" + contentType + "]");
      }
    } finally {
      if (imageWriter != null) {
        imageWriter.dispose();
      }
      if (imageOutputStream != null) {
        try {
          imageOutputStream.close();
        } catch (IOException ex) {
          // ignore
        }
      }
    }
  }
  private void testResolveArgumentWithValidation(SimpleBean simpleBean)
      throws IOException, Exception {
    MediaType contentType = MediaType.TEXT_PLAIN;
    servletRequest.addHeader("Content-Type", contentType.toString());

    @SuppressWarnings("unchecked")
    HttpMessageConverter<SimpleBean> beanConverter = createMock(HttpMessageConverter.class);
    expect(beanConverter.getSupportedMediaTypes())
        .andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
    expect(beanConverter.canRead(SimpleBean.class, contentType)).andReturn(true);
    expect(beanConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class)))
        .andReturn(simpleBean);
    replay(beanConverter);

    processor =
        new RequestResponseBodyMethodProcessor(
            Collections.<HttpMessageConverter<?>>singletonList(beanConverter));
    processor.resolveArgument(
        paramValidBean, mavContainer, webRequest, new ValidatingBinderFactory());

    verify(beanConverter);
  }
コード例 #16
0
  @SuppressWarnings("resource")
  public void writeJsonResponse(
      HttpServletResponse response,
      Object responseObject,
      Class<?> jsonView,
      boolean streamResponse,
      boolean isMultipart)
      throws IOException, JsonGenerationException, JsonMappingException {

    ObjectMapper objectMapper = configurationService.getJsonHandler().getMapper();

    if (isMultipart) {
      response.setContentType(RouterController.TEXT_HTML.toString());
      response.setCharacterEncoding(RouterController.TEXT_HTML.getCharSet().name());

      ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
      bos.write("<html><body><textarea>".getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

      String responseJson;
      if (jsonView == null) {
        responseJson = objectMapper.writeValueAsString(responseObject);
      } else {
        responseJson = objectMapper.writerWithView(jsonView).writeValueAsString(responseObject);
      }

      responseJson = responseJson.replace("&quot;", "\\&quot;");
      bos.write(responseJson.getBytes(ExtDirectSpringUtil.UTF8_CHARSET));
      bos.write("</textarea></body></html>".getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

      response.setContentLength(bos.size());
      FileCopyUtils.copy(bos.toByteArray(), response.getOutputStream());
    } else {

      response.setContentType(APPLICATION_JSON.toString());
      response.setCharacterEncoding(APPLICATION_JSON.getCharSet().name());

      ServletOutputStream outputStream = response.getOutputStream();

      if (!streamResponse) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        JsonGenerator jsonGenerator =
            objectMapper.getFactory().createJsonGenerator(bos, JsonEncoding.UTF8);

        if (jsonView == null) {
          objectMapper.writeValue(jsonGenerator, responseObject);
        } else {
          objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
        }

        response.setContentLength(bos.size());
        outputStream.write(bos.toByteArray());
        jsonGenerator.close();
      } else {
        JsonGenerator jsonGenerator =
            objectMapper.getFactory().createJsonGenerator(outputStream, JsonEncoding.UTF8);
        if (jsonView == null) {
          objectMapper.writeValue(jsonGenerator, responseObject);
        } else {
          objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
        }
        jsonGenerator.close();
      }

      outputStream.flush();
    }
  }
コード例 #17
0
 @Test
 public void testToString() throws Exception {
   MediaType mediaType = new MediaType("text", "plain", 0.7);
   String result = mediaType.toString();
   assertEquals("Invalid toString() returned", "text/plain;q=0.7", result);
 }
コード例 #18
0
  public SSEWriter(HttpServletResponse response) {
    this.response = response;

    response.setContentType(EVENT_STREAM.toString());
    response.setCharacterEncoding(EVENT_STREAM.getCharSet().name());
  }