public static String filterTypeName(Class<?> type) {
   if (type != null) {
     if (!type.isPrimitive()
         && !(type.isArray() && ArrayTool.getLowerComponentType(type).isPrimitive())) {
       // for not primitives
       //
       return String.format(
           "%s.%s", ClassUtils.getPackageName(type), ClassUtils.getShortClassName(type));
     } else {
       return ClassUtils.getShortClassName(type);
     }
   }
   return StringUtils.EMPTY;
 }
 public static String getConstructorWithFields(
     String simpleClassName, Map<String, Class<?>> fields, int numberOfParamsForSuperConstructor) {
   StringBuilder buf = new StringBuilder();
   if (fields.size() < 256) {
     // Generate constructor with parameters only in case where there are less than 256 arguments.
     // 255 arguments to the method is a Java limitation
     //
     buf.append(String.format("\n  public %s(", simpleClassName));
     Iterator<Entry<String, Class<?>>> fieldsIterator = fields.entrySet().iterator();
     while (fieldsIterator.hasNext()) {
       Entry<String, Class<?>> field = fieldsIterator.next();
       buf.append(
           String.format("%s %s", ClassUtils.getShortClassName(field.getValue()), field.getKey()));
       if (fieldsIterator.hasNext()) {
         buf.append(", ");
       }
     }
     buf.append(") {\n");
     buf.append("    super(");
     fieldsIterator = fields.entrySet().iterator();
     for (int i = 0; i < numberOfParamsForSuperConstructor; i++) {
       if (i != 0) {
         buf.append(", ");
       }
       buf.append(fieldsIterator.next().getKey());
     }
     buf.append(");\n");
     while (fieldsIterator.hasNext()) {
       Entry<String, Class<?>> field = fieldsIterator.next();
       buf.append(String.format("    this.%s = %s;\n", field.getKey(), field.getKey()));
     }
     buf.append("  }\n");
   }
   return buf.toString();
 }
 public static Class<?> getRequiredClass(String className) {
   try {
     return ClassUtils.getClass(className);
   } catch (ClassNotFoundException e) {
     throw new RuntimeException(e);
   }
 }
示例#4
0
  /**
   * Gets an accessible <code>Field</code> by name breaking scope if requested.
   * Superclasses/interfaces will be considered.
   *
   * @param cls the class to reflect, must not be null
   * @param fieldName the field name to obtain
   * @param forceAccess whether to break scope restrictions using the <code>setAccessible</code>
   *     method. <code>False</code> will only match public fields.
   * @return the Field object
   * @throws IllegalArgumentException if the class or field name is null
   */
  public static Field getField(final Class<?> cls, String fieldName, boolean forceAccess) {
    if (cls == null) {
      throw new IllegalArgumentException("The class must not be null");
    }
    if (fieldName == null) {
      throw new IllegalArgumentException("The field name must not be null");
    }
    // Sun Java 1.3 has a bugged implementation of getField hence we write the
    // code ourselves

    // getField() will return the Field object with the declaring class
    // set correctly to the class that declares the field. Thus requesting the
    // field on a subclass will return the field from the superclass.
    //
    // priority order for lookup:
    // searchclass private/protected/package/public
    // superclass protected/package/public
    //  private/different package blocks access to further superclasses
    // implementedinterface public

    // check up the superclass hierarchy
    for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) {
      try {
        Field field = acls.getDeclaredField(fieldName);
        // getDeclaredField checks for non-public scopes as well
        // and it returns accurate results
        if (!Modifier.isPublic(field.getModifiers())) {
          if (forceAccess) {
            field.setAccessible(true);
          } else {
            continue;
          }
        }
        return field;
      } catch (NoSuchFieldException ex) { // NOPMD
        // ignore
      }
    }
    // check the public interface case. This must be manually searched for
    // incase there is a public supersuperclass field hidden by a private/package
    // superclass field.
    Field match = null;
    for (Class<?> class1 : ClassUtils.getAllInterfaces(cls)) {
      try {
        Field test = ((Class<?>) class1).getField(fieldName);
        if (match != null) {
          throw new IllegalArgumentException(
              "Reference to field "
                  + fieldName
                  + " is ambiguous relative to "
                  + cls
                  + "; a matching field exists on two or more implemented interfaces.");
        }
        match = test;
      } catch (NoSuchFieldException ex) { // NOPMD
        // ignore
      }
    }
    return match;
  }
示例#5
0
  /**
   * @param cls
   * @param toClass
   * @param subtypeVarAssigns
   * @return
   */
  private static Map<TypeVariable<?>, Type> getTypeArguments(
      Class<?> cls, Class<?> toClass, Map<TypeVariable<?>, Type> subtypeVarAssigns) {
    // make sure they're assignable
    if (!isAssignable(cls, toClass)) {
      return null;
    }

    // can't work with primitives
    if (cls.isPrimitive()) {
      // both classes are primitives?
      if (toClass.isPrimitive()) {
        // dealing with widening here. No type arguments to be
        // harvested with these two types.
        return new HashMap<TypeVariable<?>, Type>();
      }

      // work with wrapper the wrapper class instead of the primitive
      cls = ClassUtils.primitiveToWrapper(cls);
    }

    // create a copy of the incoming map, or an empty one if it's null
    HashMap<TypeVariable<?>, Type> typeVarAssigns =
        subtypeVarAssigns == null
            ? new HashMap<TypeVariable<?>, Type>()
            : new HashMap<TypeVariable<?>, Type>(subtypeVarAssigns);

    // no arguments for the parameters, or target class has been reached
    if (cls.getTypeParameters().length > 0 || toClass.equals(cls)) {
      return typeVarAssigns;
    }

    // walk the inheritance hierarchy until the target class is reached
    return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
  }
 @Override
 public String toString() {
   String functionKeyString = this.getFunctionalKey().toString();
   int indexOfCrochet = functionKeyString.indexOf('[');
   String fctKeyPropsStr = functionKeyString.substring(indexOfCrochet);
   return ClassUtils.getShortClassName(this.getClass()) + fctKeyPropsStr;
 }
  private static Object getProperValue(Number number, Class<?> expectedClass) {
    Class<?> klazz = ClassUtils.wrapperToPrimitive(number.getClass());
    Object value = null;

    // Dexlib will only ever make byte (t), int, long (l), or short (s)
    if (klazz == byte.class) {
      value = number.byteValue();
      if (expectedClass == boolean.class) {
        value = (byte) value == 1;
      }
    } else if (klazz == short.class) {
      value = number.shortValue();
      if (expectedClass == char.class) {
        value = (char) number.shortValue();
      }
    } else if (klazz == int.class) {
      if (expectedClass == int.class) {
        value = number.intValue();
      } else if (expectedClass == float.class) {
        value = Float.intBitsToFloat(number.intValue());
      }
    } else if (klazz == long.class) {
      value = number.longValue();
      if (expectedClass == long.class) {
        value = number.longValue();
      } else if (expectedClass == double.class) {
        value = Double.longBitsToDouble(number.longValue());
      }
    }

    return value;
  }
