Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 2010-2011 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * http://glassfish.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 
 package com.sun.jersey.core.provider.jaxb;
 
 
 import java.util.List;

Author(s):
Paul.Sandoz@Sun.Com
 
An abstract provider for T[], Collection<T>, and its subtypes as long as they have the public default constructor or are interfaces implemented by one the following classes: T must be a JAXB type annotated with javax.xml.bind.annotation.XmlRootElement.

Implementing classes may extend this class to provide specific marshalling and unmarshalling behaviour.

When unmarshalling a javax.xml.bind.UnmarshalException will result in a javax.ws.rs.WebApplicationException being thrown with a status of 400 (Client error), and a javax.xml.bind.JAXBException will result in a javax.ws.rs.WebApplicationException being thrown with a status of 500 (Internal Server error).

When marshalling a javax.xml.bind.JAXBException will result in a javax.ws.rs.WebApplicationException being thrown with a status of 500 (Internal Server error).

Author(s):
Paul.Sandoz@Sun.Com
Martin Matula
public abstract class AbstractListElementProvider extends AbstractJAXBProvider<Object> {
    private static final Class[] DEFAULT_IMPLS = new Class[] {
        ArrayList.class,
        LinkedList.class,
        HashSet.class,
        TreeSet.class,
        Stack.class
    };

    
This is to allow customized JAXB collections checking.

See also:
verifyArrayType and verifyGenericype methods
    public static interface JaxbTypeChecker {
        boolean isJaxbType(Class type);
    }
    private static final JaxbTypeChecker DefaultJaxbTypeCHECKER = new JaxbTypeChecker() {
        @Override
        public boolean isJaxbType(Class type) {
            return type.isAnnotationPresent(XmlRootElement.class) ||
                type.isAnnotationPresent(XmlType.class);
        }
    };
        super(ps);
    }
    public AbstractListElementProvider(Providers psMediaType mt) {
        super(psmt);
    }
    @Override
    public boolean isReadable(Class<?> typeType genericTypeAnnotation annotations[], MediaType mediaType) {
        if (verifyCollectionSubclass(type)) {
            return verifyGenericType(genericType) && isSupported(mediaType);
        } else if (type.isArray()) {
            return verifyArrayType(type) && isSupported(mediaType);
        } else
            return false;
    }
    @Override
    public boolean isWriteable(Class<?> typeType genericTypeAnnotation annotations[], MediaType mediaType) {
        if (Collection.class.isAssignableFrom(type)) {
            return verifyGenericType(genericType) && isSupported(mediaType);
        } else if (type.isArray()) {
            return verifyArrayType(type) && isSupported(mediaType);
        } else
            return false;
    }
    public static boolean verifyCollectionSubclass(Class<?> type) {
        try {
            if (Collection.class.isAssignableFrom(type)) {
                for (Class c : ) {
                    if (type.isAssignableFrom(c)) {
                        return true;
                    }
                }
                return !Modifier.isAbstract(type.getModifiers()) && Modifier.isPublic(type.getConstructor().getModifiers());
            }
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(AbstractListElementProvider.class.getName()).log(.nullex);
        } catch (SecurityException ex) {
            Logger.getLogger(AbstractListElementProvider.class.getName()).log(.nullex);
        }
        return false;
    }
    private static boolean verifyArrayType(Class type) {
        return verifyArrayType(type);
    }


    
The method could be used to check if given type is an array of JAXB beans. It allows customizing the "is this a JAXB bean?" part.

Parameters:
type the array to be checked
checker allows JAXB bean check customization
Returns:
true if given type is an array of JAXB beans
    public static boolean verifyArrayType(Class typeJaxbTypeChecker checker) {
        type = type.getComponentType();
        return checker.isJaxbType(type) ||
                JAXBElement.class.isAssignableFrom(type);
    }
    private static boolean verifyGenericType(Type genericType) {
        return verifyGenericType(genericType);
    }

    
The method could be used to check if given type is a collection of JAXB beans. It allows customizing the "is this a JAXB bean?" part.

