Esempio n. 1
0
 static String javaSignature(Class<?> type) {
   if (!type.isArray()) {
     return type.getName();
   } else {
     int arrayDimension = 0;
     do {
       ++arrayDimension;
       type = type.getComponentType();
     } while (type.isArray());
     String name = type.getName();
     String suffix = "[]";
     if (arrayDimension == 1) {
       return name.concat(suffix);
     } else {
       int length = name.length() + arrayDimension * suffix.length();
       StringBuffer sb = new StringBuffer(length);
       sb.append(name);
       while (arrayDimension != 0) {
         --arrayDimension;
         sb.append(suffix);
       }
       return sb.toString();
     }
   }
 }
Esempio n. 2
0
  private static void testPotato(
      Class<? extends Collection> implClazz, Class<? extends List> argClazz) throws Throwable {
    try {
      System.out.printf("implClazz=%s, argClazz=%s\n", implClazz.getName(), argClazz.getName());
      final int iterations = 100000;
      final List<Integer> list = (List<Integer>) argClazz.newInstance();
      final Integer one = Integer.valueOf(1);
      final List<Integer> oneElementList = Collections.singletonList(one);
      final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class);
      final Thread t =
          new CheckedThread() {
            public void realRun() {
              for (int i = 0; i < iterations; i++) {
                list.add(one);
                list.remove(one);
              }
            }
          };
      t.setDaemon(true);
      t.start();

      for (int i = 0; i < iterations; i++) {
        Collection<?> coll = constr.newInstance(list);
        Object[] elts = coll.toArray();
        check(elts.length == 0 || (elts.length == 1 && elts[0] == one));
      }
    } catch (Throwable t) {
      unexpected(t);
    }
  }
Esempio n. 3
0
  public static void validatePassivating(Class<?> cl, Bean<?> bean, String typeName) {
    Class<?> beanClass = bean.getBeanClass();

    if (!Serializable.class.isAssignableFrom(beanClass) && false) {
      ConfigException exn =
          new ConfigException(
              L.l(
                  "{0}: {1} is an invalid {2} because it is not serializable.",
                  cl.getName(), bean, typeName));

      throw exn;
      // InjectManager.create().addDefinitionError(exn);
    }

    for (InjectionPoint ip : bean.getInjectionPoints()) {
      if (ip.isTransient() || ip.isDelegate()) continue;

      Class<?> type = getRawClass(ip.getType());

      if (type.isInterface()) continue;

      if (!Serializable.class.isAssignableFrom(type)) {
        ConfigException exn =
            new ConfigException(
                L.l(
                    "{0}: {1} is an invalid {4} because its injection point '{2}' of type {3} is not serializable.",
                    cl.getName(), bean, ip.getMember().getName(), ip.getType(), typeName));

        throw exn;
      }
    }
  }
  /**
   * Creates a new entity enumeration icon chooser.
   *
   * @param enumeration the enumeration to display in this combo box
   */
  public EnumerationIconChooser(Class<E> enumeration) {
    super();

    this.enumeration = enumeration;

    try {
      this.icons = (ImageIcon[]) enumeration.getMethod("getIcons").invoke(null);
      for (int i = 0; i < icons.length; i++) {
        addItem(icons[i]);
      }
    } catch (NoSuchMethodException ex) {
      System.err.println(
          "The method 'getIcons()' is missing in enumeration " + enumeration.getName());
      ex.printStackTrace();
      System.exit(1);
    } catch (IllegalAccessException ex) {
      System.err.println(
          "Cannot access method 'getIcons()' in enumeration "
              + enumeration.getName()
              + ": ex.getMessage()");
      ex.printStackTrace();
      System.exit(1);
    } catch (InvocationTargetException ex) {
      ex.getCause().printStackTrace();
      System.exit(1);
    }
  }
  private void BuildSignature() {
    Var[] vars = new Var[samMethod.getParameterTypes().length];
    lambdaApplyParameters = new Class<?>[samMethod.getParameterTypes().length];
    for (int i = 0; i < vars.length; i++) {
      //noinspection unchecked
      Type paramType = samMethod.getGenericParameterTypes()[i];
      if (paramType instanceof Class) vars[i] = new Var((Class<?>) paramType);
      else if (paramType instanceof TypeVariable)
        vars[i] = new Var(findMaterializedType(((TypeVariable) paramType).getName()));
      else
        throw new LambdaException(
            "unexpected param generic type [%s] for SAM [%s]", paramType, samType.getName());

      lambdaApplyParameters[i] = Object.class;
    }

    Class<?> materializedRetType;
    Type genericRetType = samMethod.getGenericReturnType();
    if (genericRetType instanceof Class<?>) materializedRetType = samMethod.getReturnType();
    else if (genericRetType instanceof TypeVariable)
      materializedRetType = findMaterializedType(((TypeVariable) genericRetType).getName());
    else
      throw new LambdaException(
          "unexpected generic return type [%s] for SAM [%s]",
          samMethod.getReturnType(), samType.getName());

    this.lambdaSignature = new LambdaSignature<Object>(materializedRetType, vars);
  }
  private void setDNAndEntryFields(final T o, final Entry e) throws LDAPPersistException {
    if (dnField != null) {
      try {
        dnField.set(o, e.getDN());
      } catch (Exception ex) {
        debugException(ex);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_SETTING_DN.get(
                type.getName(), e.getDN(), dnField.getName(), getExceptionMessage(ex)),
            ex);
      }
    }

    if (entryField != null) {
      try {
        entryField.set(o, new ReadOnlyEntry(e));
      } catch (Exception ex) {
        debugException(ex);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_SETTING_ENTRY.get(
                type.getName(), entryField.getName(), getExceptionMessage(ex)),
            ex);
      }
    }
  }
  public String constructDN(final T o, final String parentDN) throws LDAPPersistException {
    final String existingDN = getEntryDN(o);
    if (existingDN != null) {
      return existingDN;
    }

    final LinkedHashMap<String, Attribute> attrMap = new LinkedHashMap<String, Attribute>(1);

    for (final FieldInfo i : rdnFields) {
      final Attribute a = i.encode(o, true);
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_FIELD_MISSING_VALUE.get(type.getName(), i.getField().getName()));
      }

      attrMap.put(toLowerCase(i.getAttributeName()), a);
    }

    for (final GetterInfo i : rdnGetters) {
      final Attribute a = i.encode(o);
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_GETTER_MISSING_VALUE.get(
                type.getName(), i.getMethod().getName()));
      }

      attrMap.put(toLowerCase(i.getAttributeName()), a);
    }

    return constructDN(o, parentDN, attrMap);
  }