示例#8
0
 private static boolean isAssignable(Type paramType, Class paramClass) {
   for (Object localObject = paramType;
       ;
       localObject = getRawType((ParameterizedType) localObject)) {
     if (localObject == null) return (paramClass == null) || (!paramClass.isPrimitive());
     if (paramClass == null) return false;
     if (paramClass.equals(localObject)) return true;
     if ((localObject instanceof Class))
       return ClassUtils.isAssignable((Class) localObject, paramClass);
     if (!(localObject instanceof ParameterizedType)) break;
   }
   if ((localObject instanceof TypeVariable)) {
     Type[] arrayOfType = ((TypeVariable) localObject).getBounds();
     int i = arrayOfType.length;
     for (int j = 0; j < i; j++) if (isAssignable(arrayOfType[j], paramClass)) return true;
     return false;
   }
   if ((localObject instanceof GenericArrayType))
     return (paramClass.equals(Object.class))
         || ((paramClass.isArray())
             && (isAssignable(
                 ((GenericArrayType) localObject).getGenericComponentType(),
                 paramClass.getComponentType())));
   if ((localObject instanceof WildcardType)) return false;
   throw new IllegalStateException("found an unhandled type: " + localObject);
 }
 public static Class<?> getOptionalClass(String className) {
   try {
     return ClassUtils.getClass(className);
   } catch (ClassNotFoundException e) {
     return null;
   } catch (NoClassDefFoundError e) {
     return null;
   }
 }
示例#10
0
  /**
   * Checks if the subject type may be implicitly cast to the target class following the Java
   * generics rules.
   *
   * @param type the subject type to be assigned to the target type
   * @param toClass the target class
   * @return true if <code>type</code> is assignable to <code>toClass</code>.
   */
  private static boolean isAssignable(Type type, Class<?> toClass) {
    if (type == null) {
      // consistency with ClassUtils.isAssignable() behavior
      return toClass == null || !toClass.isPrimitive();
    }

    // only a null type can be assigned to null type which
    // would have cause the previous to return true
    if (toClass == null) {
      return false;
    }

    // all types are assignable to themselves
    if (toClass.equals(type)) {
      return true;
    }

    if (type instanceof Class<?>) {
      // just comparing two classes
      return ClassUtils.isAssignable((Class<?>) type, toClass);
    }

    if (type instanceof ParameterizedType) {
      // only have to compare the raw type to the class
      return isAssignable(getRawType((ParameterizedType) type), toClass);
    }

    // *
    if (type instanceof TypeVariable<?>) {
      // if any of the bounds are assignable to the class, then the
      // type is assignable to the class.
      for (Type bound : ((TypeVariable<?>) type).getBounds()) {
        if (isAssignable(bound, toClass)) {
          return true;
        }
      }

      return false;
    }

    // the only classes to which a generic array type can be assigned
    // are class Object and array classes
    if (type instanceof GenericArrayType) {
      return toClass.equals(Object.class)
          || toClass.isArray()
              && isAssignable(
                  ((GenericArrayType) type).getGenericComponentType(), toClass.getComponentType());
    }

    // wildcard types are not assignable to a class (though one would think
    // "? super Object" would be assignable to Object)
    if (type instanceof WildcardType) {
      return false;
    }

    throw new IllegalStateException("found an unhandled type: " + type);
  }
 /**
  * @param classNameWithNamespace name of the class with namespace, symbols '/' or '.' are
  *     supported to be a separator<br>
  *     (e.g. <code>my/test/TestClass</code> or <code>my.test.TestClass</code>)
  * @return name of the class file without package (e.g. <code>TestClass</code>) if no one of the
  *     supported symbols found, returns classNameWithNamespace.
  */
 public static String getShortClassName(String classNameWithNamespace) {
   if (classNameWithNamespace.contains("/")) {
     String[] path = classNameWithNamespace.split("/");
     return path[path.length - 1];
   } else if (classNameWithNamespace.contains(".")) {
     return ClassUtils.getShortCanonicalName(classNameWithNamespace);
   }
   return classNameWithNamespace;
 }
  /*
   * (non-Javadoc)
   * @see org.openl.binding.INodeBinder#bind(org.openl.parser.ISyntaxNode, org.openl.env.IOpenEnv,
   * org.openl.binding.IBindingContext)
   */
  public IBoundNode bind(ISyntaxNode node, IBindingContext bindingContext) throws Exception {

    if (node.getNumberOfChildren() != 1) {
      BindHelper.processError("Suffix node should have 1 subnode", node, bindingContext);

      return new ErrorBoundNode(node);
    }

    int index = node.getType().lastIndexOf('.');
    String methodName = node.getType().substring(index + 1);
    IBoundNode[] children = bindChildren(node, bindingContext);

    if (!children[0].isLvalue()) {
      BindHelper.processError(
          "The node is not an Lvalue", children[0].getSyntaxNode(), bindingContext, false);

      return new ErrorBoundNode(node);
    }

    IOpenClass[] types = getTypes(children);
    IMethodCaller methodCaller =
        UnaryOperatorNodeBinder.findUnaryOperatorMethodCaller(methodName, types, bindingContext);

    if (methodCaller == null) {

      String message = UnaryOperatorNodeBinder.errorMsg(methodName, types[0]);
      BindHelper.processError(message, node, bindingContext);

      return new ErrorBoundNode(node);
    }

    IOpenClass methodType = methodCaller.getMethod().getType();

    if (ClassUtils.primitiveToWrapper(methodType.getInstanceClass())
        != ClassUtils.primitiveToWrapper(types[0].getInstanceClass())) {
      //        if (!methodCaller.getMethod().getType().equals(types[0])) {
      BindHelper.processError(
          "Suffix operator must return the same type as an argument", node, bindingContext);

      return new ErrorBoundNode(node);
    }

    return new SuffixNode(node, children, methodCaller);
  }
