001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the License.
004 *
005 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
006 * specific language governing permission and limitations under the License.
007 *
008 * When distributing Covered Software, include this CDDL Header Notice in each file and include
009 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
010 * Header, with the fields enclosed by brackets [] replaced by your own identifying
011 * information: "Portions copyright [year] [name of copyright owner]".
012 *
013 * Copyright 2015 ForgeRock AS.
014 */
015
016package org.forgerock.util.xml;
017
018import java.io.InputStream;
019import java.io.StringReader;
020
021import org.xml.sax.InputSource;
022import org.xml.sax.helpers.DefaultHandler;
023
024/**
025 * This is a custom XML handler to load the dtds from the classpath This should
026 * be used by all the xml parsing document builders to set the default entity
027 * resolvers. This will avoid to have the dtds having specified in a fixed
028 * directory that will get replaced during installation This will need to
029 * specify the dtds as follows jar://com/sun/identity/sm/sms.dtd Bundle all the
030 * dtds along with the jar files and
031 */
032public class XMLHandler extends DefaultHandler {
033
034    /* FIXME: does this class need to be non-final and public? */
035
036    /**
037     * Creates a new XML handler.
038     */
039    public XMLHandler() {
040        // No impl.
041    }
042
043    @Override
044    public InputSource resolveEntity(final String aPublicID, final String aSystemID) {
045        final String sysid = aSystemID.trim();
046
047        if (sysid.toLowerCase().startsWith("jar://")) {
048            final String dtdname = sysid.substring(5);
049            final InputStream is = getClass().getResourceAsStream(dtdname);
050            if (is != null) {
051                return new InputSource(is);
052            }
053        }
054
055        /*
056         * make sure that we do NOT return null here, as xerces would fall back
057         * to the default entity resolver and try to resolve the entity with
058         * that
059         */
060        return new InputSource(new StringReader(""));
061    }
062}