Esempio n. 8
0
 public static <T> Constructor<T> findConstructor(Class<T> cls, boolean canFixAccess)
     throws IllegalArgumentException {
   try {
     Constructor<T> ctor = cls.getDeclaredConstructor();
     if (canFixAccess) {
       checkAndFixAccess(ctor);
     } else {
       // Has to be public...
       if (!Modifier.isPublic(ctor.getModifiers())) {
         throw new IllegalArgumentException(
             "Default constructor for "
                 + cls.getName()
                 + " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type");
       }
     }
     return ctor;
   } catch (NoSuchMethodException e) {;
   } catch (Exception e) {
     ClassUtil.unwrapAndThrowAsIAE(
         e,
         "Failed to find default constructor of class "
             + cls.getName()
             + ", problem: "
             + e.getMessage());
   }
   return null;
 }
Esempio n. 9
0
 private static boolean typeMatches(Class<?> foundType, Class<?> expectedType) {
   if (foundType == null) return true;
   if (expectedType.isAssignableFrom(foundType)) return true;
   if (isPrimitiveType(expectedType.getName())
       && foundType.equals(getWrapper(expectedType.getName()))) return true;
   if (isPrimitiveType(foundType.getName())
       && expectedType.equals(getWrapper(foundType.getName()))) return true;
   if (isNumberType(foundType) && isNumberType(expectedType)) return true;
   return false;
 }
Esempio n. 10
0
 /**
  * Convert the type into a string. The string representation approximates the code that would be
  * used to define the type.
  *
  * @param type - the type.
  * @return a string representation of the type, similar to how it was declared.
  */
 public static String toString(Type type) {
   if (type instanceof ParameterizedType) return toString((ParameterizedType) type);
   if (type instanceof WildcardType) return toString((WildcardType) type);
   if (type instanceof GenericArrayType) return toString((GenericArrayType) type);
   if (type instanceof Class) {
     final Class theClass = (Class) type;
     return (theClass.isArray() ? theClass.getName() + "[]" : theClass.getName());
   }
   return type.toString();
 }