示例#13
0
  /**
   * Convert value to enum.
   *
   * @param cls enum to convert to
   * @param value value to convert
   * @param <T> enum type
   * @return enum
   */
  @Override
  public <T> T convert(Class<T> cls, Object value) {

    try {
      if (ClassUtils.isAssignable(value.getClass(), String.class)) {
        return stringToEnum(cls, (String) value);
      } else if (ClassUtils.isAssignable(value.getClass(), Integer.class, true)) {
        return intToEnum(cls, (Integer) value);
      } else {
        throw new UnsupportedOperationException(
            value.getClass().getSimpleName() + " to Enum no supported");
      }
    } catch (IndexOutOfBoundsException
        | ReflectiveOperationException
        | UnsupportedOperationException
        | IllegalArgumentException e) {
      throw new InvalidAttributeException("Unknown " + cls.getSimpleName() + " value " + value);
    }
  }
  @Override
  public <F> F createCompositeFilter(ClassLoader loader, Object... filters) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
    for (Object filter : filters) {
      interfaces.addAll(ClassUtils.getAllInterfaces(filter.getClass()));
    }

    return (F)
        Proxy.newProxyInstance(
            loader, interfaces.toArray(CLASS_ARRAY), new CompositeFilter(this, filters));
  }
 @Override
 public CodisStoreSchema search(Map<String, CodisStoreSchema> schemaMap, Class<?> clazz) {
   List<Class<?>> clazzList = ClassUtils.getAllSuperclasses(clazz);
   for (Class clz : clazzList) {
     CodisStoreSchema schema = schemaMap.get(clz.getName());
     if (schema != null) {
       return schema;
     }
   }
   return null;
 }
 public static String fakeECTXml() throws IOException, ClassNotFoundException {
   String r;
   // String filename = "ericsson activate CFU.xml";
   String filename = "ericsson deactivate CFU.xml";
   log.debug(filename);
   // log.debug(ClassUtils.getClass(ProxyProcessHelper.class.getName()).getClassLoader().getResource(filename));
   r =
       IOUtils.toString(
           ClassUtils.getClass(ProxyProcessHelper.class.getName())
               .getClassLoader()
               .getResourceAsStream(filename));
   return r;
 }
  private Operator<?>[] getSelfContainedOperators() {
    final List<Operator<?>> result = new ArrayList<>();

    for (Class<?> c : ClassUtils.hierarchy(getClass(), interfacesPolicy)) {
      for (Class<?> inner : c.getDeclaredClasses()) {
        if (Operator.class.isAssignableFrom(inner)) {
          final Operator<?> operator = newInstance(inner.asSubclass(Operator.class));
          if (operator != null) {
            result.add(operator);
          }
        }
      }
    }
    return result.toArray(new Operator[result.size()]);
  }
 protected final String getShortClassName(Class<?> paramAnonymousClass) {
   Iterator localIterator = ClassUtils.getAllInterfaces(paramAnonymousClass).iterator();
   do {
     if (!localIterator.hasNext()) {
       break;
     }
     paramAnonymousClass = (Class) localIterator.next();
   } while (!Annotation.class.isAssignableFrom(paramAnonymousClass));
   for (; ; ) {
     if (paramAnonymousClass == null) {}
     for (paramAnonymousClass = ""; ; paramAnonymousClass = paramAnonymousClass.getName()) {
       return new StringBuilder(paramAnonymousClass).insert(0, '@').toString();
     }
     paramAnonymousClass = null;
   }
 }
示例#19
0
 private static Map getTypeArguments(Class paramClass1, Class paramClass2, Map paramMap) {
   Object localObject;
   if (!isAssignable(paramClass1, paramClass2)) localObject = null;
   while (true) {
     return localObject;
     if (paramClass1.isPrimitive()) {
       if (paramClass2.isPrimitive()) return new HashMap();
       paramClass1 = ClassUtils.primitiveToWrapper(paramClass1);
     }
     if (paramMap == null) ;
     for (localObject = new HashMap();
         (paramClass1.getTypeParameters().length <= 0) && (!paramClass2.equals(paramClass1));
         localObject = new HashMap(paramMap))
       return getTypeArguments(
           getClosestParentType(paramClass1, paramClass2), paramClass2, (Map) localObject);
   }
 }
  protected Class func_180212_a(Class p_180212_1_, boolean p_180212_2_) {
    Iterator var3 = ClassUtils.hierarchy(p_180212_1_, Interfaces.INCLUDE).iterator();
    Class var4;

    do {
      if (!var3.hasNext()) {
        throw new IllegalArgumentException("Don\'t know how to search for " + p_180212_1_);
      }

      var4 = (Class) var3.next();
    } while (!this.field_180216_b.contains(var4));

    if (var4 == this.field_180217_c && p_180212_2_) {
      this.func_180213_a(p_180212_1_);
    }

    return var4;
  }
