001/**
002 * Copyright 2015 DuraSpace, Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.fcrepo.oai.jersey;
017
018import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
019import org.openarchives.oai._2.OAIPMHtype;
020import org.openarchives.oai._2_0.oai_dc.OaiDcType;
021
022import javax.ws.rs.ext.ContextResolver;
023import javax.ws.rs.ext.Provider;
024import javax.xml.bind.JAXBContext;
025import javax.xml.bind.JAXBException;
026import javax.xml.bind.Marshaller;
027import java.io.IOException;
028import java.io.Writer;
029
030/**
031 * The type Oai jaxb provider.
032 * 
033 * @author Frank Asseg
034 */
035@Provider
036public class OaiJaxbProvider implements ContextResolver<Marshaller> {
037
038    private final Marshaller marshaller;
039
040    /**
041     * Instantiates a new Oai jaxb provider.
042     *
043     * @throws JAXBException the jAXB exception
044     */
045    public OaiJaxbProvider() throws JAXBException {
046        this.marshaller = JAXBContext.newInstance(OaiDcType.class, OAIPMHtype.class).createMarshaller();
047        this.marshaller.setProperty("com.sun.xml.bind.marshaller.CharacterEscapeHandler", new CharacterEscapeHandler() {
048            @Override
049            public void escape(final char[] chars, final int start, final int len, final boolean isAttr,
050                               final Writer writer) throws IOException {
051                final StringBuilder data = new StringBuilder(len);
052                for (int i = start; i < len + start; i++) {
053                    if (chars[i] == '&') {
054                        data.append("&amp;");
055                    } else {
056                        data.append(chars[i]);
057                    }
058                }
059                writer.write(data.toString());
060            }
061        });
062    }
063
064    @Override
065    public Marshaller getContext(final Class<?> aClass) {
066        if (aClass == OAIPMHtype.class) {
067            return this.marshaller;
068        }
069        return null;
070    }
071}