Path: blob/master/src/jdk.dynalink/share/classes/jdk/dynalink/NamespaceOperation.java
41154 views
/*1* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file, and Oracle licenses the original version of this file under the BSD30* license:31*/32/*33Copyright 2016 Attila Szegedi3435Redistribution and use in source and binary forms, with or without36modification, are permitted provided that the following conditions are37met:38* Redistributions of source code must retain the above copyright39notice, this list of conditions and the following disclaimer.40* Redistributions in binary form must reproduce the above copyright41notice, this list of conditions and the following disclaimer in the42documentation and/or other materials provided with the distribution.43* Neither the name of the copyright holder nor the names of44contributors may be used to endorse or promote products derived from45this software without specific prior written permission.4647THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS48IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED49TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A50PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER51BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR52CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF53SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR54BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,55WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR56OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF57ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.58*/5960package jdk.dynalink;6162import java.util.Arrays;63import java.util.Objects;6465/**66* Describes an operation that operates on at least one {@link Namespace} of67* an object. E.g. a property getter would be described as68* <pre>69* Operation propertyGetter = new NamespaceOperation(70* StandardOperation.GET,71* StandardNamespace.PROPERTY);72* </pre>73* They are often combined with {@link NamedOperation}, e.g. to express a74* property getter for a property named "color", you would construct:75* <pre>76* Operation colorPropertyGetter = new NamedOperation(77* new NamespaceOperation(78* StandardOperation.GET,79* StandardNamespace.PROPERTY),80* "color");81* </pre>82* <p>While {@code NamespaceOperation} can be constructed directly, it is often convenient83* to use the {@link Operation#withNamespace(Namespace)} and {@link Operation#withNamespaces(Namespace...)} factory84* methods instead, e.g.:85* <pre>86* Operation getElementOrPropertyEmpty =87* StandardOperation.GET88* .withNamespace(StandardNamespace.PROPERTY)89* .named("color");90* </pre>91* <h2>Operations on multiple namespaces</h2>92* If multiple namespaces are specified, the namespaces are treated as93* alternatives to each other in order of preference. The semantics of94* such operation is "first applicable".95* That is, a composite of {@code GET:PROPERTY|ELEMENT:color} should be96* interpreted as <i>get the property named "color" on the object, but if the97* property does not exist, then get the collection element named "color"98* instead</i>.99* <p>100* Operations with multiple namespaces are helpful in implementation of languages that101* don't distinguish between one or more of the namespaces, or when expressing operations102* against objects that can be considered both ordinary objects and collections, e.g. Java103* {@link java.util.Map} objects. A {@code GET:PROPERTY|ELEMENT:empty} operation104* against a Java map will always match105* the {@link java.util.Map#isEmpty()} property, but106* {@code GET:ELEMENT|PROPERTY:empty} will actually match a map element with107* key {@code "empty"} if the map contains that key, and only fall back to the108* {@code isEmpty()} property getter if the map does not contain the key. If109* the source language mandates this semantics, it can be easily achieved using110* operations on multiple namespaces.111* <p>112* Even if the language itself doesn't distinguish between some of the113* namespaces, it can be helpful to map different syntaxes to different namespace orderings.114* E.g. the source expression {@code obj.color} could map to115* {@code GET:PROPERTY|ELEMENT|METHOD:color}, but a different source116* expression that looks like collection element access {@code obj[key]} could117* be expressed instead as {@code GET:ELEMENT|PROPERTY|METHOD} in order to favor the118* element semantics. Finally, if the retrieved value is subsequently called, then it makes sense119* to bring {@code METHOD} to the front of the namespace list: the getter part of the120* source expression {@code obj.color()} could be121* {@code GET:METHOD|PROPERTY|ELEMENT:color} and the one for122* {@code obj[key]()} could be {@code GET:METHOD|ELEMENT|PROPERTY}.123* <p>124* The base operation of a namespace operation can not itself be a namespace or named125* operation, but rather one of simple operations such are elements of126* {@link StandardOperation}. A namespace operation itself can serve as the base127* operation of a named operation, though; a typical way to construct e.g. the128* {@code GET:ELEMENT|PROPERTY:empty} from above would be:129* <pre>130* Operation getElementOrPropertyEmpty = StandardOperation.GET131* .withNamespaces(132* StandardNamespace.ELEMENT,133* StandardNamespace.PROPERTY)134* .named("empty");135* </pre>136*/137public final class NamespaceOperation implements Operation {138private final Operation baseOperation;139private final Namespace[] namespaces;140141/**142* Constructs a new namespace operation.143* @param baseOperation the base operation that operates on one or more namespaces.144* @param namespaces one or more namespaces this operation operates on.145* @throws IllegalArgumentException if less than one namespace is146* specified, or the base operation is itself a {@link NamespaceOperation} or a147* {@link NamedOperation}.148* @throws NullPointerException if either the {@code namespaces} array or any of its149* elements are {@code null}, or if {@code baseOperation} is {@code null}.150*/151public NamespaceOperation(final Operation baseOperation, final Namespace... namespaces) {152this.baseOperation = Objects.requireNonNull(baseOperation, "baseOperation is null");153if (baseOperation instanceof NamedOperation) {154throw new IllegalArgumentException("baseOperation is a NamedOperation");155} else if (baseOperation instanceof NamespaceOperation) {156throw new IllegalArgumentException("baseOperation is a NamespaceOperation");157}158159this.namespaces = Objects.requireNonNull(namespaces, "namespaces array is null").clone();160if (namespaces.length < 1) {161throw new IllegalArgumentException("Must specify at least one namespace");162}163for(int i = 0; i < namespaces.length; ++i) {164final int fi = i;165Objects.requireNonNull(namespaces[i], () -> "operations[" + fi + "] is null");166}167}168169/**170* Returns the base operation of this named operation.171* @return the base operation of this named operation.172*/173public Operation getBaseOperation() {174return baseOperation;175}176177/**178* Returns the namespaces in this namespace operation. The returned179* array is a copy and changes to it don't have effect on this180* object.181* @return the namespaces in this namespace operation.182*/183public Namespace[] getNamespaces() {184return namespaces.clone();185}186187/**188* Returns the number of namespaces in this namespace operation.189* @return the number of namespaces in this namespace operation.190*/191public int getNamespaceCount() {192return namespaces.length;193}194195/**196* Returns the i-th namespace in this namespace operation.197* @param i the namespace index198* @return the i-th namespace in this namespace operation.199* @throws IndexOutOfBoundsException if the index is out of range.200*/201public Namespace getNamespace(final int i) {202try {203return namespaces[i];204} catch (final ArrayIndexOutOfBoundsException e) {205throw new IndexOutOfBoundsException(Integer.toString(i));206}207}208209/**210* Returns true if this namespace operation contains a namespace equal to211* the specified namespace.212* @param namespace the namespace being searched for. Must not be null.213* @return true if the if this namespace operation contains a namespace214* equal to the specified namespace.215*/216public boolean contains(final Namespace namespace) {217Objects.requireNonNull(namespace);218for(final Namespace component: namespaces) {219if (component.equals(namespace)) {220return true;221}222}223return false;224}225226/**227* Returns true if the other object is also a namespace operation and their228* base operation and namespaces are equal.229* @param obj the object to compare to230* @return true if this object is equal to the other one, false otherwise.231*/232@Override233public boolean equals(final Object obj) {234if (obj instanceof NamespaceOperation) {235final NamespaceOperation other = (NamespaceOperation)obj;236return baseOperation.equals(other.baseOperation) && Arrays.equals(namespaces, other.namespaces);237}238return false;239}240241/**242* Returns the hash code of this namespace operation. Defined to be equal243* to {@code baseOperation.hashCode() + 31 * Arrays.hashCode(namespaces)}.244*/245@Override246public int hashCode() {247return baseOperation.hashCode() + 31 * Arrays.hashCode(namespaces);248}249250/**251* Returns the string representation of this namespace operation. Defined to252* be the {@code toString} of its base operation, followed by a colon character,253* followed with the list of its namespaces separated with the vertical line254* character (e.g. {@code "GET:PROPERTY|ELEMENT"}).255* @return the string representation of this namespace operation.256*/257@Override258public String toString() {259final StringBuilder b = new StringBuilder();260b.append(baseOperation).append(':');261b.append(namespaces[0]);262for(int i = 1; i < namespaces.length; ++i) {263b.append('|').append(namespaces[i]);264}265return b.toString();266}267268/**269* If the passed operation is a namespace operation, returns its270* {@link #getBaseOperation()}, otherwise returns the operation as is.271* @param op the operation272* @return the base operation of the passed operation.273*/274public static Operation getBaseOperation(final Operation op) {275return op instanceof NamespaceOperation ? ((NamespaceOperation )op).getBaseOperation() : op;276}277278/**279* If the passed operation is a namespace operation, returns its280* {@link #getNamespaces()}, otherwise returns an empty array.281* @param op the operation282* @return the namespaces of the passed operation.283*/284public static Namespace[] getNamespaces(final Operation op) {285return op instanceof NamespaceOperation ? ((NamespaceOperation)op).getNamespaces() : new Namespace[0];286}287288/**289* Returns true if the specified operation is a {@link NamespaceOperation}290* and its base operation is equal to the specified operation, and it291* contains the specified namespace. If it is not a {@link NamespaceOperation},292* then it returns false.293* @param op the operation. Must not be null.294* @param baseOperation the base operation being searched for. Must not be null.295* @param namespace the namespace being searched for. Must not be null.296* @return true if the if the passed operation is a {@link NamespaceOperation},297* its base operation equals the searched base operation, and contains a namespace298* equal to the searched namespace.299*/300public static boolean contains(final Operation op, final Operation baseOperation, final Namespace namespace) {301if (op instanceof NamespaceOperation) {302final NamespaceOperation no = (NamespaceOperation)op;303return no.baseOperation.equals(baseOperation) && no.contains(namespace);304}305return false;306}307}308309310