示例#21
0
 @Override
 public Class<?> getType(Object propertyId) {
   final String pName = propertyId.toString();
   try {
     final DynaProperty dynaProperty = getDynaClass().getDynaProperty(pName);
     final Class<?> type = dynaProperty.getType();
     if (type.isPrimitive()) {
       // Vaadin can't handle primitive types in _all_ places, so use
       // wrappers instead. FieldGroup works, but e.g. Table in _editable_
       // mode fails for some reason
       return ClassUtils.primitiveToWrapper(type);
     }
     return type;
   } catch (Exception e) {
     // If type can't be found via dynaClass, it is most likely
     // nested/indexed/mapped property
     try {
       return getNestedPropertyType(getDynaClass(), pName);
     } catch (Exception ex) {
       throw new RuntimeException(ex);
     }
   }
 }
示例#22
0
  /**
   * kdb result conversions to standard beaker types.
   *
   * <p>TODO it would be better if this was handled by customizing a serializer module, but I don't
   * see a clean way of doing that.
   */
  private Object convert(Object o) {
    // Convert flips of simple lists into TableDisplays.
    if (c.t(o) == 98)
      to_tabledisplay:
      {
        Flip f = (Flip) o;

        // Make sure each column is an array and a type we can handle.
        List<String> columns = Arrays.asList(f.x);
        List<String> classes = new ArrayList<>();
        List<List<?>> colLists = new ArrayList<>();
        for (Object c : f.y) {
          List<?> values = toList(c);
          if (values == null) {
            break to_tabledisplay;
          }
          String type =
              objConv.convertType(
                  ClassUtils.primitiveToWrapper(c.getClass().getComponentType()).getName());
          if (type == null) {
            break to_tabledisplay;
          }

          // Special case - convert Dates to nanosecond times.
          if (BasicObjectSerializer.TYPE_TIME.equals(type)) {
            List<Long> timestamps = new ArrayList<>(values.size());
            for (Object d : values) {
              timestamps.add(
                  TimeUnit.NANOSECONDS.convert(((Date) d).getTime(), TimeUnit.MILLISECONDS));
            }
            values = timestamps;
          }

          classes.add(type);
          colLists.add(values);
        }

        // Columns to rows.
        int rows = colLists.get(0).size();
        List<List<?>> values = new ArrayList<>();
        for (int row = 0; row < rows; ++row) {
          List<Object> rowValues = new ArrayList<>();
          for (List<?> col : colLists) {
            rowValues.add(col.get(row));
          }
          values.add(rowValues);
        }

        return new TableDisplay(values, columns, classes);
      }

    // Convert Dicts to maps.
    if (c.t(o) == 99)
      to_map:
      {
        Dict f = (Dict) o;

        // Special case - keyed tables are dicts of flips.
        if ((c.t(f.x) == 98) && (c.t(f.y) == 98))
          to_table:
          {
            Flip keys = (Flip) f.x;
            Flip cols = (Flip) f.y;
            return convert(
                new Flip(
                    new Dict(
                        ArrayUtils.addAll(keys.x, cols.x), ArrayUtils.addAll(keys.y, cols.y))));
          }

        List<?> keys = toList(f.x);
        if (keys == null) break to_map;
        List<?> values = toList(f.y);
        if (values == null) break to_map;
        Map<Object, Object> map = new HashMap<>();
        for (int i = 0; i < values.size(); ++i) {
          map.put(keys.get(i), values.get(i));
        }
        return map;
      }

    // No conversion.
    return o;
  }
  @Override
  @SuppressWarnings({"unchecked", "rawtypes"})
  protected void populateItem(final ListItem<ConnConfProperty> item) {
    final ConnConfProperty property = item.getModelObject();

    final Label label =
        new Label(
            "connPropAttrSchema",
            StringUtils.isBlank(property.getSchema().getDisplayName())
                ? property.getSchema().getName()
                : property.getSchema().getDisplayName());
    item.add(label);

    FieldPanel<? extends Serializable> field;
    boolean required = false;
    boolean isArray = false;

    if (property.getSchema().isConfidential()
        || Constants.GUARDED_STRING.equalsIgnoreCase(property.getSchema().getType())
        || Constants.GUARDED_BYTE_ARRAY.equalsIgnoreCase(property.getSchema().getType())) {

      field =
          new AjaxPasswordFieldPanel(
              "panel", label.getDefaultModelObjectAsString(), new Model<String>());
      ((PasswordTextField) field.getField()).setResetPassword(false);

      required = property.getSchema().isRequired();
    } else {
      Class<?> propertySchemaClass;
      try {
        propertySchemaClass =
            ClassUtils.forName(property.getSchema().getType(), ClassUtils.getDefaultClassLoader());
        if (ClassUtils.isPrimitiveOrWrapper(propertySchemaClass)) {
          propertySchemaClass =
              org.apache.commons.lang3.ClassUtils.primitiveToWrapper(propertySchemaClass);
        }
      } catch (Exception e) {
        LOG.error("Error parsing attribute type", e);
        propertySchemaClass = String.class;
      }

      if (ClassUtils.isAssignable(Number.class, propertySchemaClass)) {
        @SuppressWarnings("unchecked")
        final Class<Number> numberClass = (Class<Number>) propertySchemaClass;
        field =
            new SpinnerFieldPanel<Number>(
                "panel",
                label.getDefaultModelObjectAsString(),
                numberClass,
                new Model<Number>(),
                null,
                null);

        required = property.getSchema().isRequired();
      } else if (ClassUtils.isAssignable(Boolean.class, propertySchemaClass)) {
        field =
            new AjaxCheckBoxPanel(
                "panel", label.getDefaultModelObjectAsString(), new Model<Boolean>());
      } else {
        field =
            new AjaxTextFieldPanel(
                "panel", label.getDefaultModelObjectAsString(), new Model<String>());

        required = property.getSchema().isRequired();
      }

      if (propertySchemaClass.isArray()) {
        isArray = true;
      }
    }

    field.setTitle(property.getSchema().getHelpMessage());

    if (required) {
      field.addRequiredLabel();
    }

    if (isArray) {
      if (property.getValues().isEmpty()) {
        property.getValues().add(null);
      }

      final MultiFieldPanel multiFieldPanel =
          new MultiFieldPanel("panel", new PropertyModel<List<String>>(property, "values"), field);
      item.add(multiFieldPanel);
    } else {
      setNewFieldModel(field, property.getValues());
      item.add(field);
    }

    if (withOverridable) {
      item.add(
          new AjaxCheckBoxPanel(
              "connPropAttrOverridable",
              "connPropAttrOverridable",
              new PropertyModel<Boolean>(property, "overridable")));
    }

    configuration.add(property);
  }
 @Override
 protected boolean canValidate(Object[] params, ConstraintValidatorContext validatorContext) {
   return (super.canValidate(params, validatorContext)
       && ((this.annoParamClasses == null)
           || ToolClassUtils.isAssignable(ClassUtils.toClass(params), this.annoParamClasses)));
 }
