DocumentHandler.java 14.1 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25 26 27 28 29 30 31
 */
package com.sun.beans.decoder;

import com.sun.beans.finder.ClassFinder;

import java.beans.ExceptionListener;

import java.io.IOException;
M
malenkov 已提交
32
import java.io.StringReader;
33 34 35 36 37 38 39 40

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
41 42 43
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
44 45 46 47 48 49 50 51 52

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

53 54
import sun.misc.SharedSecrets;

55 56 57 58 59 60 61 62 63 64
/**
 * The main class to parse JavaBeans XML archive.
 *
 * @since 1.7
 *
 * @author Sergey A. Malenkov
 *
 * @see ElementHandler
 */
public final class DocumentHandler extends DefaultHandler {
65 66 67 68
    private final AccessControlContext acc = AccessController.getContext();
    private final Map<String, Class<? extends ElementHandler>> handlers = new HashMap<>();
    private final Map<String, Object> environment = new HashMap<>();
    private final List<Object> objects = new ArrayList<>();
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

    private Reference<ClassLoader> loader;
    private ExceptionListener listener;
    private Object owner;

    private ElementHandler handler;

    /**
     * Creates new instance of document handler.
     */
    public DocumentHandler() {
        setElementHandler("java", JavaElementHandler.class); // NON-NLS: the element name
        setElementHandler("null", NullElementHandler.class); // NON-NLS: the element name
        setElementHandler("array", ArrayElementHandler.class); // NON-NLS: the element name
        setElementHandler("class", ClassElementHandler.class); // NON-NLS: the element name
        setElementHandler("string", StringElementHandler.class); // NON-NLS: the element name
        setElementHandler("object", ObjectElementHandler.class); // NON-NLS: the element name

        setElementHandler("void", VoidElementHandler.class); // NON-NLS: the element name
        setElementHandler("char", CharElementHandler.class); // NON-NLS: the element name
        setElementHandler("byte", ByteElementHandler.class); // NON-NLS: the element name
        setElementHandler("short", ShortElementHandler.class); // NON-NLS: the element name
        setElementHandler("int", IntElementHandler.class); // NON-NLS: the element name
        setElementHandler("long", LongElementHandler.class); // NON-NLS: the element name
        setElementHandler("float", FloatElementHandler.class); // NON-NLS: the element name
        setElementHandler("double", DoubleElementHandler.class); // NON-NLS: the element name
        setElementHandler("boolean", BooleanElementHandler.class); // NON-NLS: the element name

        // some handlers for new elements
        setElementHandler("new", NewElementHandler.class); // NON-NLS: the element name
        setElementHandler("var", VarElementHandler.class); // NON-NLS: the element name
        setElementHandler("true", TrueElementHandler.class); // NON-NLS: the element name
        setElementHandler("false", FalseElementHandler.class); // NON-NLS: the element name
        setElementHandler("field", FieldElementHandler.class); // NON-NLS: the element name
        setElementHandler("method", MethodElementHandler.class); // NON-NLS: the element name
        setElementHandler("property", PropertyElementHandler.class); // NON-NLS: the element name
    }

    /**
     * Returns the class loader used to instantiate objects.
     * If the class loader has not been explicitly set
     * then {@code null} is returned.
     *
     * @return the class loader used to instantiate objects
     */
    public ClassLoader getClassLoader() {
        return (this.loader != null)
                ? this.loader.get()
                : null;
    }

    /**
     * Sets the class loader used to instantiate objects.
     * If the class loader is not set
     * then default class loader will be used.
     *
     * @param loader  a classloader to use
     */
    public void setClassLoader(ClassLoader loader) {
        this.loader = new WeakReference<ClassLoader>(loader);
    }

    /**
     * Returns the exception listener for parsing.
     * The exception listener is notified
     * when handler catches recoverable exceptions.
     * If the exception listener has not been explicitly set
     * then default exception listener is returned.
     *
     * @return the exception listener for parsing
     */
    public ExceptionListener getExceptionListener() {
        return this.listener;
    }

    /**
     * Sets the exception listener for parsing.
     * The exception listener is notified
     * when handler catches recoverable exceptions.
     *
     * @param listener  the exception listener for parsing
     */
    public void setExceptionListener(ExceptionListener listener) {
        this.listener = listener;
    }

    /**
     * Returns the owner of this document handler.
     *
     * @return the owner of this document handler
     */
    public Object getOwner() {
        return this.owner;
    }

    /**
     * Sets the owner of this document handler.
     *
     * @param owner  the owner of this document handler
     */
    public void setOwner(Object owner) {
        this.owner = owner;
    }

    /**
     * Returns the handler for the element with specified name.
     *
     * @param name  the name of the element
     * @return the corresponding element handler
     */
    public Class<? extends ElementHandler> getElementHandler(String name) {
        Class<? extends ElementHandler> type = this.handlers.get(name);
        if (type == null) {
            throw new IllegalArgumentException("Unsupported element: " + name);
        }
        return type;
    }

    /**
     * Sets the handler for the element with specified name.
     *
     * @param name     the name of the element
     * @param handler  the corresponding element handler
     */
    public void setElementHandler(String name, Class<? extends ElementHandler> handler) {
        this.handlers.put(name, handler);
    }

