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 private 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(final URL... jars) { 083 this(jars, new Class[0]); 084 } 085 086 public ClassHierarchyImpl(final URL[] jars, final 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 (final Class<? extends ExternalConstructor<?>> p : parameterParsers) { 091 try { 092 parameterParser.addParser(p); 093 } catch (final 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(final NamedParameterNode<T> name) { 110 final String[] vals = name.getDefaultInstanceAsStrings(); 111 final T[] ret = (T[]) new Object[vals.length]; 112 for (int i = 0; i < vals.length; i++) { 113 final String val = vals[i]; 114 try { 115 ret[i] = parse(name, val); 116 } catch (final 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(final NamedParameterNode<T> np, final String value) throws ParseException { 147 final ClassNode<T> iface; 148 try { 149 iface = (ClassNode<T>) getNode(np.getFullArgName()); 150 } catch (final NameResolutionException e) { 151 throw new IllegalStateException("Could not parse validated named parameter argument type. NamedParameter is " + 152 np.getFullName() + " argument type is " + np.getFullArgName()); 153 } 154 Class<?> clazz; 155 String fullName; 156 try { 157 clazz = (Class<?>) classForName(iface.getFullName()); 158 fullName = null; 159 } catch (final ClassNotFoundException e) { 160 clazz = null; 161 fullName = iface.getFullName(); 162 } 163 try { 164 if (clazz != null) { 165 return (T) parameterParser.parse(clazz, value); 166 } else { 167 return parameterParser.parse(fullName, value); 168 } 169 } catch (final UnsupportedOperationException e) { 170 try { 171 final Node impl = getNode(value); 172 if (impl instanceof ClassNode) { 173 if (isImplementation(iface, (ClassNode<?>) impl)) { 174 return (T) impl; 175 } 176 } 177 throw new ParseException("Name<" + iface.getFullName() + "> " + np.getFullName() + 178 " cannot take non-subclass " + impl.getFullName(), e); 179 } catch (final NameResolutionException e2) { 180 throw new ParseException("Name<" + iface.getFullName() + "> " + np.getFullName() + 181 " cannot take non-class " + value, e); 182 } 183 } 184 } 185 186 /** 187 * Helper method that converts a String to a Class using this 188 * ClassHierarchy's classloader. 189 */ 190 @Override 191 public Class<?> classForName(final String name) throws ClassNotFoundException { 192 return ReflectionUtilities.classForName(name, loader); 193 } 194 195 private <T, U> Node buildPathToNode(final Class<U> clazz) 196 throws ClassHierarchyException { 197 final String[] path = clazz.getName().split("\\$"); 198 199 Node root = namespace; 200 for (int i = 0; i < path.length - 1; i++) { 201 root = root.get(path[i]); 202 } 203 204 if (root == null) { 205 throw new NullPointerException(); 206 } 207 final Node parent = root; 208 209 final Type argType = ReflectionUtilities.getNamedParameterTargetOrNull(clazz); 210 211 if (argType == null) { 212 return JavaNodeFactory.createClassNode(parent, clazz); 213 } else { 214 215 // checked inside of NamedParameterNode, using reflection. 216 @SuppressWarnings("unchecked") final NamedParameterNode<T> np = JavaNodeFactory.createNamedParameterNode( 217 parent, (Class<? extends Name<T>>) clazz, argType); 218 219 if (parameterParser.canParse(ReflectionUtilities.getFullName(argType))) { 220 if (clazz.getAnnotation(NamedParameter.class).default_class() != Void.class) { 221 throw new ClassHierarchyException("Named parameter " + ReflectionUtilities.getFullName(clazz) + 222 " defines default implementation for parsable type " + ReflectionUtilities.getFullName(argType)); 223 } 224 } 225 226 final String shortName = np.getShortName(); 227 if (shortName != null) { 228 final NamedParameterNode<?> oldNode = shortNames.get(shortName); 229 if (oldNode != null) { 230 if (oldNode.getFullName().equals(np.getFullName())) { 231 throw new IllegalStateException("Tried to double bind " 232 + oldNode.getFullName() + " to short name " + shortName); 233 } 234 throw new ClassHierarchyException("Named parameters " + oldNode.getFullName() 235 + " and " + np.getFullName() + " have the same short name: " 236 + shortName); 237 } 238 shortNames.put(shortName, np); 239 } 240 return np; 241 } 242 } 243 244 private Node getAlreadyBoundNode(final Class<?> clazz) throws NameResolutionException { 245 return getAlreadyBoundNode(ReflectionUtilities.getFullName(clazz)); 246 } 247 248 @Override 249 public Node getNode(final Class<?> clazz) { 250 try { 251 return getNode(ReflectionUtilities.getFullName(clazz)); 252 } catch (final NameResolutionException e) { 253 throw new ClassHierarchyException("JavaClassHierarchy could not resolve " + clazz 254 + " which is definitely avalable at runtime", e); 255 } 256 } 257 258 @Override 259 public synchronized Node getNode(final String name) throws NameResolutionException { 260 final Node n = register(name); 261 if (n == null) { 262 // This will never succeed; it just generates a nice exception. 263 getAlreadyBoundNode(name); 264 throw new IllegalStateException("IMPLEMENTATION BUG: Register failed, " 265 + "but getAlreadyBoundNode succeeded!"); 266 } 267 return n; 268 } 269 270 private Node getAlreadyBoundNode(final String name) throws NameResolutionException { 271 Node root = namespace; 272 final String[] toks = name.split("\\$"); 273 final String outerClassName = toks[0]; 274 root = root.get(outerClassName); 275 if (root == null) { 276 throw new NameResolutionException(name, outerClassName); 277 } 278 for (int i = 1; i < toks.length; i++) { 279 root = root.get(toks[i]); 280 if (root == null) { 281 final StringBuilder sb = new StringBuilder(outerClassName); 282 for (int j = 0; j < i; j++) { 283 sb.append(toks[j]); 284 if (j != i - 1) { 285 sb.append("."); 286 } 287 } 288 throw new NameResolutionException(name, sb.toString()); 289 } 290 } 291 return root; 292 } 293 294 private Node register(final String s) { 295 final Class<?> c; 296 try { 297 c = classForName(s); 298 } catch (final ClassNotFoundException e1) { 299 return null; 300 } 301 try { 302 final Node n = getAlreadyBoundNode(c); 303 return n; 304 } catch (final NameResolutionException e) { 305 // node not bound yet 306 } 307 // First, walk up the class hierarchy, registering all out parents. This 308 // can't be loopy. 309 if (c.getSuperclass() != null) { 310 register(ReflectionUtilities.getFullName(c.getSuperclass())); 311 } 312 for (final Class<?> i : c.getInterfaces()) { 313 register(ReflectionUtilities.getFullName(i)); 314 } 315 // Now, we'd like to register our enclosing classes. This turns out to be 316 // safe. 317 // Thankfully, Java doesn't allow: 318 // class A implements A.B { class B { } } 319 320 // It also doesn't allow cycles such as: 321 // class A implements B.BB { interface AA { } } 322 // class B implements A.AA { interface BB { } } 323 324 // So, even though grafting arbitrary DAGs together can give us cycles, Java 325 // seems 326 // to have our back on this one. 327 final Class<?> enclosing = c.getEnclosingClass(); 328 if (enclosing != null) { 329 register(ReflectionUtilities.getFullName(enclosing)); 330 } 331 332 // Now register the class. This has to be after the above so we know our 333 // parents (superclasses and enclosing packages) are already registered. 334 final Node n = registerClass(c); 335 336 // Finally, do things that might introduce cycles that invlove c. 337 // This has to be below registerClass, which ensures that any cycles 338 // this stuff introduces are broken. 339 for (final Class<?> innerClass : c.getDeclaredClasses()) { 340 register(ReflectionUtilities.getFullName(innerClass)); 341 } 342 if (n instanceof ClassNode) { 343 final ClassNode<?> cls = (ClassNode<?>) n; 344 for (final ConstructorDef<?> def : cls.getInjectableConstructors()) { 345 for (final ConstructorArg arg : def.getArgs()) { 346 register(arg.getType()); 347 if (arg.getNamedParameterName() != null) { 348 final NamedParameterNode<?> np = (NamedParameterNode<?>) register(arg 349 .getNamedParameterName()); 350 try { 351 // TODO: When handling sets, need to track target of generic parameter, and check the type here! 352 if (!np.isSet() && !np.isList()) { 353 if (!ReflectionUtilities.isCoercable(classForName(arg.getType()), 354 classForName(np.getFullArgName()))) { 355 throw new ClassHierarchyException( 356 "Named parameter type mismatch in " + cls.getFullName() + ". Constructor expects a " 357 + arg.getType() + " but " + np.getName() + " is a " 358 + np.getFullArgName()); 359 } 360 } 361 } catch (final ClassNotFoundException e) { 362 throw new ClassHierarchyException("Constructor refers to unknown class " 363 + arg.getType(), e); 364 } 365 } 366 } 367 } 368 } else if (n instanceof NamedParameterNode) { 369 final NamedParameterNode<?> np = (NamedParameterNode<?>) n; 370 register(np.getFullArgName()); 371 } 372 return n; 373 } 374 375 /** 376 * Assumes that all of the parents of c have been registered already. 377 * 378 * @param c 379 */ 380 @SuppressWarnings("unchecked") 381 private <T> Node registerClass(final Class<T> c) 382 throws ClassHierarchyException { 383 if (c.isArray()) { 384 throw new UnsupportedOperationException("Can't register array types"); 385 } 386 try { 387 return getAlreadyBoundNode(c); 388 } catch (final NameResolutionException e) { 389 // node not bound yet 390 } 391 392 final Node n = buildPathToNode(c); 393 394 if (n instanceof ClassNode) { 395 final ClassNode<T> cn = (ClassNode<T>) n; 396 final Class<T> superclass = (Class<T>) c.getSuperclass(); 397 if (superclass != null) { 398 try { 399 ((ClassNode<T>) getAlreadyBoundNode(superclass)).putImpl(cn); 400 } catch (final NameResolutionException e) { 401 throw new IllegalStateException(e); 402 } 403 } 404 for (final Class<?> interf : c.getInterfaces()) { 405 try { 406 ((ClassNode<T>) getAlreadyBoundNode(interf)).putImpl(cn); 407 } catch (final NameResolutionException e) { 408 throw new IllegalStateException(e); 409 } 410 } 411 } 412 return n; 413 } 414 415 @Override 416 public PackageNode getNamespace() { 417 return namespace; 418 } 419 420 public ParameterParser getParameterParser() { 421 return parameterParser; 422 } 423 424 @Override 425 public synchronized boolean isImplementation(final ClassNode<?> inter, final ClassNode<?> impl) { 426 return impl.isImplementationOf(inter); 427 } 428 429 @Override 430 public synchronized ClassHierarchy merge(final ClassHierarchy ch) { 431 if (this == ch) { 432 return this; 433 } 434 if (!(ch instanceof ClassHierarchyImpl)) { 435 throw new UnsupportedOperationException("Can't merge java and non-java class hierarchies yet!"); 436 } 437 if (this.jars.size() == 0) { 438 return ch; 439 } 440 final ClassHierarchyImpl chi = (ClassHierarchyImpl) ch; 441 final HashSet<URL> otherJars = new HashSet<>(); 442 otherJars.addAll(chi.jars); 443 final HashSet<URL> myJars = new HashSet<>(); 444 myJars.addAll(this.jars); 445 if (myJars.containsAll(otherJars)) { 446 return this; 447 } else if (otherJars.containsAll(myJars)) { 448 return ch; 449 } else { 450 myJars.addAll(otherJars); 451 return new ClassHierarchyImpl(myJars.toArray(new URL[0])); 452 } 453 } 454}