示例#25
0
 /**
  * Gets the package name from the canonical name.
  *
  * <p>The string passed in is assumed to be a canonical name - it is not checked.
  *
  * <p>If the class is unpackaged, return an empty string.
  *
  * @param canonicalName the canonical name to get the package name for, may be <code>null</code>
  * @return the package name or an empty string
  * @since 2.4
  */
 public static String getPackageCanonicalName(String canonicalName) {
   return ClassUtils.getPackageName(getCanonicalName(canonicalName));
 }
示例#26
0
 /**
  * Gets the canonical name minus the package name from a String.
  *
  * <p>The string passed in is assumed to be a canonical name - it is not checked.
  *
  * @param canonicalName the class name to get the short name for
  * @return the canonical name of the class without the package name or an empty string
  * @since 2.4
  */
 public static String getShortCanonicalName(String canonicalName) {
   return ClassUtils.getShortClassName(getCanonicalName(canonicalName));
 }
 @Override
 public boolean needToProxy(Class<?> clazz) {
   return ClassUtils.getAllInterfaces(clazz).contains(Session.class);
 }
/** @author Olaf Lessenich */
public class ASTNodeArtifact extends Artifact<ASTNodeArtifact> {

  private static final Logger LOG =
      Logger.getLogger(ClassUtils.getShortClassName(ASTNodeArtifact.class));

  /**
   * Initializes parser.
   *
   * @param p program
   */
  private static void initParser(final Program p) {
    p.initJavaParser(
        new JavaParser() {
          @Override
          public CompilationUnit parse(final java.io.InputStream is, final String fileName)
              throws java.io.IOException, beaver.Parser.Exception {
            return new parser.JavaParser().parse(is, fileName);
          }
        });
  }

  /**
   * Initializes a program.
   *
   * @return program
   */
  private static Program initProgram() {
    Program program = new Program();
    program.state().reset();
    program.initBytecodeReader(new BytecodeParser());
    initParser(program);
    return program;
  }

  /**
   * @param artifact artifact to create program from
   * @return ASTNodeArtifact
   */
  public static ASTNodeArtifact createProgram(final ASTNodeArtifact artifact) {
    assert (artifact.astnode != null);
    assert (artifact.astnode instanceof Program);

    Program old = (Program) artifact.astnode;
    Program program;
    try {
      program = old.clone();
    } catch (CloneNotSupportedException e) {
      program = new Program();
    }

    ASTNodeArtifact p = new ASTNodeArtifact(program);
    p.deleteChildren();

    return p;
  }

  /** Encapsulated ASTNode. */
  private ASTNode<?> astnode = null;

  /** Constructor class. */
  public ASTNodeArtifact() {}

  /** @param astnode astnode */
  public ASTNodeArtifact(final ASTNode<?> astnode) {
    assert (astnode != null);
    this.astnode = astnode;
  }

  /**
   * Constructs an ASTNodeArtifact from a FileArtifact.
   *
   * @param artifact file artifact
   */
  public ASTNodeArtifact(final FileArtifact artifact) {
    assert (artifact != null);

    setRevision(artifact.getRevision());

    ASTNode<?> astnode;
    if (artifact.isEmptyDummy()) {
      astnode = new ASTNode<>();
      setEmptyDummy(true);
    } else {
      Program p = initProgram();
      p.addSourceFile(artifact.getPath());
      astnode = p;
    }

    this.astnode = astnode;
    renumber(1, this);
  }

