001package co.codewizards.cloudstore.ls.core.provider;
002
003import java.io.IOException;
004import java.io.InputStream;
005import java.io.ObjectInputStream;
006import java.lang.annotation.Annotation;
007import java.lang.reflect.Type;
008
009import javax.ws.rs.Consumes;
010import javax.ws.rs.WebApplicationException;
011import javax.ws.rs.core.MediaType;
012import javax.ws.rs.core.MultivaluedMap;
013import javax.ws.rs.ext.MessageBodyReader;
014import javax.ws.rs.ext.Provider;
015
016import co.codewizards.cloudstore.core.io.NoCloseInputStream;
017
018/**
019 * @author Marco หงุ่ยตระกูล-Schulze - marco at nightlabs dot de
020 */
021@Provider
022@Consumes(MediaTypeConst.APPLICATION_JAVA_NATIVE)
023public class JavaNativeMessageBodyReader
024implements MessageBodyReader<Object>
025{
026        private static volatile ClassLoader classLoader;
027
028        public static ClassLoader getClassLoader() {
029                return classLoader;
030        }
031        public static void setClassLoader(ClassLoader classLoader) {
032                JavaNativeMessageBodyReader.classLoader = classLoader;
033        }
034
035        @Override
036        public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
037                // We return always true, because we declared our media-type already in the @Consumes above and thus don't need to check it here.
038                // At least I hope we don't get consulted for media-types that were not declared in @Consumes.
039                return true;
040        }
041
042        @Override
043        public Object readFrom(
044                        final Class<Object> type, final Type genericType,
045                        final Annotation[] annotations, final MediaType mediaType,
046                        final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream
047        )
048        throws IOException, WebApplicationException
049        {
050                try (ObjectInputStream oin = new ExtObjectInputStream(new NoCloseInputStream(entityStream));) {
051                        final Object entity = oin.readObject();
052                        return entity;
053                } catch (ClassNotFoundException e) {
054                        throw new IOException(e);
055                }
056        }
057}