This project has retired. For details please refer to its Attic page.
Source code
001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.reef.tang.implementation.java;
020
021import org.apache.reef.tang.ClassHierarchy;
022import org.apache.reef.tang.ExternalConstructor;
023import org.apache.reef.tang.JavaClassHierarchy;
024import org.apache.reef.tang.annotations.Name;
025import org.apache.reef.tang.annotations.NamedParameter;
026import org.apache.reef.tang.exceptions.BindException;
027import org.apache.reef.tang.exceptions.ClassHierarchyException;
028import org.apache.reef.tang.exceptions.NameResolutionException;
029import org.apache.reef.tang.exceptions.ParseException;
030import org.apache.reef.tang.formats.ParameterParser;
031import org.apache.reef.tang.types.*;
032import org.apache.reef.tang.util.MonotonicTreeMap;
033import org.apache.reef.tang.util.ReflectionUtilities;
034
035import java.lang.reflect.Type;
036import java.net.URL;
037import java.net.URLClassLoader;
038import java.util.*;
039
040public class ClassHierarchyImpl implements JavaClassHierarchy {
041  // TODO Want to add a "register namespace" method, but Java is not designed
042  // to support such things.
043  // There are third party libraries that would help, but they can fail if the
044  // relevant jar has not yet been loaded.  Tint works around this using such
045  // a library.
046
047  /**
048   * The ParameterParser that this ClassHierarchy uses to parse default values.
049   * Custom parameter parsers allow applications to extend the set of classes
050   * that Tang can parse.
051   */
052  public final ParameterParser parameterParser = new ParameterParser();
053  /**
054   * The classloader that was used to populate this class hierarchy.
055   */
056  private final URLClassLoader loader;
057  /**
058   * The jars that are reflected by that loader.  These are in addition to
059   * whatever jars are available by the default classloader (i.e., the one
060   * that loaded Tang.  We need this list so that we can merge class hierarchies
061   * that are backed by different classpaths.
062   */
063  private final List<URL> jars;
064  /**
065   * A reference to the root package which is a root of a tree of nodes.
066   * The children of each node in the tree are accessible by name, and the
067   * structure of the tree mirrors Java's package namespace.
068   */
069  private final PackageNode namespace;
070  /**
071   * A map from short name to named parameter node.  This is only used to
072   * sanity check short names so that name clashes get resolved.
073   */
074  private final Map<String, NamedParameterNode<?>> shortNames = new MonotonicTreeMap<>();
075
076  @SuppressWarnings("unchecked")
077  public ClassHierarchyImpl() {
078    this(new URL[0], new Class[0]);
079  }
080
081  @SuppressWarnings("unchecked")
082  public ClassHierarchyImpl(URL... jars) {
083    this(jars, new Class[0]);
084  }
085
086  public ClassHierarchyImpl(URL[] jars, Class<? extends ExternalConstructor<?>>[] parameterParsers) {
087    this.namespace = JavaNodeFactory.createRootPackageNode();
088    this.jars = new ArrayList<>(Arrays.asList(jars));
089    this.loader = new URLClassLoader(jars, this.getClass().getClassLoader());
090    for (Class<? extends ExternalConstructor<?>> p : parameterParsers) {
091      try {
092        parameterParser.addParser(p);
093      } catch (BindException e) {
094        throw new IllegalArgumentException("Could not register parameter parsers", e);
095      }
096    }
097  }
098
099  /**
100   * A helper method that returns the parsed default value of a given
101   * NamedParameter.
102   *
103   * @return null or an empty set if there is no default value, the default value (or set of values) otherwise.
104   * @throws ClassHierarchyException if a default value was specified, but could not be parsed, or if a set of
105   *                                 values were specified for a non-set parameter.
106   */
107  @SuppressWarnings("unchecked")
108  @Override
109  public <T> T parseDefaultValue(NamedParameterNode<T> name) {
110    String[] vals = name.getDefaultInstanceAsStrings();
111    T[] ret = (T[]) new Object[vals.length];
112    for (int i = 0; i < vals.length; i++) {
113      String val = vals[i];
114      try {
115        ret[i] = parse(name, val);
116      } catch (ParseException e) {
117        throw new ClassHierarchyException("Could not parse default value", e);
118      }
119    }
120    if (name.isSet()) {
121      return (T) new HashSet<T>(Arrays.asList(ret));
122    } else if (name.isList()) {
123      return (T) new ArrayList<T>(Arrays.asList(ret));
124    } else {
125      if (ret.length == 0) {
126        return null;
127      } else if (ret.length == 1) {
128        return ret[0];
129      } else {
130        throw new IllegalStateException("Multiple defaults for non-set named parameter! " + name.getFullName());
131      }
132    }
133  }
134
135  /**
136   * Parse a string, assuming that it is of the type expected by a given NamedParameter.
137   * <p/>
138   * This method does not deal with sets; if the NamedParameter is set valued, then the provided
139   * string should correspond to a single member of the set.  It is up to the caller to call parse
140   * once for each value that should be parsed as a member of the set.
141   *
142   * @return a non-null reference to the parsed value.
143   */
144  @Override
145  @SuppressWarnings("unchecked")
146  public <T> T parse(NamedParameterNode<T> np, String value) throws ParseException {
147    final ClassNode<T> iface;
148    try {
149      iface = (ClassNode<T>) getNode(np.getFullArgName());
150    } catch (NameResolutionException e) {
151      throw new IllegalStateException("Could not parse validated named parameter argument type.  NamedParameter is " + np.getFullName() + " argument type is " + np.getFullArgName());
152    }
153    Class<?> clazz;
154    String fullName;
155    try {
156      clazz = (Class<?>) classForName(iface.getFullName());
157      fullName = null;
158    } catch (ClassNotFoundException e) {
159      clazz = null;
160      fullName = iface.getFullName();
161    }
162    try {
163      if (clazz != null) {
164        return (T) parameterParser.parse(clazz, value);
165      } else {
166        return parameterParser.parse(fullName, value);
167      }
168    } catch (UnsupportedOperationException e) {
169      try {
170        final Node impl = getNode(value);
171        if (impl instanceof ClassNode) {
172          if (isImplementation(iface, (ClassNode<?>) impl)) {
173            return (T) impl;
174          }
175        }
176        throw new ParseException("Name<" + iface.getFullName() + "> " + np.getFullName() + " cannot take non-subclass " + impl.getFullName(), e);
177      } catch (NameResolutionException e2) {
178        throw new ParseException("Name<" + iface.getFullName() + "> " + np.getFullName() + " cannot take non-class " + value, e);
179      }
180    }
181  }
182
183  /**
184   * Helper method that converts a String to a Class using this
185   * ClassHierarchy's classloader.
186   */
187  @Override
188  public Class<?> classForName(String name) throws ClassNotFoundException {
189    return ReflectionUtilities.classForName(name, loader);
190  }
191
192  private <T, U> Node buildPathToNode(Class<U> clazz)
193      throws ClassHierarchyException {
194    String[] path = clazz.getName().split("\\$");
195
196    Node root = namespace;
197    for (int i = 0; i < path.length - 1; i++) {
198      root = root.get(path[i]);
199    }
200
201    if (root == null) {
202      throw new NullPointerException();
203    }
204    Node parent = root;
205
206    Type argType = ReflectionUtilities.getNamedParameterTargetOrNull(clazz);
207
208    if (argType == null) {
209      return JavaNodeFactory.createClassNode(parent, clazz);
210    } else {
211
212      @SuppressWarnings("unchecked")
213      // checked inside of NamedParameterNode, using reflection.
214          NamedParameterNode<T> np = JavaNodeFactory.createNamedParameterNode(
215          parent, (Class<? extends Name<T>>) clazz, argType);
216
217      if (parameterParser.canParse(ReflectionUtilities.getFullName(argType))) {
218        if (clazz.getAnnotation(NamedParameter.class).default_class() != Void.class) {
219          throw new ClassHierarchyException("Named parameter " + ReflectionUtilities.getFullName(clazz) + " defines default implementation for parsable type " + ReflectionUtilities.getFullName(argType));
220        }
221      }
222
223      String shortName = np.getShortName();
224      if (shortName != null) {
225        NamedParameterNode<?> oldNode = shortNames.get(shortName);
226        if (oldNode != null) {
227          if (oldNode.getFullName().equals(np.getFullName())) {
228            throw new IllegalStateException("Tried to double bind "
229                + oldNode.getFullName() + " to short name " + shortName);
230          }
231          throw new ClassHierarchyException("Named parameters " + oldNode.getFullName()
232              + " and " + np.getFullName() + " have the same short name: "
233              + shortName);
234        }
235        shortNames.put(shortName, np);
236      }
237      return np;
238    }
239  }
240
241  private Node getAlreadyBoundNode(Class<?> clazz) throws NameResolutionException {
242    return getAlreadyBoundNode(ReflectionUtilities.getFullName(clazz));
243  }
244
245  @Override
246  public Node getNode(Class<?> clazz) {
247    try {
248      return getNode(ReflectionUtilities.getFullName(clazz));
249    } catch (NameResolutionException e) {
250      throw new ClassHierarchyException("JavaClassHierarchy could not resolve " + clazz
251          + " which is definitely avalable at runtime", e);
252    }
253  }
254
255  @Override
256  public synchronized Node getNode(String name) throws NameResolutionException {
257    Node n = register(name);
258    if (n == null) {
259      // This will never succeed; it just generates a nice exception.
260      getAlreadyBoundNode(name);
261      throw new IllegalStateException("IMPLEMENTATION BUG: Register failed, "
262          + "but getAlreadyBoundNode succeeded!");
263    }
264    return n;
265  }
266
267  private Node getAlreadyBoundNode(String name) throws NameResolutionException {
268    Node root = namespace;
269    String[] toks = name.split("\\$");
270    String outerClassName = toks[0];
271    root = root.get(outerClassName);
272    if (root == null) {
273      throw new NameResolutionException(name, outerClassName);
274    }
275    for (int i = 1; i < toks.length; i++) {
276      root = root.get(toks[i]);
277      if (root == null) {
278        StringBuilder sb = new StringBuilder(outerClassName);
279        for (int j = 0; j < i; j++) {
280          sb.append(toks[j]);
281          if (j != i - 1) {
282            sb.append(".");
283          }
284        }
285        throw new NameResolutionException(name, sb.toString());
286      }
287    }
288    return root;
289  }
290
291  private Node register(String s) {
292    final Class<?> c;
293    try {
294      c = classForName(s);
295    } catch (ClassNotFoundException e1) {
296      return null;
297    }
298    try {
299      Node n = getAlreadyBoundNode(c);
300      return n;
301    } catch (NameResolutionException e) {
302    }
303    // First, walk up the class hierarchy, registering all out parents. This
304    // can't be loopy.
305    if (c.getSuperclass() != null) {
306      register(ReflectionUtilities.getFullName(c.getSuperclass()));
307    }
308    for (Class<?> i : c.getInterfaces()) {
309      register(ReflectionUtilities.getFullName(i));
310    }
311    // Now, we'd like to register our enclosing classes. This turns out to be
312    // safe.
313    // Thankfully, Java doesn't allow:
314    // class A implements A.B { class B { } }
315
316    // It also doesn't allow cycles such as:
317    // class A implements B.BB { interface AA { } }
318    // class B implements A.AA { interface BB { } }
319
320    // So, even though grafting arbitrary DAGs together can give us cycles, Java
321    // seems
322    // to have our back on this one.
323    Class<?> enclosing = c.getEnclosingClass();
324    if (enclosing != null) {
325      register(ReflectionUtilities.getFullName(enclosing));
326    }
327
328    // Now register the class. This has to be after the above so we know our
329    // parents (superclasses and enclosing packages) are already registered.
330    Node n = registerClass(c);
331
332    // Finally, do things that might introduce cycles that invlove c.
333    // This has to be below registerClass, which ensures that any cycles
334    // this stuff introduces are broken.
335    for (Class<?> inner_class : c.getDeclaredClasses()) {
336      register(ReflectionUtilities.getFullName(inner_class));
337    }
338    if (n instanceof ClassNode) {
339      ClassNode<?> cls = (ClassNode<?>) n;
340      for (ConstructorDef<?> def : cls.getInjectableConstructors()) {
341        for (ConstructorArg arg : def.getArgs()) {
342          register(arg.getType());
343          if (arg.getNamedParameterName() != null) {
344            NamedParameterNode<?> np = (NamedParameterNode<?>) register(arg
345                .getNamedParameterName());
346            try {
347              if (np.isSet()) {
348                /// XXX When handling sets, need to track target of generic parameter, and check the type here!
349              } else if (np.isList()) {
350
351              } else {
352                if (!ReflectionUtilities.isCoercable(classForName(arg.getType()),
353                    classForName(np.getFullArgName()))) {
354                  throw new ClassHierarchyException(
355                      "Named parameter type mismatch in " + cls.getFullName() + ".  Constructor expects a "
356                          + arg.getType() + " but " + np.getName() + " is a "
357                          + np.getFullArgName());
358                }
359              }
360            } catch (ClassNotFoundException e) {
361              throw new ClassHierarchyException("Constructor refers to unknown class "
362                  + arg.getType(), e);
363            }
364          }
365        }
366      }
367    } else if (n instanceof NamedParameterNode) {
368      NamedParameterNode<?> np = (NamedParameterNode<?>) n;
369      register(np.getFullArgName());
370    }
371    return n;
372  }
373
374  /**
375   * Assumes that all of the parents of c have been registered already.
376   *
377   * @param c
378   */
379  @SuppressWarnings("unchecked")
380  private <T> Node registerClass(final Class<T> c)
381      throws ClassHierarchyException {
382    if (c.isArray()) {
383      throw new UnsupportedOperationException("Can't register array types");
384    }
385    try {
386      return getAlreadyBoundNode(c);
387    } catch (NameResolutionException e) {
388    }
389
390    final Node n = buildPathToNode(c);
391
392    if (n instanceof ClassNode) {
393      ClassNode<T> cn = (ClassNode<T>) n;
394      Class<T> superclass = (Class<T>) c.getSuperclass();
395      if (superclass != null) {
396        try {
397          ((ClassNode<T>) getAlreadyBoundNode(superclass)).putImpl(cn);
398        } catch (NameResolutionException e) {
399          throw new IllegalStateException(e);
400        }
401      }
402      for (Class<?> interf : c.getInterfaces()) {
403        try {
404          ((ClassNode<T>) getAlreadyBoundNode(interf)).putImpl(cn);
405        } catch (NameResolutionException e) {
406          throw new IllegalStateException(e);
407        }
408      }
409    }
410    return n;
411  }
412
413  @Override
414  public PackageNode getNamespace() {
415    return namespace;
416  }
417
418  @Override
419  public synchronized boolean isImplementation(ClassNode<?> inter, ClassNode<?> impl) {
420    return impl.isImplementationOf(inter);
421  }
422
423  @Override
424  public synchronized ClassHierarchy merge(ClassHierarchy ch) {
425    if (this == ch) {
426      return this;
427    }
428    if (!(ch instanceof ClassHierarchyImpl)) {
429      throw new UnsupportedOperationException("Can't merge java and non-java class hierarchies yet!");
430    }
431    if (this.jars.size() == 0) {
432      return ch;
433    }
434    ClassHierarchyImpl chi = (ClassHierarchyImpl) ch;
435    HashSet<URL> otherJars = new HashSet<>();
436    otherJars.addAll(chi.jars);
437    HashSet<URL> myJars = new HashSet<>();
438    myJars.addAll(this.jars);
439    if (myJars.containsAll(otherJars)) {
440      return this;
441    } else if (otherJars.containsAll(myJars)) {
442      return ch;
443    } else {
444      myJars.addAll(otherJars);
445      return new ClassHierarchyImpl(myJars.toArray(new URL[0]));
446    }
447  }
448}