DOMLinkerExporter.java revision 1805:7caf1f762f1d
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.NamedOperation;
39import jdk.dynalink.NamespaceOperation;
40import jdk.dynalink.Operation;
41import jdk.dynalink.StandardNamespace;
42import jdk.dynalink.StandardOperation;
43import jdk.dynalink.linker.GuardedInvocation;
44import jdk.dynalink.linker.GuardingDynamicLinker;
45import jdk.dynalink.linker.GuardingDynamicLinkerExporter;
46import jdk.dynalink.linker.LinkRequest;
47import jdk.dynalink.linker.LinkerServices;
48import jdk.dynalink.linker.TypeBasedGuardingDynamicLinker;
49import jdk.dynalink.linker.support.Guards;
50import jdk.dynalink.linker.support.Lookup;
51import org.w3c.dom.Element;
52import org.w3c.dom.Node;
53import org.w3c.dom.NodeList;
54
55/**
56 * This is a dynalink pluggable linker (see http://openjdk.java.net/jeps/276).
57 * This linker handles XML DOM Element objects specially. This linker links
58 * special properties starting with "_" and treats those as child element names
59 * to access. This kind of child element access makes it easy to write XML DOM
60 * accessing scripts. See for example ./dom_linker_gutenberg.js.
61 */
62public final class DOMLinkerExporter extends GuardingDynamicLinkerExporter {
63    static {
64        System.out.println("pluggable dynalink DOM linker loaded");
65    }
66
67    // return List of child Elements of the given Element matching the given name.
68    private static List<Element> getChildElements(final Element elem, final String name) {
69        final NodeList nodeList = elem.getChildNodes();
70        final List<Element> childElems = new ArrayList<>();
71        final int len = nodeList.getLength();
72        for (int i = 0; i < len; i++) {
73            final Node node = nodeList.item(i);
74            if (node.getNodeType() == Node.ELEMENT_NODE &&
75                ((Element)node).getTagName().equals(name)) {
76                childElems.add((Element)node);
77            }
78        }
79        return childElems;
80    }
81
82    // method that returns either unique child element matching given name
83    // or a list of child elements of that name (if there are more than one matches).
84    public static Object getElementsByName(final Object elem, final String name) {
85        final List<Element> elems = getChildElements((Element)elem, name);
86        return elems.size() == 1? elems.get(0) : elems;
87    }
88
89    // method to extract text context under a given DOM Element
90    public static Object getElementText(final Object elem) {
91        final NodeList nodeList = ((Element)elem).getChildNodes();
92        final int len = nodeList.getLength();
93        final StringBuilder text = new StringBuilder();
94        for (int i = 0; i < len; i++) {
95            final Node node = nodeList.item(i);
96            if (node.getNodeType() == Node.TEXT_NODE) {
97                text.append(node.getNodeValue());
98            }
99        }
100        return text.toString();
101    }
102
103    private static final MethodHandle ELEMENTS_BY_NAME;
104    private static final MethodHandle ELEMENT_TEXT;
105    private static final MethodHandle IS_ELEMENT;
106    static {
107        ELEMENTS_BY_NAME = Lookup.PUBLIC.findStatic(DOMLinkerExporter.class,
108            "getElementsByName",
109            MethodType.methodType(Object.class, Object.class, String.class));
110        ELEMENT_TEXT = Lookup.PUBLIC.findStatic(DOMLinkerExporter.class,
111            "getElementText",
112            MethodType.methodType(Object.class, Object.class));
113        IS_ELEMENT = Guards.isInstance(Element.class, MethodType.methodType(Boolean.TYPE, Object.class));
114    }
115
116    @Override
117    public List<GuardingDynamicLinker> get() {
118        final ArrayList<GuardingDynamicLinker> linkers = new ArrayList<>();
119        linkers.add(new TypeBasedGuardingDynamicLinker() {
120            @Override
121            public boolean canLinkType(final Class<?> type) {
122                return Element.class.isAssignableFrom(type);
123            }
124
125            @Override
126            public GuardedInvocation getGuardedInvocation(final LinkRequest request,
127                final LinkerServices linkerServices) throws Exception {
128                final Object self = request.getReceiver();
129                if (! (self instanceof Element)) {
130                    return null;
131                }
132
133                final CallSiteDescriptor desc = request.getCallSiteDescriptor();
134                final Operation op = desc.getOperation();
135                final Object name = NamedOperation.getName(op);
136                final boolean getProp = NamespaceOperation.contains(
137                        NamedOperation.getBaseOperation(op),
138                        StandardOperation.GET, StandardNamespace.PROPERTY);
139                if (getProp && name instanceof String) {
140                    final String nameStr = (String)name;
141
142                    // Treat names starting with "_" as special names.
143                    // Everything else is linked other dynalink bean linker!
144                    // This avoids collision with Java methods of org.w3c.dom.Element class
145                    // Assumption is that Java APIs won't start with "_" character!!
146                    if (nameStr.equals("_")) {
147                        // short-hand to get text content under a given DOM Element
148                        return new GuardedInvocation(ELEMENT_TEXT, IS_ELEMENT);
149                    } else if (nameStr.startsWith("_")) {
150                        return new GuardedInvocation(
151                            MethodHandles.insertArguments(ELEMENTS_BY_NAME, 1, nameStr.substring(1)),
152                            IS_ELEMENT);
153                    }
154
155                }
156
157                return null;
158            }
159        });
160        return linkers;
161    }
162}
163