Java tutorial
/* * Copyright 2014 Guillaume Bailleul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.gbmb.collector.rest; import com.fasterxml.jackson.databind.ObjectMapper; import net.gbmb.collector.CollectionRecord; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotWritableException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; public class HttpRecordMessageConverter implements HttpMessageConverter<CollectionRecord> { private static final ObjectMapper MAPPER = new ObjectMapper(); @Override public boolean canRead(Class<?> aClass, MediaType mediaType) { if (aClass.equals(CollectionRecord.class)) { return MediaType.APPLICATION_JSON.includes(mediaType); } else { return false; } } @Override public boolean canWrite(Class<?> aClass, MediaType mediaType) { return false; } @Override public List<MediaType> getSupportedMediaTypes() { List<MediaType> ret = new ArrayList<MediaType>(1); ret.add(MediaType.APPLICATION_JSON); return ret; } @Override public CollectionRecord read(Class<? extends CollectionRecord> aClass, HttpInputMessage httpInputMessage) throws IOException { CollectionRecord cr = convert(httpInputMessage.getBody()); cr.setRecordDate(new Date()); return cr; } @Override public void write(CollectionRecord collectionRecord, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException { throw new HttpMessageNotWritableException("Not writable"); } public CollectionRecord convert(InputStream body) throws IOException { CollectionRecord cr = new CollectionRecord(); Map<String, Object> content = MAPPER.readValue(body, Map.class); cr.setContent(content); return cr; } }