    /**
     * Indicates whether the variable with specified identifier is defined.
     *
     * @param id  the identifier
     * @return @{code true} if the variable is defined;
     *         @{code false} otherwise
     */
    public boolean hasVariable(String id) {
        return this.environment.containsKey(id);
    }

    /**
     * Returns the value of the variable with specified identifier.
     *
     * @param id  the identifier
     * @return the value of the variable
     */
    public Object getVariable(String id) {
        if (!this.environment.containsKey(id)) {
            throw new IllegalArgumentException("Unbound variable: " + id);
        }
        return this.environment.get(id);
    }

    /**
     * Sets new value of the variable with specified identifier.
     *
     * @param id     the identifier
     * @param value  new value of the variable
     */
    public void setVariable(String id, Object value) {
        this.environment.put(id, value);
    }

    /**
     * Returns the array of readed objects.
     *
     * @return the array of readed objects
     */
    public Object[] getObjects() {
        return this.objects.toArray();
    }

    /**
     * Adds the object to the list of readed objects.
     *
     * @param object  the object that is readed from XML document
     */
    void addObject(Object object) {
        this.objects.add(object);
    }

M
malenkov 已提交
249 250 251 252 253 254 255 256
    /**
     * Disables any external entities.
     */
    @Override
    public InputSource resolveEntity(String publicId, String systemId) {
        return new InputSource(new StringReader(""));
    }

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    /**
     * Prepares this handler to read objects from XML document.
     */
    @Override
    public void startDocument() {
        this.objects.clear();
        this.handler = null;
    }

    /**
     * Parses opening tag of XML element
     * using corresponding element handler.
     *
     * @param uri         the namespace URI, or the empty string
     *                    if the element has no namespace URI or
     *                    if namespace processing is not being performed
     * @param localName   the local name (without prefix), or the empty string
     *                    if namespace processing is not being performed
     * @param qName       the qualified name (with prefix), or the empty string
     *                    if qualified names are not available
     * @param attributes  the attributes attached to the element
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        ElementHandler parent = this.handler;
        try {
            this.handler = getElementHandler(qName).newInstance();
            this.handler.setOwner(this);
            this.handler.setParent(parent);
        }
        catch (Exception exception) {
            throw new SAXException(exception);
        }
        for (int i = 0; i < attributes.getLength(); i++)
            try {
                String name = attributes.getQName(i);
                String value = attributes.getValue(i);
                this.handler.addAttribute(name, value);
            }
            catch (RuntimeException exception) {
                handleException(exception);
            }

        this.handler.startElement();
    }

    /**
     * Parses closing tag of XML element
     * using corresponding element handler.
     *
     * @param uri        the namespace URI, or the empty string
     *                   if the element has no namespace URI or
     *                   if namespace processing is not being performed
     * @param localName  the local name (without prefix), or the empty string
     *                   if namespace processing is not being performed
     * @param qName      the qualified name (with prefix), or the empty string
     *                   if qualified names are not available
     */
    @Override
    public void endElement(String uri, String localName, String qName) {
        try {
            this.handler.endElement();
        }
        catch (RuntimeException exception) {
            handleException(exception);
        }
        finally {
            this.handler = this.handler.getParent();
        }
    }

    /**
     * Parses character data inside XML element.
     *
     * @param chars   the array of characters
     * @param start   the start position in the character array
     * @param length  the number of characters to use
     */
    @Override
    public void characters(char[] chars, int start, int length) {
        if (this.handler != null) {
            try {
                while (0 < length--) {
                    this.handler.addCharacter(chars[start++]);
                }
            }
            catch (RuntimeException exception) {
                handleException(exception);
            }
        }
    }

    /**
     * Handles an exception using current exception listener.
     *
     * @param exception  an exception to handle
     * @see #setExceptionListener
     */
    public void handleException(Exception exception) {
        if (this.listener == null) {
            throw new IllegalStateException(exception);
        }
        this.listener.exceptionThrown(exception);
    }

    /**
     * Starts parsing of the specified input source.
     *
     * @param input  the input source to parse
     */
367 368 369
    public void parse(final InputSource input) {
        if ((this.acc == null) && (null != System.getSecurityManager())) {
            throw new SecurityException("AccessControlContext is not set");
370
        }
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
        AccessControlContext stack = AccessController.getContext();
        SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Void>() {
            public Void run() {
                try {
                    SAXParserFactory.newInstance().newSAXParser().parse(input, DocumentHandler.this);
                }
                catch (ParserConfigurationException exception) {
                    handleException(exception);
                }
                catch (SAXException wrapper) {
                    Exception exception = wrapper.getException();
                    if (exception == null) {
                        exception = wrapper;
                    }
                    handleException(exception);
                }
                catch (IOException exception) {
                    handleException(exception);
                }
                return null;
391
            }
392
        }, stack, this.acc);
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    }

    /**
     * Resolves class by name using current class loader.
     * This method handles exception using current exception listener.
     *
     * @param name  the name of the class
     * @return the object that represents the class
     */
    public Class<?> findClass(String name) {
        try {
            return ClassFinder.resolveClass(name, getClassLoader());
        }
        catch (ClassNotFoundException exception) {
            handleException(exception);
            return null;
        }
    }
}