Parameters:
genericType the type to be checked
checker allows JAXB bean check customization
Returns:
true if given type is a collection of JAXB beans
    public static boolean verifyGenericType(Type genericTypeJaxbTypeChecker checker) {
        if (!(genericType instanceof ParameterizedType)) return false;
        final ParameterizedType pt = (ParameterizedType)genericType;
        if (pt.getActualTypeArguments().length > 1) return false;
        final Type ta = pt.getActualTypeArguments()[0];
        if (ta instanceof ParameterizedType) {
            ParameterizedType lpt = (ParameterizedTypeta;
            return (lpt.getRawType() instanceof Class) &&
                    JAXBElement.class.isAssignableFrom((Classlpt.getRawType());
        }
        if (!(pt.getActualTypeArguments()[0] instanceof Class)) return false;
        final Class listClass = (Class)pt.getActualTypeArguments()[0];
        return checker.isJaxbType(listClass);
    }
    @Override
    public final void writeTo(
            Object t,
            Class<?> type,
            Type genericType,
            Annotation annotations[],
            MediaType mediaType,
            MultivaluedMap<StringObjecthttpHeaders,
            OutputStream entityStreamthrows IOException {
        try {
            final Collection c = (type.isArray())
                    ? Arrays.asList((Object[])t)
                    : (Collection)t;
            final Class elementType = getElementClass(typegenericType);
            final Charset charset = getCharset(mediaType);
            final String charsetName = charset.name();
            final Marshaller m = getMarshaller(elementTypemediaType);
            m.setProperty(.true);
            if (charset != ) {
                m.setProperty(.charsetName);
            }
            setHeader(mannotations);
            writeList(elementTypecmediaTypecharsetmentityStream);
        } catch (JAXBException ex) {
            throw new WebApplicationException(ex.);
        }
    }

    
Write a collection of JAXB objects as child elements of the root element.

Parameters:
elementType the element type in the collection.
t the collecton to marshall
mediaType the media type
c the charset
m the marshaller
entityStream the output stream to marshall the collection
Throws:
javax.xml.bind.JAXBException
java.io.IOException
    public abstract void writeList(Class<?> elementTypeCollection<?> t,
            MediaType mediaTypeCharset c,
            Marshaller mOutputStream entityStream)
            throws JAXBExceptionIOException;
    @Override
    public final Object readFrom(
            Class<Objecttype,
            Type genericType,
            Annotation annotations[],
            MediaType mediaType,
            MultivaluedMap<StringStringhttpHeaders,
            InputStream entityStreamthrows IOException {
        try {
            final Class elementType = getElementClass(typegenericType);
            final Unmarshaller u = getUnmarshaller(elementTypemediaType);
            final XMLStreamReader r = getXMLStreamReader(elementTypemediaTypeuentityStream);
            boolean jaxbElement = false;
            Collection l = null;
            if (type.isArray()) {
                l = new ArrayList();
            } else {
                try {
                    l = (Collectiontype.newInstance();
                } catch (Exception e) {
                    for (Class c : ) {
                        if (type.isAssignableFrom(c)) {
                            try {
                                l = (Collectionc.newInstance();
                                break;
                            } catch (InstantiationException ex) {
                                Logger.getLogger(AbstractListElementProvider.class.getName()).log(.nullex);
                            } catch (IllegalAccessException ex) {
                                Logger.getLogger(AbstractListElementProvider.class.getName()).log(.nullex);
                            }
                        }
                    }
                }
            }
            // Move to root element
            int event = r.next();
            while (event != .)
                event = r.next();
            // Move to first child (if any)
            event = r.next();
            while (event != . &&
                    event != .)
                event = r.next();
            while (event != .) {
                if (elementType.isAnnotationPresent(XmlRootElement.class)) {
                    l.add(u.unmarshal(r));
                } else if (elementType.isAnnotationPresent(XmlType.class)) {
                    l.add(u.unmarshal(relementType).getValue());
                } else {
                    l.add(u.unmarshal(relementType));
                    jaxbElement = true;
                }
                // Move to next peer (if any)
                event = r.getEventType();
                while (event != . &&
                        event != .)
                    event = r.next();
            }
            return (type.isArray())
                    ? createArray((ListljaxbElement ? JAXBElement.class : elementType)
                    : l;
        } catch (UnmarshalException ex) {
            throw new WebApplicationException(ex.);
        } catch (XMLStreamException ex) {
            throw new WebApplicationException(ex.);
        } catch (JAXBException ex) {
            throw new WebApplicationException(ex.);
        }
    }
    private Object createArray(List lClass componentType) {
        Object array = Array.newInstance(componentTypel.size());
        for (int i = 0; i < l.size(); i++)
            Array.set(arrayil.get(i));
        return array;
    }

    
Get the XMLStreamReader for unmarshalling.

Parameters:
elementType the individual element type.
mediaType the media type.
unmarshaller the unmarshaller as a carrier of possible config options.
entityStream the input stream.
Returns:
the XMLStreamReader.
Throws:
javax.xml.stream.XMLStreamException
    protected abstract XMLStreamReader getXMLStreamReader(Class<?> elementTypeMediaType mediaTypeUnmarshaller unmarshaller,
            InputStream entityStream)
            throws XMLStreamException;
    protected Class getElementClass(Class<?> typeType genericType) {
        Type ta;
        if (genericType instanceof ParameterizedType) {
            // List case
            ta = ((ParameterizedTypegenericType).getActualTypeArguments()[0];
        } else if (genericType instanceof GenericArrayType) {
            // GenericArray case
            ta = ((GenericArrayTypegenericType).getGenericComponentType();
        } else {
            // Array case
            ta = type.getComponentType();
        }
        if (ta instanceof ParameterizedType) {
            // JAXBElement case
            ta = ((ParameterizedTypeta).getActualTypeArguments()[0];
        }
        return (Classta;
    }
    private final Inflector inflector = Inflector.getInstance();
    private String convertToXmlName(final String name) {
        return name.replace("$""_");
    }
    protected final String getRootElementName(Class<?> elementType) {
        if(isXmlRootElementProcessing()) {
            return convertToXmlName(.pluralize(.demodulize(getElementName(elementType))));
        } else {
            return convertToXmlName(.decapitalize(.pluralize(.demodulize(elementType.getName()))));
        }
    }
    protected final String getElementName(Class<?> elementType) {
        String name = elementType.getName();
        XmlRootElement xre = elementType.getAnnotation(XmlRootElement.class);
        if (xre != null && !xre.name().equals("##default")) {
            name = xre.name();
        }
        return name;
    }
New to GrepCode? Check out our FAQ X