001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.ws.converter;
015
016import java.io.IOException;
017import java.io.InputStream;
018import java.io.OutputStream;
019import java.nio.charset.StandardCharsets;
020import java.util.Scanner;
021import java.util.UUID;
022
023import org.springframework.http.HttpInputMessage;
024import org.springframework.http.HttpOutputMessage;
025import org.springframework.http.MediaType;
026import org.springframework.http.converter.AbstractHttpMessageConverter;
027
028public class UuidTextMessageConverter extends AbstractHttpMessageConverter<UUID> {
029
030  public UuidTextMessageConverter() {
031    super(MediaType.TEXT_PLAIN);
032  }
033
034  @Override
035  protected boolean supports(Class<?> clazz) {
036    return UUID.class.isAssignableFrom(clazz);
037  }
038
039  @Override
040  protected UUID readInternal(Class<? extends UUID> clazz, HttpInputMessage inputMessage)
041      throws IOException {
042    final String requestBody = toString(inputMessage.getBody());
043
044    return UUID.fromString(requestBody);
045  }
046
047  @Override
048  protected void writeInternal(UUID uuid, HttpOutputMessage outputMessage) throws IOException {
049    try (OutputStream os = outputMessage.getBody()) {
050      os.write(uuid.toString().getBytes(StandardCharsets.UTF_8));
051    }
052  }
053
054  /** '\A' matches the beginning of a string (but not an internal line). */
055  private static String toString(InputStream inputStream) {
056    final Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name());
057    return scanner.useDelimiter("\\A").next();
058  }
059}