DOMLinkerExporter.java revision 1786:80120e9b3273
1/*
2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 *   - Redistributions of source code must retain the above copyright
9 *     notice, this list of conditions and the following disclaimer.
10 *
11 *   - Redistributions in binary form must reproduce the above copyright
12 *     notice, this list of conditions and the following disclaimer in the
13 *     documentation and/or other materials provided with the distribution.
14 *
15 *   - Neither the name of Oracle nor the names of its
16 *     contributors may be used to endorse or promote products derived
17 *     from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31
32import java.lang.invoke.MethodHandle;
33import java.lang.invoke.MethodHandles;
34import java.lang.invoke.MethodType;
35import java.util.ArrayList;
36import java.util.List;
37import jdk.dynalink.CallSiteDescriptor;
38import jdk.dynalink.CompositeOperation;
39import jdk.dynalink.NamedOperation;
40import jdk.dynalink.Operation;
41import jdk.dynalink.StandardOperation;
42import jdk.dynalink.linker.GuardedInvocation;
43import jdk.dynalink.linker.GuardingDynamicLinker;
44import jdk.dynalink.linker.GuardingDynamicLinkerExporter;
45import jdk.dynalink.linker.LinkRequest;
46import jdk.dynalink.linker.LinkerServices;
47import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
48import jdk.dynalink.linker.support.Guards;
49import jdk.dynalink.linker.support.Lookup;
50import org.w3c.dom.Element;
51import org.w3c.dom.Node;
52import org.w3c.dom.NodeList;
53
54/**
55 * This is a dynalink pluggable linker (see http://openjdk.java.net/jeps/276).
56 * This linker handles XML DOM Element objects specially. This linker links
57 * special properties starting with "_" and treats those as child element names
58 * to access. This kind of child element access makes it easy to write XML DOM
59 * accessing scripts. See for example ./dom_linker_gutenberg.js.
60 */
61public final class DOMLinkerExporter extends GuardingDynamicLinkerExporter {
62    static {
63        System.out.println("pluggable dynalink DOM linker loaded");
64    }
65
66    // return List of child Elements of the given Element matching the given name.
67    private static List<Element> getChildElements(final Element elem, final String name) {
68        final NodeList nodeList = elem.getChildNodes();
69        final List<Element> childElems = new ArrayList<>();
70        final int len = nodeList.getLength();
71        for (int i = 0; i < len; i++) {
72            final Node node = nodeList.item(i);
73            if (node.getNodeType() == Node.ELEMENT_NODE &&
74                ((Element)node).getTagName().equals(name)) {
75                childElems.add((Element)node);
76            }
77        }
78        return childElems;
79    }
80
81    // method that returns either unique child element matching given name
82    // or a list of child elements of that name (if there are more than one matches).
83    public static Object getElementsByName(final Object elem, final String name) {
84        final List<Element> elems = getChildElements((Element)elem, name);
85        return elems.size() == 1? elems.get(0) : elems;
86    }
87
88    // method to extract text context under a given DOM Element
89    public static Object getElementText(final Object elem) {
90        final NodeList nodeList = ((Element)elem).getChildNodes();
91        final int len = nodeList.getLength();
92        final StringBuilder text = new StringBuilder();
93        for (int i = 0; i < len; i++) {
94            final Node node = nodeList.item(i);
95            if (node.getNodeType() == Node.TEXT_NODE) {
96                text.append(node.getNodeValue());
97            }
98        }
99        return text.toString();
100    }
101
102    private static final MethodHandle ELEMENTS_BY_NAME;
103    private static final MethodHandle ELEMENT_TEXT;
104    private static final MethodHandle IS_ELEMENT;
105    static {
106        ELEMENTS_BY_NAME = Lookup.PUBLIC.findStatic(DOMLinkerExporter.class,
107            "getElementsByName",
108            MethodType.methodType(Object.class, Object.class, String.class));
109        ELEMENT_TEXT = Lookup.PUBLIC.findStatic(DOMLinkerExporter.class,
110            "getElementText",
111            MethodType.methodType(Object.class, Object.class));
112        IS_ELEMENT = Guards.isInstance(Element.class, MethodType.methodType(Boolean.TYPE, Object.class));
113    }
114
115    @Override
116    public List<GuardingDynamicLinker> get() {
117        final ArrayList<GuardingDynamicLinker> linkers = new ArrayList<>();
118        linkers.add(new TypeBasedGuardingDynamicLinker() {
119            @Override
120            public boolean canLinkType(final Class<?> type) {
121                return Element.class.isAssignableFrom(type);
122            }
123
124            @Override
125            public GuardedInvocation getGuardedInvocation(final LinkRequest request,
126                final LinkerServices linkerServices) throws Exception {
127                final Object self = request.getReceiver();
128                if (! (self instanceof Element)) {
129                    return null;
130                }
131
132                final CallSiteDescriptor desc = request.getCallSiteDescriptor();
133                final Operation op = desc.getOperation();
134                final Object name = NamedOperation.getName(op);
135                final boolean getProp = CompositeOperation.contains(
136                        NamedOperation.getBaseOperation(op),
137                        StandardOperation.GET_PROPERTY);
138                if (getProp && name instanceof String) {
139                    final String nameStr = (String)name;
140
141                    // Treat names starting with "_" as special names.
142                    // Everything else is linked other dynalink bean linker!
143                    // This avoids collision with Java methods of org.w3c.dom.Element class
144                    // Assumption is that Java APIs won't start with "_" character!!
145                    if (nameStr.equals("_")) {
146                        // short-hand to get text content under a given DOM Element
147                        return new GuardedInvocation(ELEMENT_TEXT, IS_ELEMENT);
148                    } else if (nameStr.startsWith("_")) {
149                        return new GuardedInvocation(
150                            MethodHandles.insertArguments(ELEMENTS_BY_NAME, 1, nameStr.substring(1)),
151                            IS_ELEMENT);
152                    }
153
154                }
155
156                return null;
157            }
158        });
159        return linkers;
160    }
161}
162