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