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