1/*
2 * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * 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 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/*
27 * This file is available under and governed by the GNU General Public
28 * License version 2 only, as published by the Free Software Foundation.
29 * However, the following notice accompanied the original version of this
30 * file, and Oracle licenses the original version of this file under the BSD
31 * license:
32 */
33/*
34   Copyright 2016 Attila Szegedi
35
36   Licensed under both the Apache License, Version 2.0 (the "Apache License")
37   and the BSD License (the "BSD License"), with licensee being free to
38   choose either of the two at their discretion.
39
40   You may not use this file except in compliance with either the Apache
41   License or the BSD License.
42
43   If you choose to use this file in compliance with the Apache License, the
44   following notice applies to you:
45
46       You may obtain a copy of the Apache License at
47
48           http://www.apache.org/licenses/LICENSE-2.0
49
50       Unless required by applicable law or agreed to in writing, software
51       distributed under the License is distributed on an "AS IS" BASIS,
52       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
53       implied. See the License for the specific language governing
54       permissions and limitations under the License.
55
56   If you choose to use this file in compliance with the BSD License, the
57   following notice applies to you:
58
59       Redistribution and use in source and binary forms, with or without
60       modification, are permitted provided that the following conditions are
61       met:
62       * Redistributions of source code must retain the above copyright
63         notice, this list of conditions and the following disclaimer.
64       * Redistributions in binary form must reproduce the above copyright
65         notice, this list of conditions and the following disclaimer in the
66         documentation and/or other materials provided with the distribution.
67       * Neither the name of the copyright holder nor the names of
68         contributors may be used to endorse or promote products derived from
69         this software without specific prior written permission.
70
71       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
72       IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
73       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
74       PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
75       BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
76       CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
77       SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
78       BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
79       WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
80       OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
81       ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
82*/
83
84package jdk.dynalink;
85
86import java.util.Arrays;
87import java.util.Objects;
88
89/**
90 * Describes an operation that operates on at least one {@link Namespace} of
91 * an object. E.g. a property getter would be described as
92 * <pre>
93 * Operation propertyGetter = new NamespaceOperation(
94 *     StandardOperation.GET,
95 *     StandardNamespace.PROPERTY);
96 * </pre>
97 * They are often combined with {@link NamedOperation}, e.g. to express a
98 * property getter for a property named "color", you would construct:
99 * <pre>
100 * Operation colorPropertyGetter = new NamedOperation(
101 *     new NamespaceOperation(
102 *         StandardOperation.GET,
103 *         StandardNamespace.PROPERTY),
104 *     "color");
105 * </pre>
106 * <p>While {@code NamespaceOperation} can be constructed directly, it is often convenient
107 * to use the {@link Operation#withNamespace(Namespace)} and {@link Operation#withNamespaces(Namespace...)} factory
108 * methods instead, e.g.:
109 * <pre>
110 * Operation getElementOrPropertyEmpty =
111 *     StandardOperation.GET
112 *         .withNamespace(StandardNamespace.PROPERTY)
113 *         .named("color");
114 * </pre>
115 * <h3>Operations on multiple namespaces</h3>
116 * If multiple namespaces are specified, the namespaces are treated as
117 * alternatives to each other in order of preference. The semantics of
118 * such operation is "first applicable".
119 * That is, a composite of {@code GET:PROPERTY|ELEMENT:color} should be
120 * interpreted as <i>get the property named "color" on the object, but if the
121 * property does not exist, then get the collection element named "color"
122 * instead</i>.
123 * <p>
124 * Operations with multiple namespaces are helpful in implementation of languages that
125 * don't distinguish between one or more of the namespaces, or when expressing operations
126 * against objects that can be considered both ordinary objects and collections, e.g. Java
127 * {@link java.util.Map} objects. A {@code GET:PROPERTY|ELEMENT:empty} operation
128 * against a Java map will always match
129 * the {@link java.util.Map#isEmpty()} property, but
130 * {@code GET:ELEMENT|PROPERTY:empty} will actually match a map element with
131 * key {@code "empty"} if the map contains that key, and only fall back to the
132 * {@code isEmpty()} property getter if the map does not contain the key. If
133 * the source language mandates this semantics, it can be easily achieved using
134 * operations on multiple namespaces.
135 * <p>
136 * Even if the language itself doesn't distinguish between some of the
137 * namespaces, it can be helpful to map different syntaxes to different namespace orderings.
138 * E.g. the source expression {@code obj.color} could map to
139 * {@code GET:PROPERTY|ELEMENT|METHOD:color}, but a different source
140 * expression that looks like collection element access {@code obj[key]} could
141 * be expressed instead as {@code GET:ELEMENT|PROPERTY|METHOD} in order to favor the
142 * element semantics. Finally, if the retrieved value is subsequently called, then it makes sense
143 * to bring {@code METHOD} to the front of the namespace list: the getter part of the
144 * source expression {@code obj.color()} could be
145 * {@code GET:METHOD|PROPERTY|ELEMENT:color} and the one for
146 * {@code obj[key]()} could be {@code GET:METHOD|ELEMENT|PROPERTY}.
147 * <p>
148 * The base operation of a namespace operation can not itself be a namespace or named
149 * operation, but rather one of simple operations such are elements of
150 * {@link StandardOperation}. A namespace operation itself can serve as the base
151 * operation of a named operation, though; a typical way to construct e.g. the
152 * {@code GET:ELEMENT|PROPERTY:empty} from above would be:
153 * <pre>
154 * Operation getElementOrPropertyEmpty = StandardOperation.GET
155 *     .withNamespaces(
156 *         StandardNamespace.ELEMENT,
157 *         StandardNamespace.PROPERTY)
158 *     .named("empty");
159 * </pre>
160 */
161public final class NamespaceOperation implements Operation {
162    private final Operation baseOperation;
163    private final Namespace[] namespaces;
164
165    /**
166     * Constructs a new namespace operation.
167     * @param baseOperation the base operation that operates on one or more namespaces.
168     * @param namespaces one or more namespaces this operation operates on.
169     * @throws IllegalArgumentException if less than one namespace is
170     * specified, or the base operation is itself a {@link NamespaceOperation} or a
171     * {@link NamedOperation}.
172     * @throws NullPointerException if either the {@code namespaces} array or any of its
173     * elements are {@code null}, or if {@code baseOperation} is {@code null}.
174     */
175    public NamespaceOperation(final Operation baseOperation, final Namespace... namespaces) {
176        this.baseOperation = Objects.requireNonNull(baseOperation, "baseOperation is null");
177        if (baseOperation instanceof NamedOperation) {
178            throw new IllegalArgumentException("baseOperation is a NamedOperation");
179        } else if (baseOperation instanceof NamespaceOperation) {
180           throw new IllegalArgumentException("baseOperation is a NamespaceOperation");
181        }
182
183        this.namespaces = Objects.requireNonNull(namespaces, "namespaces array is null").clone();
184        if (namespaces.length < 1) {
185            throw new IllegalArgumentException("Must specify at least one namespace");
186        }
187        for(int i = 0; i < namespaces.length; ++i) {
188            final int fi = i;
189            Objects.requireNonNull(namespaces[i], () -> "operations[" + fi + "] is null");
190        }
191    }
192
193    /**
194     * Returns the base operation of this named operation.
195     * @return the base operation of this named operation.
196     */
197    public Operation getBaseOperation() {
198        return baseOperation;
199    }
200
201    /**
202     * Returns the namespaces in this namespace operation. The returned
203     * array is a copy and changes to it don't have effect on this
204     * object.
205     * @return the namespaces in this namespace operation.
206     */
207    public Namespace[] getNamespaces() {
208        return namespaces.clone();
209    }
210
211    /**
212     * Returns the number of namespaces in this namespace operation.
213     * @return the number of namespaces in this namespace operation.
214     */
215    public int getNamespaceCount() {
216        return namespaces.length;
217    }
218
219    /**
220     * Returns the i-th namespace in this namespace operation.
221     * @param i the namespace index
222     * @return the i-th namespace in this namespace operation.
223     * @throws IndexOutOfBoundsException if the index is out of range.
224     */
225    public Namespace getNamespace(final int i) {
226        try {
227            return namespaces[i];
228        } catch (final ArrayIndexOutOfBoundsException e) {
229            throw new IndexOutOfBoundsException(Integer.toString(i));
230        }
231    }
232
233    /**
234     * Returns true if this namespace operation contains a namespace equal to
235     * the specified namespace.
236     * @param namespace the namespace being searched for. Must not be null.
237     * @return true if the if this namespace operation contains a namespace
238     * equal to the specified namespace.
239     */
240    public boolean contains(final Namespace namespace) {
241        Objects.requireNonNull(namespace);
242        for(final Namespace component: namespaces) {
243            if (component.equals(namespace)) {
244                return true;
245            }
246        }
247        return false;
248    }
249
250    /**
251     * Returns true if the other object is also a namespace operation and their
252     * base operation and namespaces are equal.
253     * @param obj the object to compare to
254     * @return true if this object is equal to the other one, false otherwise.
255     */
256    @Override
257    public boolean equals(final Object obj) {
258        if (obj instanceof NamespaceOperation) {
259            final NamespaceOperation other = (NamespaceOperation)obj;
260            return baseOperation.equals(other.baseOperation) && Arrays.equals(namespaces, other.namespaces);
261        }
262        return false;
263    }
264
265    /**
266     * Returns the hash code of this namespace operation. Defined to be equal
267     * to {@code baseOperation.hashCode() + 31 * Arrays.hashCode(namespaces)}.
268     */
269    @Override
270    public int hashCode() {
271        return baseOperation.hashCode() + 31 * Arrays.hashCode(namespaces);
272    };
273
274    /**
275     * Returns the string representation of this namespace operation. Defined to
276     * be the {@code toString} of its base operation, followed by a colon character,
277     * followed with the list of its namespaces separated with the vertical line
278     * character (e.g. {@code "GET:PROPERTY|ELEMENT"}).
279     * @return the string representation of this namespace operation.
280     */
281    @Override
282    public String toString() {
283        final StringBuilder b = new StringBuilder();
284        b.append(baseOperation).append(':');
285        b.append(namespaces[0]);
286        for(int i = 1; i < namespaces.length; ++i) {
287            b.append('|').append(namespaces[i]);
288        }
289        return b.toString();
290    }
291
292    /**
293     * If the passed operation is a namespace operation, returns its
294     * {@link #getBaseOperation()}, otherwise returns the operation as is.
295     * @param op the operation
296     * @return the base operation of the passed operation.
297     */
298    public static Operation getBaseOperation(final Operation op) {
299        return op instanceof NamespaceOperation ? ((NamespaceOperation )op).getBaseOperation() : op;
300    }
301
302    /**
303     * If the passed operation is a namespace operation, returns its
304     * {@link #getNamespaces()}, otherwise returns an empty array.
305     * @param op the operation
306     * @return the namespaces of the passed operation.
307     */
308    public static Namespace[] getNamespaces(final Operation op) {
309        return op instanceof NamespaceOperation ? ((NamespaceOperation)op).getNamespaces() : new Namespace[0];
310    }
311
312    /**
313     * Returns true if the specified operation is a {@link NamespaceOperation}
314     * and its base operation is equal to the specified operation, and it
315     * contains the specified namespace. If it is not a {@link NamespaceOperation},
316     * then it returns false.
317     * @param op the operation. Must not be null.
318     * @param baseOperation the base operation being searched for. Must not be null.
319     * @param namespace the namespace being searched for. Must not be null.
320     * @return true if the if the passed operation is a {@link NamespaceOperation},
321     * its base operation equals the searched base operation, and contains a namespace
322     * equal to the searched namespace.
323     */
324    public static boolean contains(final Operation op, final Operation baseOperation, final Namespace namespace) {
325        if (op instanceof NamespaceOperation) {
326            final NamespaceOperation no = (NamespaceOperation)op;
327            return no.baseOperation.equals(baseOperation) && no.contains(namespace);
328        }
329        return false;
330    }
331}
332