Esempio n. 11
0
 public void process(File cFile) {
   try {
     String cName = ClassNameFinder.thisClass(BinaryFile.read(cFile));
     if (!cName.contains("")) return; // Ignore unpackaged classes
     testClass = Class.forName(cName);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   TestMethods testMethods = new TestMethods();
   Method creator = null;
   Method cleanup = null;
   for (Method m : testClass.getDeclaredMethods()) {
     testMethods.addIfTestMethod(m);
     if (creator == null) creator = checkForCreatorMethod(m);
     if (cleanup == null) cleanup = checkForCleanupMethod(m);
   }
   if (testMethods.size() > 0) {
     if (creator == null)
       try {
         if (!Modifier.isPublic(testClass.getDeclaredConstructor().getModifiers())) {
           Print.print("Error: " + testClass + " default constructor must be public");
           System.exit(1);
         }
       } catch (NoSuchMethodException e) {
         // Synthesized default constructor; OK
       }
     Print.print(testClass.getName());
   }
   for (Method m : testMethods) {
     Print.printnb("  . " + m.getName() + " ");
     try {
       Object testObject = createTestObject(creator);
       boolean success = false;
       try {
         if (m.getReturnType().equals(boolean.class)) success = (Boolean) m.invoke(testObject);
         else {
           m.invoke(testObject);
           success = true; // If no assert fails
         }
       } catch (InvocationTargetException e) {
         // Actual exception is inside e:
         Print.print(e.getCause());
       }
       Print.print(success ? "" : "(failed)");
       testsRun++;
       if (!success) {
         failures++;
         failedTests.add(testClass.getName() + ": " + m.getName());
       }
       if (cleanup != null) cleanup.invoke(testObject, testObject);
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
Esempio n. 12
0
  public static void premain(String args, Instrumentation inst) throws Exception {
    try {
      String[] agentArgs;
      if (args == null) agentArgs = new String[] {""};
      else agentArgs = args.split(",");
      if (!agentArgs[0].equals("instrumenting")) jarFileName = agentArgs[0];
      BaseClassTransformer rct = null;
      rct = new BaseClassTransformer();
      if (agentArgs[0].equals("instrumenting")) {
        initVMClasses = new HashSet<String>();
        for (Class<?> c : inst.getAllLoadedClasses()) {
          ((Set<String>) initVMClasses).add(c.getName());
        }
      }
      if (!agentArgs[0].equals("instrumenting")) {

        inst.addTransformer(rct);
        Tracer.setLocals(new CounterThreadLocal());
        Tracer.overrideAll(true);
        for (Class<?> c : inst.getAllLoadedClasses()) {
          try {
            if (c.isInterface()) continue;
            if (c.isArray()) continue;
            byte[] bytes = rct.getBytes(c.getName());
            if (bytes == null) {
              continue;
            }
            inst.redefineClasses(new ClassDefinition[] {new ClassDefinition(c, bytes)});
          } catch (Throwable e) {
            synchronized (System.err) {
              System.err.println("" + c + " failed...");
              e.printStackTrace();
            }
          }
        }
        Runtime.getRuntime()
            .addShutdownHook(
                new Thread() {
                  public void run() {
                    Tracer.mark();
                    try {
                      PrintStream ps = new PrintStream("bailout.txt");
                      ps.println("Bailouts: " + Tracer.getBailoutCount());
                      ps.close();
                    } catch (Exception e) {
                    }
                    Tracer.unmark();
                  }
                });
        if ("true".equals(System.getProperty("bci.observerOn"))) Tracer.overrideAll(false);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 13
0
 private void visitType(java.lang.reflect.Type type, StringBuilder builder) {
   if (type instanceof Class) {
     Class<?> cl = (Class<?>) type;
     if (cl.isPrimitive()) {
       builder.append(Type.getType(cl).getDescriptor());
     } else {
       if (cl.isArray()) {
         builder.append(cl.getName().replace('.', '/'));
       } else {
         builder.append('L');
         builder.append(cl.getName().replace('.', '/'));
         builder.append(';');
       }
     }
   } else if (type instanceof ParameterizedType) {
     ParameterizedType parameterizedType = (ParameterizedType) type;
     visitNested(parameterizedType.getRawType(), builder);
     builder.append('<');
     for (java.lang.reflect.Type param : parameterizedType.getActualTypeArguments()) {
       visitType(param, builder);
     }
     builder.append(">;");
   } else if (type instanceof WildcardType) {
     WildcardType wildcardType = (WildcardType) type;
     if (wildcardType.getUpperBounds().length == 1
         && wildcardType.getUpperBounds()[0].equals(Object.class)) {
       if (wildcardType.getLowerBounds().length == 0) {
         builder.append('*');
         return;
       }
     } else {
       for (java.lang.reflect.Type upperType : wildcardType.getUpperBounds()) {
         builder.append('+');
         visitType(upperType, builder);
       }
     }
     for (java.lang.reflect.Type lowerType : wildcardType.getLowerBounds()) {
       builder.append('-');
       visitType(lowerType, builder);
     }
   } else if (type instanceof TypeVariable) {
     TypeVariable<?> typeVar = (TypeVariable) type;
     builder.append('T');
     builder.append(typeVar.getName());
     builder.append(';');
   } else if (type instanceof GenericArrayType) {
     GenericArrayType arrayType = (GenericArrayType) type;
     builder.append('[');
     visitType(arrayType.getGenericComponentType(), builder);
   } else {
     throw new IllegalArgumentException(
         String.format("Cannot generate signature for %s.", type));
   }
 }
Esempio n. 14
0
  String constructDN(final T o, final String parentDN, final Map<String, Attribute> attrMap)
      throws LDAPPersistException {
    final String existingDN = getEntryDN(o);
    if (existingDN != null) {
      return existingDN;
    }

    final ArrayList<String> rdnNameList = new ArrayList<String>(1);
    final ArrayList<byte[]> rdnValueList = new ArrayList<byte[]>(1);
    for (final FieldInfo i : rdnFields) {
      final Attribute a = attrMap.get(toLowerCase(i.getAttributeName()));
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_FIELD_MISSING_VALUE.get(type.getName(), i.getField().getName()));
      }

      rdnNameList.add(a.getName());
      rdnValueList.add(a.getValueByteArray());
    }

    for (final GetterInfo i : rdnGetters) {
      final Attribute a = attrMap.get(toLowerCase(i.getAttributeName()));
      if (a == null) {
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_RDN_GETTER_MISSING_VALUE.get(
                type.getName(), i.getMethod().getName()));
      }

      rdnNameList.add(a.getName());
      rdnValueList.add(a.getValueByteArray());
    }

    final String[] rdnNames = new String[rdnNameList.size()];
    rdnNameList.toArray(rdnNames);

    final byte[][] rdnValues = new byte[rdnNames.length][];
    rdnValueList.toArray(rdnValues);

    final RDN rdn = new RDN(rdnNames, rdnValues);

    if (parentDN == null) {
      return new DN(rdn, defaultParentDN).toString();
    } else {
      try {
        final DN parsedParentDN = new DN(parentDN);
        return new DN(rdn, parsedParentDN).toString();
      } catch (LDAPException le) {
        debugException(le);
        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_INVALID_PARENT_DN.get(type.getName(), parentDN, le.getMessage()),
            le);
      }
    }
  }
 private void ensureProtectedAccess(T obj) {
   if (cclass.isInstance(obj)) {
     return;
   }
   throw new RuntimeException(
       new IllegalAccessException(
           "Class "
               + cclass.getName()
               + " can not access a protected member of class "
               + tclass.getName()
               + " using an instance of "
               + obj.getClass().getName()));
 }
Esempio n. 16
0
 /**
  * Method that can be called to try to create an instantiate of specified type. Instantiation is
  * done using default no-argument constructor.
  *
  * @param canFixAccess Whether it is possible to try to change access rights of the default
  *     constructor (in case it is not publicly accessible) or not.
  * @throws IllegalArgumentException If instantiation fails for any reason; except for cases where
  *     constructor throws an unchecked exception (which will be passed as is)
  */
 public static <T> T createInstance(Class<T> cls, boolean canFixAccess)
     throws IllegalArgumentException {
   Constructor<T> ctor = findConstructor(cls, canFixAccess);
   if (ctor == null) {
     throw new IllegalArgumentException(
         "Class " + cls.getName() + " has no default (no arg) constructor");
   }
   try {
     return ctor.newInstance();
   } catch (Exception e) {
     ClassUtil.unwrapAndThrowAsIAE(
         e, "Failed to instantiate class " + cls.getName() + ", problem: " + e.getMessage());
     return null;
   }
 }
Esempio n. 17
0
 /**
  * Gets the datatype of the object.
  *
  * @param obj the object
  * @return the type
  */
 public static String getDataType(Object obj) {
   if (obj == null) {
     return null;
   }
   if (obj instanceof String) {
     return "string"; //$NON-NLS-1$
   } else if (obj instanceof Collection) {
     return "collection"; //$NON-NLS-1$
   } else if (obj.getClass().isArray()) {
     // make sure ultimate component class is acceptable
     Class componentType = obj.getClass().getComponentType();
     while (componentType.isArray()) {
       componentType = componentType.getComponentType();
     }
     String type = componentType.getName();
     if (type.indexOf(".") == -1
         && "intdoubleboolean".indexOf(type) == -1) { // $NON-NLS-1$ //$NON-NLS-2$
       return null;
     }
     return "array"; //$NON-NLS-1$
   } else if (obj instanceof Double) {
     return "double"; //$NON-NLS-1$
   } else if (obj instanceof Integer) {
     return "int"; //$NON-NLS-1$
   } else {
     return "object"; //$NON-NLS-1$
   }
 }
Esempio n. 18
0
 /**
  * Generates code to push typed parameters onto the operand stack prior to a direct Java method
  * call.
  */
 private static int generatePushParam(ClassFileWriter cfw, int paramOffset, Class<?> paramType) {
   if (!paramType.isPrimitive()) {
     cfw.addALoad(paramOffset);
     return 1;
   }
   String typeName = paramType.getName();
   switch (typeName.charAt(0)) {
     case 'z':
     case 'b':
     case 'c':
     case 's':
     case 'i':
       // load an int value, convert to double.
       cfw.addILoad(paramOffset);
       return 1;
     case 'l':
       // load a long, convert to double.
       cfw.addLLoad(paramOffset);
       return 2;
     case 'f':
       // load a float, convert to double.
       cfw.addFLoad(paramOffset);
       return 1;
     case 'd':
       cfw.addDLoad(paramOffset);
       return 2;
   }
   throw Kit.codeBug();
 }
Esempio n. 19
0
  private void restoreDefinition(@Nonnull Class<?> redefinedClass) {
    if (redefinedClassesWithNativeMethods.contains(redefinedClass.getName())) {
      reregisterNativeMethodsForRestoredClass(redefinedClass);
    }

    removeMockedClass(redefinedClass);
  }
Esempio n. 20
0
 /**
  * Generates code to return a Java type, after calling a Java method that returns the same type.
  * Generates the appropriate RETURN bytecode.
  */
 private static void generatePopResult(ClassFileWriter cfw, Class<?> retType) {
   if (retType.isPrimitive()) {
     String typeName = retType.getName();
     switch (typeName.charAt(0)) {
       case 'b':
       case 'c':
       case 's':
       case 'i':
       case 'z':
         cfw.add(ByteCode.IRETURN);
         break;
       case 'l':
         cfw.add(ByteCode.LRETURN);
         break;
       case 'f':
         cfw.add(ByteCode.FRETURN);
         break;
       case 'd':
         cfw.add(ByteCode.DRETURN);
         break;
     }
   } else {
     cfw.add(ByteCode.ARETURN);
   }
 }
Esempio n. 21
0
  Entry encode(final T o, final String parentDN) throws LDAPPersistException {
    // Get the attributes that should be included in the entry.
    final LinkedHashMap<String, Attribute> attrMap = new LinkedHashMap<String, Attribute>();
    attrMap.put("objectClass", objectClassAttribute);

    for (final Map.Entry<String, FieldInfo> e : fieldMap.entrySet()) {
      final FieldInfo i = e.getValue();
      if (!i.includeInAdd()) {
        continue;
      }

      final Attribute a = i.encode(o, false);
      if (a != null) {
        attrMap.put(e.getKey(), a);
      }
    }

    for (final Map.Entry<String, GetterInfo> e : getterMap.entrySet()) {
      final GetterInfo i = e.getValue();
      if (!i.includeInAdd()) {
        continue;
      }

      final Attribute a = i.encode(o);
      if (a != null) {
        attrMap.put(e.getKey(), a);
      }
    }

    final String dn = constructDN(o, parentDN, attrMap);
    final Entry entry = new Entry(dn, attrMap.values());

    if (postEncodeMethod != null) {
      try {
        postEncodeMethod.invoke(o, entry);
      } catch (Throwable t) {
        debugException(t);

        if (t instanceof InvocationTargetException) {
          t = ((InvocationTargetException) t).getTargetException();
        }

        throw new LDAPPersistException(
            ERR_OBJECT_HANDLER_ERROR_INVOKING_POST_ENCODE_METHOD.get(
                postEncodeMethod.getName(), type.getName(), getExceptionMessage(t)),
            t);
      }
    }

    setDNAndEntryFields(o, entry);

    if (superclassHandler != null) {
      final Entry e = superclassHandler.encode(o, parentDN);
      for (final Attribute a : e.getAttributes()) {
        entry.addAttribute(a);
      }
    }

    return entry;
  }
Esempio n. 22
0
 JavaMembers(Scriptable scope, Class<?> cl, boolean includeProtected) {
   try {
     Context cx = ContextFactory.getGlobal().enterContext();
     ClassShutter shutter = cx.getClassShutter();
     if (shutter != null && !shutter.visibleToScripts(cl.getName())) {
       throw Context.reportRuntimeError1("msg.access.prohibited", cl.getName());
     }
     this.includePrivate = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS);
     this.members = new HashMap<String, Object>();
     this.staticMembers = new HashMap<String, Object>();
     this.cl = cl;
     reflect(scope, includeProtected);
   } finally {
     Context.exit();
   }
 }
Esempio n. 23
0
 private Class findMaterializedType(String name) {
   for (MaterializedTypeVariable materializedTypeVariable : materializedTypeVariableses) {
     if (materializedTypeVariable.name.equals(name)) return materializedTypeVariable.actualClass;
   }
   throw new LambdaException(
       "materialized type not found for name [%s] for SAM [%s]", name, samType.getName());
 }
  public static void main(String[] args) {
    // read class name from command line args or user input
    String name;
    if (args.length > 0) name = args[0];
    else {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter class name (e.g. java.util.Date): ");
      name = in.next();
    }

    try {
      // print class name and superclass name (if != Object)
      Class cl = Class.forName(name);
      Class supercl = cl.getSuperclass();
      String modifiers = Modifier.toString(cl.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.print("class " + name);
      if (supercl != null && supercl != Object.class)
        System.out.print(" extends " + supercl.getName());

      System.out.print("\n{\n");
      printConstructors(cl);
      System.out.println();
      printMethods(cl);
      System.out.println();
      printFields(cl);
      System.out.println("}");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    System.exit(0);
  }
Esempio n. 25
0
 static boolean derivesFrom(Class<?> c, String className) {
   while (c != null) {
     if (c.getName().equals(className)) return true;
     c = c.getSuperclass();
   }
   return false;
 }
  /**
   * Computes the serial version UID value for the given class. The code is taken from {@link
   * ObjectStreamClass#computeDefaultSUID(Class)}.
   *
   * @param cls A class.
   * @return A serial version UID.
   * @throws IOException If failed.
   */
  static long computeSerialVersionUid(Class cls) throws IOException {
    if (Serializable.class.isAssignableFrom(cls) && !Enum.class.isAssignableFrom(cls)) {
      return ObjectStreamClass.lookup(cls).getSerialVersionUID();
    }

    MessageDigest md;

    try {
      md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
      throw new IOException("Failed to get digest for SHA.", e);
    }

    md.update(cls.getName().getBytes(UTF_8));

    for (Field f : getFieldsForSerialization(cls)) {
      md.update(f.getName().getBytes(UTF_8));
      md.update(f.getType().getName().getBytes(UTF_8));
    }

    byte[] hashBytes = md.digest();

    long hash = 0;

    // Composes a single-long hash from the byte[] hash.
    for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--)
      hash = (hash << 8) | (hashBytes[i] & 0xFF);

    return hash;
  }
Esempio n. 27
0
 public static void setEnv(Map<String, String> newenv) {
   try {
     Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
     Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
     theEnvironmentField.setAccessible(true);
     Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
     env.putAll(newenv);
     Field theCaseInsensitiveEnvironmentField =
         processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
     theCaseInsensitiveEnvironmentField.setAccessible(true);
     Map<String, String> cienv =
         (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
     cienv.putAll(newenv);
   } catch (NoSuchFieldException e) {
     try {
       Class[] classes = Collections.class.getDeclaredClasses();
       Map<String, String> env = System.getenv();
       for (Class cl : classes) {
         if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
           Field field = cl.getDeclaredField("m");
           field.setAccessible(true);
           Object obj = field.get(env);
           Map<String, String> map = (Map<String, String>) obj;
           map.clear();
           map.putAll(newenv);
         }
       }
     } catch (Exception e2) {
       e2.printStackTrace();
     }
   } catch (Exception e1) {
     e1.printStackTrace();
   }
 }
Esempio n. 28
0
  public JavaType findType(String name) {
    if (_bindings == null) {
      _resolve();
    }
    JavaType t = _bindings.get(name);
    if (t != null) {
      return t;
    }
    if (_placeholders != null && _placeholders.contains(name)) {
      return UNBOUND;
    }
    // New with 1.7: check parent context
    if (_parentBindings != null) {
      return _parentBindings.findType(name);
    }
    // nothing found, so...
    // Should we throw an exception or just return null?

    /* [JACKSON-499] 18-Feb-2011, tatu: There are some tricky type bindings within
     *   java.util, such as HashMap$KeySet; so let's punt the problem
     *   (honestly not sure what to do -- they are unbound for good, I think)
     */
    if (_contextClass != null) {
      Class<?> enclosing = _contextClass.getEnclosingClass();
      if (enclosing != null) {
        // [JACKSON-572]: Actually, let's skip this for all non-static inner classes
        //   (which will also cover 'java.util' type cases...
        if (!Modifier.isStatic(_contextClass.getModifiers())) {
          return UNBOUND;
        }

        // ... so this piece of code should not be needed any more
        /*
        Package pkg = enclosing.getPackage();
        if (pkg != null) {
            // as per [JACKSON-533], also include "java.util.concurrent":
            if (pkg.getName().startsWith("java.util")) {
                return UNBOUND;
            }
        }
        */
      }
    }

    String className;
    if (_contextClass != null) {
      className = _contextClass.getName();
    } else if (_contextType != null) {
      className = _contextType.toString();
    } else {
      className = "UNKNOWN";
    }
    throw new IllegalArgumentException(
        "Type variable '"
            + name
            + "' can not be resolved (with context of class "
            + className
            + ")");
    // t = UNBOUND;
  }
Esempio n. 29
0
 /**
  * @deprecated Use {@link #getTypeTag(Class)} and {@link #convertArg(Context, Scriptable, Object,
  *     int)} for type convertion.
  */
 public static Object convertArg(Context cx, Scriptable scope, Object arg, Class desired) {
   int tag = getTypeTag(desired);
   if (tag == JAVA_UNSUPPORTED_TYPE) {
     throw Context.reportRuntimeError1("msg.cant.convert", desired.getName());
   }
   return convertArg(cx, scope, arg, tag);
 }
Esempio n. 30
0
 /**
  * Gets a simple class name for the specified class type.
  *
  * @param type the class
  * @return the simple class name
  */
 public static String getSimpleClassName(Class type) {
   String name = type.getName();
   // trim trailing semicolon, if any
   int i = name.indexOf(";"); // $NON-NLS-1$
   if (i > -1) {
     name = name.substring(0, i);
   }
   // add brackets for arrays
   while (name.startsWith("[")) { // $NON-NLS-1$
     name = name.substring(1);
     name = name + "[]"; // $NON-NLS-1$
   }
   // eliminate leading package name, if any
   String ext = XML.getExtension(name);
   if (ext != null) {
     name = ext;
   }
   // substitute int for I and double for D arrays
   i = name.indexOf("["); // $NON-NLS-1$
   if (i > -1) {
     String s = name.substring(0, i);
     if (s.equals("I")) { // $NON-NLS-1$
       s = "int"; // $NON-NLS-1$
     } else if (s.equals("D")) { // $NON-NLS-1$
       s = "double"; // $NON-NLS-1$
     } else if (s.equals("Z")) { // $NON-NLS-1$
       s = "boolean"; // $NON-NLS-1$
     }
     name = s + name.substring(i);
   }
   return name;
 }