  /**
   * Returns the encapsulated JastAddJ ASTNode
   *
   * @return encapsulated ASTNode object from JastAddJ
   */
  public final ASTNode<?> getASTNode() {
    return astnode;
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * de.fosd.jdime.common.Artifact#addChild(de.fosd.jdime.common.Artifact)
   */
  @Override
  public final ASTNodeArtifact addChild(final ASTNodeArtifact child) throws IOException {
    if (child.isConflict()) {
      child.setParent(this);
      children.add(child);
      return child;
    }

    ASTNodeArtifact myChild;
    try {
      myChild = new ASTNodeArtifact((ASTNode<?>) child.astnode.clone());
      myChild.deleteChildren();
      myChild.setRevision(child.getRevision());
      myChild.setParent(this);
      myChild.astnode.setParent(astnode);
      myChild.setRevision(child.getRevision());
      myChild.setNumber(child.getNumber());
      myChild.cloneMatches(child);

      if (children == null) {
        initializeChildren();
      }
      children.add(myChild);
      // astnode.flushCaches();
      if (LOG.isTraceEnabled()) {
        LOG.trace("Added child " + myChild.getId() + " to parent node " + getId());
      }
      return myChild;
    } catch (CloneNotSupportedException e) {
      throw new NotYetImplementedException();
    }
  }

  @Override
  public final int compareTo(final ASTNodeArtifact o) {
    if (hasUniqueLabels()) {
      return astnode.dumpString().compareTo(o.astnode.dumpString());
    } else {
      throw new RuntimeException("This artifact is not comparable.");
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * de.fosd.jdime.common.Artifact#copyArtifact(de.fosd.jdime.common.Artifact)
   */
  @Override
  public final void copyArtifact(final ASTNodeArtifact destination) throws IOException {
    ASTNodeArtifact copy = destination.addChild(this);
    if (!isConflict() && hasChildren()) {
      for (ASTNodeArtifact child : getChildren()) {
        child.copyArtifact(copy);
      }
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#createArtifact(boolean)
   */
  @Override
  public final void createArtifact(final boolean isLeaf) throws IOException {
    // TODO Auto-generated method stub
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#createEmptyDummy()
   */
  @Override
  public final ASTNodeArtifact createEmptyDummy() throws FileNotFoundException {
    ASTNodeArtifact dummy = new ASTNodeArtifact();
    dummy.astnode = new ASTNode<>();
    dummy.setEmptyDummy(true);
    dummy.setRevision(getRevision());
    return dummy;
  }

  /** */
  public final void deleteChildren() {
    while (hasChildren()) {
      ASTNodeArtifact child = getChild(0);
      child.astnode = null;
      children.remove(0);
    }
  }

  private static String getGraphvizId(ASTNodeArtifact artifact) {
    return "\"" + artifact.getId() + "\"";
  }

  /**
   * Returns the AST in dot-format.
   *
   * @param includeNumbers include node number in label if true
   * @return AST in dot-format.
   */
  public final String dumpGraphvizTree(final boolean includeNumbers, int virtualcount) {
    assert (astnode != null);
    StringBuilder sb = new StringBuilder();

    if (isConflict()) {
      // insert virtual node
      String conflictId = "\"c" + virtualcount + "\"";
      sb.append(conflictId);
      sb.append("[label=\"Conflict\", fillcolor = red, style = filled]")
          .append(System.lineSeparator());

      // left alternative
      sb.append(left.dumpGraphvizTree(includeNumbers, virtualcount));
      sb.append(conflictId)
          .append("->")
          .append(getGraphvizId(left))
          .append("[label=\"")
          .append(left.getRevision())
          .append("\"]")
          .append(";")
          .append(System.lineSeparator());

      // right alternative
      sb.append(right.dumpGraphvizTree(includeNumbers, virtualcount));
      sb.append(conflictId)
          .append("->")
          .append(getGraphvizId(right))
          .append("[label=\"")
          .append(right.getRevision())
          .append("\"]")
          .append(";")
          .append(System.lineSeparator());
    } else {
      sb.append(getGraphvizId(this)).append("[label=\"");

      // node label
      if (includeNumbers) {
        sb.append("(").append(getNumber()).append(") ");
      }

      sb.append(astnode.dumpString());

      sb.append("\"");

      if (hasMatches()) {
        sb.append(", fillcolor = green, style = filled");
      }

      sb.append("];");
      sb.append(System.lineSeparator());

      // children
      for (ASTNodeArtifact child : getChildren()) {
        String childId = getGraphvizId(child);
        if (child.isConflict()) {
          virtualcount++;
          childId = "\"c" + virtualcount + "\"";
        }

        sb.append(child.dumpGraphvizTree(includeNumbers, virtualcount));

        // edge
        sb.append(getGraphvizId(this))
            .append("->")
            .append(childId)
            .append(";")
            .append(System.lineSeparator());
      }
    }

    return sb.toString();
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#dumpTree(java.lang.String)
   */
  @Override
  protected final String dumpTree(final String indent) {
    assert (astnode != null);
    StringBuilder sb = new StringBuilder();

    // node itself
    Matching<ASTNodeArtifact> m = null;

    // color
    if (!isConflict() && hasMatches()) {

      Set<Revision> matchingRevisions = matches.keySet();

      // print color code
      String color = "";

      for (Revision rev : matchingRevisions) {
        m = getMatching(rev);
        color = m.getColor().toShell();
      }

      sb.append(color);
    }

    if (isConflict()) {
      sb.append(Color.RED.toShell());
      sb.append(indent).append("(").append(getId()).append(") ");
      sb.append(this);
      sb.append(System.lineSeparator());
      sb.append(Color.RED.toShell());
      sb.append("<<<<<<< ");
      sb.append(System.lineSeparator());
      // children
      if (left != null) {
        sb.append(left.dumpTree(indent));
      }
      sb.append(Color.RED.toShell());
      sb.append("======= ");
      sb.append(System.lineSeparator());
      // children
      if (right != null) {
        sb.append(right.dumpTree(indent));
      }

      sb.append(Color.RED.toShell());
      sb.append(">>>>>>> ");
      sb.append(System.lineSeparator());
    } else {
      sb.append(indent).append("(").append(getId()).append(") ");
      sb.append(this);

      if (hasMatches()) {
        assert (m != null);
        sb.append(" <=> (").append(m.getMatchingArtifact(this).getId()).append(")");
        sb.append(Color.DEFAULT.toShell());
      }
      sb.append(System.lineSeparator());

      // children
      for (ASTNodeArtifact child : getChildren()) {
        sb.append(child.dumpTree(indent + "  "));
      }
    }

    return sb.toString();
  }

  /*
   * (non-Javadoc)
   *
   * @see java.lang.Object#equals(java.lang.Object)
   */
  // @Override
  @Override
  public final boolean exists() {
    return astnode != null;
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#getId()
   */
  @Override
  public final String getId() {
    return getRevision() + "-" + getNumber();
  }

  @Override
  public final String getStatsKey(final MergeContext context) {
    return "nodes";
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#hashCode()
   */
  @Override
  public final int hashCode() {
    return astnode.dumpString().hashCode();
  }

  @Override
  public final boolean hasUniqueLabels() {
    return ImportDecl.class.isAssignableFrom(astnode.getClass())
        || Literal.class.isAssignableFrom(astnode.getClass());
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#initializeChildren()
   */
  @Override
  public final void initializeChildren() {
    assert (astnode != null);
    ArtifactList<ASTNodeArtifact> children = new ArtifactList<>();
    for (int i = 0; i < astnode.getNumChildNoTransform(); i++) {
      ASTNodeArtifact child = new ASTNodeArtifact(astnode.getChild(i));
      child.setParent(this);
      child.setRevision(getRevision());
      children.add(child);
    }
    setChildren(children);
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#isEmpty()
   */
  @Override
  public final boolean isEmpty() {
    return !hasChildren();
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#isLeaf()
   */
  @Override
  public final boolean isLeaf() {
    // TODO Auto-generated method stub
    return false;
  }

  /**
   * Returns whether declaration order is significant for this node.
   *
   * @return whether declaration order is significant for this node
   */
  @Override
  public final boolean isOrdered() {
    return !ConstructorDecl.class.isAssignableFrom(astnode.getClass())
        && !MethodDecl.class.isAssignableFrom(astnode.getClass())
        && !InterfaceDecl.class.isAssignableFrom(astnode.getClass())
        && !FieldDecl.class.isAssignableFrom(astnode.getClass())
        && !FieldDeclaration.class.isAssignableFrom(astnode.getClass())
        && !ImportDecl.class.isAssignableFrom(astnode.getClass());
  }

  /**
   * Returns whether a node matches another node.
   *
   * @param other node to compare with.
   * @return true if the node matches another node.
   */
  @Override
  public final boolean matches(final ASTNodeArtifact other) {
    assert (astnode != null);
    assert (other != null);
    assert (other.astnode != null);

    if (LOG.isDebugEnabled()) {
      LOG.debug("match(" + getId() + ", " + other.getId() + ")");
    }

    if ((ImportDecl.class.isAssignableFrom(astnode.getClass())
            || Literal.class.isAssignableFrom(astnode.getClass()))
        && other.astnode.getClass().equals(astnode.getClass())) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Try Matching (prettyPrint): {"
                + astnode.prettyPrint()
                + "} and {"
                + other.astnode.prettyPrint()
                + "}");
      }
      return astnode.prettyPrint().equals(other.astnode.prettyPrint());
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "Try Matching (dumpString): {"
              + astnode.dumpString()
              + "} and {"
              + other.astnode.dumpString()
              + "}");
    }
    return astnode.dumpString().equals(other.astnode.dumpString());
  }

  @Override
  public final void merge(MergeOperation<ASTNodeArtifact> operation, MergeContext context)
      throws IOException, InterruptedException {
    Objects.requireNonNull(operation, "operation must not be null!");
    Objects.requireNonNull(context, "context must not be null!");

    MergeStrategy<ASTNodeArtifact> astNodeStrategy = new ASTNodeStrategy();

    if (LOG.isDebugEnabled()) {
      LOG.debug("Using strategy: " + astNodeStrategy);
    }

    MergeTriple<ASTNodeArtifact> triple = operation.getMergeTriple();
    ASTNodeArtifact left = triple.getLeft();
    ASTNodeArtifact right = triple.getRight();
    ASTNodeArtifact target = operation.getTarget();

    boolean safeMerge = true;

    int numChildNoTransform;
    try {
      numChildNoTransform = target.astnode.getClass().newInstance().getNumChildNoTransform();
    } catch (InstantiationException | IllegalAccessException e) {
      throw new RuntimeException();
    }

    if (!isRoot() && numChildNoTransform > 0) {

      // this language element has a fixed number of children, we need to be careful with this one
      boolean leftChanges = left.hasChanges(false);
      boolean rightChanges = right.hasChanges(false);

      if (leftChanges && rightChanges) {

        if (LOG.isTraceEnabled()) {
          LOG.trace("Target " + target.getId() + " expects a fixed amount of children.");
          LOG.trace("Both " + left.getId() + " and " + right.getId() + " contain changes.");
          LOG.trace("We will report a conflict instead of performing the merge.");
        }
        safeMerge = false;

        // to be safe, we will report a conflict instead of merging
        ASTNodeArtifact targetParent = target.getParent();
        targetParent.removeChild(target);

        Operation<ASTNodeArtifact> conflictOp =
            new ConflictOperation<>(left, left, right, targetParent);
        conflictOp.apply(context);
      }
    }

    if (safeMerge) {
      astNodeStrategy.merge(operation, context);
    }

    if (!context.isQuiet() && context.hasOutput()) {
      System.out.print(context.getStdIn());
    }
  }

  /**
   * Removes a child.
   *
   * @param child child that should be removed
   */
  public final void removeChild(final ASTNodeArtifact child) {
    if (LOG.isTraceEnabled()) {
      LOG.trace("[" + getId() + "] removing child " + child.getId());
      LOG.trace("children before removal: " + getChildren());
    }

    Iterator<ASTNodeArtifact> it = children.iterator();
    ASTNodeArtifact elem;
    while (it.hasNext()) {
      elem = it.next();
      if (elem == child) {
        it.remove();
      }
    }

    if (LOG.isTraceEnabled()) {
      LOG.trace("children after removal: " + getChildren());
    }
  }

  /**
   * Pretty-prints the AST to source code.
   *
   * @return Pretty-printed AST (source code)
   */
  public final String prettyPrint() {
    assert (astnode != null);
    rebuildAST();
    astnode.flushCaches();
    if (LOG.isDebugEnabled()) {
      System.out.println(dumpTree());
    }
    return astnode.prettyPrint();
  }

  /** Rebuild the encapsulated ASTNode tree top down. This should be only called at the root node */
  public final void rebuildAST() {

    if (isConflict()) {
      astnode.isConflict = true;
      astnode.jdimeId = getId();

      if (left != null) {
        left.rebuildAST();
        astnode.left = left.astnode;
      }

      if (right != null) {
        right.rebuildAST();
        astnode.right = right.astnode;
      }
    }

    ASTNode<?>[] newchildren = new ASTNode[getNumChildren()];

    for (int i = 0; i < getNumChildren(); i++) {
      ASTNodeArtifact child = getChild(i);
      newchildren[i] = child.astnode;
      newchildren[i].setParent(astnode);
      child.rebuildAST();
    }
    astnode.jdimeChanges = hasChanges();
    astnode.jdimeId = getId();
    astnode.setChildren(newchildren);

    assert (isConflict() || getNumChildren() == astnode.getNumChildNoTransform());
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#toString()
   */
  @Override
  public final String toString() {
    assert (astnode != null);
    return astnode.dumpString();
  }

  /*
   * (non-Javadoc)
   *
   * @see de.fosd.jdime.common.Artifact#write(java.lang.String)
   */
  @Override
  public final void write(final String str) throws IOException {
    // TODO Auto-generated method stub
  }

  @Override
  public final ASTNodeArtifact createConflictDummy(
      final ASTNodeArtifact type, final ASTNodeArtifact left, final ASTNodeArtifact right)
      throws FileNotFoundException {
    ASTNodeArtifact conflict;

    conflict = new ASTNodeArtifact(type.astnode.fullCopy());
    conflict.setConflict(left, right);

    return conflict;
  }

  /**
   * Returns statistical data of the tree. stats[0]: number of nodes stats[1]: tree depth stats[2]:
   * maximum number of children
   *
   * @return statistics
   */
  public final int[] getStats() {
    // 0: number of nodes, 1: tree depth, 2: max children
    int[] mystats = new int[3];
    mystats[0] = 1;
    mystats[1] = 0;
    mystats[2] = getNumChildren();

    for (int i = 0; i < getNumChildren(); i++) {
      int[] childstats = getChild(i).getStats();
      mystats[0] += childstats[0];
      if (childstats[1] + 1 > mystats[1]) {
        mystats[1] = childstats[1] + 1;
      }
      if (childstats[2] > mystats[2]) {
        mystats[2] = childstats[2];
      }
    }

    return mystats;
  }

  public final ASTStats getStats(Revision revision, LangElem level, boolean isFragment) {
    StatsElement nodeStats = new StatsElement();
    StatsElement toplevelnodeStats = new StatsElement();
    StatsElement classlevelnodeStats = new StatsElement();
    StatsElement methodlevelnodeStats = new StatsElement();
    StatsElement classStats = new StatsElement();
    StatsElement methodStats = new StatsElement();

    // clearly, this is a node
    nodeStats.incrementElements();

    if (isConflict()) {
      nodeStats.incrementChanges();
      nodeStats.incrementConflicting();
    } else if ((revision == null && hasMatches()) || hasMatching(revision)) {
      nodeStats.incrementMatches();
    } else {
      nodeStats.incrementChanges();
      // added or deleted?
      if (hasMatches()) {
        // was deleted
        nodeStats.incrementDeleted();
      } else {
        // was added
        nodeStats.incrementAdded();
      }
    }

    StatsElement myStats = null;
    switch (level) {
      case TOPLEVELNODE:
        myStats = toplevelnodeStats;
        break;
      case CLASSLEVELNODE:
        myStats = classlevelnodeStats;
        break;
      case METHODLEVELNODE:
        myStats = methodlevelnodeStats;
        break;
      default:
        throw new NotYetImplementedException();
    }

    assert (myStats != null);

    nodeStats.copy(myStats);
    assert myStats.getElements() != 0;

    // find out level for child nodes and adjust class and method counter
    if (astnode instanceof ClassDecl) {
      level = LangElem.CLASSLEVELNODE;
      myStats.copy(classStats);
    } else if (astnode instanceof MethodDecl || astnode instanceof ConstructorDecl) {
      level = LangElem.METHODLEVELNODE;
      myStats.copy(methodStats);
    }

    HashMap<String, StatsElement> diffstats = new HashMap<>();
    diffstats.put(LangElem.NODE.toString(), nodeStats);
    diffstats.put(LangElem.TOPLEVELNODE.toString(), toplevelnodeStats);
    diffstats.put(LangElem.CLASSLEVELNODE.toString(), classlevelnodeStats);
    diffstats.put(LangElem.METHODLEVELNODE.toString(), methodlevelnodeStats);
    diffstats.put(LangElem.CLASS.toString(), classStats);
    diffstats.put(LangElem.METHOD.toString(), methodStats);
    ASTStats stats = new ASTStats(1, 1, getNumChildren(), diffstats, myStats.getChanges() != 0);
    boolean hasSubtreeChanges = stats.hasChanges();

    if (!hasSubtreeChanges) {
      isFragment = false;
    } else if (!isFragment) {
      isFragment = true;
      stats.incrementFragments();
    }

    boolean assertsEnabled = false;
    assert assertsEnabled = true;
    if (assertsEnabled) {
      for (String key : diffstats.keySet()) {
        StatsElement e = diffstats.get(key);
        assert (e.getElements()
            == e.getMatches() + e.getAdded() + e.getDeleted() + e.getConflicting());
        assert (e.getChanges() == e.getAdded() + e.getDeleted() + e.getConflicting());
      }
    }

    for (int i = 0; i < getNumChildren(); i++) {
      stats.add(getChild(i).getStats(revision, level, isFragment));

      if (!hasSubtreeChanges && stats.hasChanges()) {
        hasSubtreeChanges = true;
        if (astnode instanceof ClassDecl) {
          stats.getDiffStats(LangElem.CLASS.toString()).incrementChanges();
        } else if (astnode instanceof MethodDecl || astnode instanceof ConstructorDecl) {
          stats.getDiffStats(LangElem.METHOD.toString()).incrementChanges();
        }
      }

      if (assertsEnabled) {
        for (String key : diffstats.keySet()) {
          StatsElement e = diffstats.get(key);
          assert (e.getElements()
              == e.getMatches() + e.getAdded() + e.getDeleted() + e.getConflicting());
        }
      }
    }

    return stats;
  }
}
 private static boolean isMethodTypeNumber(IOpenClass methodType) {
   return ClassUtils.isAssignable(methodType.getInstanceClass(), Number.class, true);
 }