示例#1
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;
 }
示例#2
0
  public Object lookup(Class clazz) {
    log.debug("looking up " + clazz.getName());
    //		if (clazz.getName().equals("org.openide.actions.ActionManager")) {
    //			return actionManager; ////
    //		}
    //		else
    if (clazz.getName().indexOf("Registry") != -1) {
      WindowManager wm = WindowManager.getDefault();
      if (wm != null && wm instanceof DummyWindowManager) {
        return ((DummyWindowManager) wm).registry();
      } else {
        log.warn("unable to return registry");
      }
    } else if (clazz.getName().indexOf("DialogDisplayer") != -1) {
      if (dialog == null) {
        dialog = new NbDialogDisplayer();
      }

      return dialog;
    } else if (clazz.getName().indexOf("NodeOp") != -1) {
      if (nodeOp == null) {
        nodeOp = new NbNodeOperation();
      }

      return nodeOp;
    }
    // this can be further tuned to better performance
    Lookup.Item item = lookupItem(new Lookup.Template(clazz));
    return item == null ? null : item.getInstance();
  }
示例#3
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);
    }
  }
示例#4
0
  public Class findClass(Class requiredInterface) throws ServiceNotFoundException {
    Class[] classes = findClasses(requiredInterface);
    if (PrioritizedService.class.isAssignableFrom(requiredInterface)) {
      PrioritizedService returnObject = null;
      for (Class clazz : classes) {
        PrioritizedService newInstance;
        try {
          newInstance = (PrioritizedService) clazz.newInstance();
        } catch (Exception e) {
          throw new UnexpectedLiquibaseException(e);
        }

        if (returnObject == null || newInstance.getPriority() > returnObject.getPriority()) {
          returnObject = newInstance;
        }
      }

      if (returnObject == null) {
        throw new ServiceNotFoundException(
            "Could not find implementation of " + requiredInterface.getName());
      }
      return returnObject.getClass();
    }

    if (classes.length != 1) {
      throw new ServiceNotFoundException(
          "Could not find unique implementation of "
              + requiredInterface.getName()
              + ".  Found "
              + classes.length
              + " implementations");
    }

    return classes[0];
  }
  private Map<String, SpringResource> generateResourceMap(Set<Class<?>> validClasses)
      throws GenerateException {
    Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>();
    for (Class<?> c : validClasses) {
      RequestMapping requestMapping = c.getAnnotation(RequestMapping.class);
      String description = "";
      // This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError
      // This occurs when a class or method loaded by reflections contains a type that has no
      // dependency
      try {
        resourceMap = analyzeController(c, resourceMap, description);
        List<Method> mList = new ArrayList<Method>(Arrays.asList(c.getMethods()));
        if (c.getSuperclass() != null) {
          mList.addAll(Arrays.asList(c.getSuperclass().getMethods()));
        }

      } catch (NoClassDefFoundError e) {
        LOG.error(e.getMessage());
        LOG.info(c.getName());
        // exception occurs when a method type or annotation is not recognized by the plugin
      } catch (ClassNotFoundException e) {
        LOG.error(e.getMessage());
        LOG.info(c.getName());
      }
    }

    return resourceMap;
  }
 private void findBeans() {
   try {
     Object currentConfiguration = null;
     for (Class<?> c : configurations) {
       currentConfiguration = c.newInstance();
       for (Method m : c.getDeclaredMethods()) {
         if (m.isAnnotationPresent(Bean.class)) {
           m.setAccessible(true);
           Class<?> returnClass = m.getReturnType();
           if (m.getAnnotation(Bean.class).value()) {
             beans.put(
                 returnClass.getName(),
                 new SingletonBeanDefinition(returnClass, m.invoke(currentConfiguration)));
           } else {
             beans.put(
                 returnClass.getName(),
                 new PrototypeBeanDefinition(returnClass, currentConfiguration, m));
           }
         }
       }
     }
   } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
     e.printStackTrace();
     throw new FailureBeanCreationException(e);
   }
 }
  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);
      }
    }
  }
示例#8
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();
     }
   }
 }
  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);
  }
示例#10
0
  public static void main(String[] args) throws Exception {
    int numTests = 100;
    int size = 36864; // about midway of HashMap resize interval

    if (args.length == 0)
      System.out.println(
          "Usage: MapCheck mapclass [int|float|string|object] [trials] [size] [serialtest]");

    if (args.length > 0) {
      try {
        mapClass = Class.forName(args[0]);
      } catch (ClassNotFoundException e) {
        throw new RuntimeException("Class " + args[0] + " not found.");
      }
    }

    if (args.length > 1) {
      String et = args[1].toLowerCase();
      if (et.startsWith("i")) eclass = java.lang.Integer.class;
      else if (et.startsWith("f")) eclass = java.lang.Float.class;
      else if (et.startsWith("s")) eclass = java.lang.String.class;
      else if (et.startsWith("d")) eclass = java.lang.Double.class;
    }
    if (eclass == null) eclass = Object.class;

    if (args.length > 2) numTests = Integer.parseInt(args[2]);

    if (args.length > 3) size = Integer.parseInt(args[3]);

    boolean doSerializeTest = args.length > 4;

    while ((size & 3) != 0) ++size;

    System.out.print("Class: " + mapClass.getName());
    System.out.print(" elements: " + eclass.getName());
    System.out.print(" trials: " + numTests);
    System.out.print(" size: " + size);
    System.out.println();

    Object[] key = new Object[size];
    Object[] absent = new Object[size];
    initializeKeys(key, absent, size);

    precheck(size, key, absent);

    for (int rep = 0; rep < numTests; ++rep) {
      mainTest(newMap(), key, absent);
      if ((rep & 3) == 3 && rep < numTests - 1) {
        shuffle(key);
        //                Thread.sleep(10);
      }
    }

    TestTimer.printStats();

    checkNullKey();

    if (doSerializeTest) serTest(newMap(), size);
  }
示例#11
0
 private void expandSupertypes(Multimap<String, String> mmap, String key, Class<?> type) {
   for (Class<?> supertype : ReflectionUtils.getSuperTypes(type)) {
     if (mmap.put(supertype.getName(), key)) {
       if (log != null) log.debug("expanded subtype {} -> {}", supertype.getName(), key);
       expandSupertypes(mmap, supertype.getName(), supertype);
     }
   }
 }
示例#12
0
 /**
  * Convenience constructor. Creates the context string as the class name appended with the
  * subcontext, with a "." if required.
  */
 public Logger(Class cls, String subCategory) {
   if (subCategory == null) {
     init(cls.getName());
   } else if (subCategory.charAt(0) == '.') {
     init(cls.getName() + subCategory);
   } else {
     init(cls.getName() + "." + subCategory);
   }
 }
 public static <T> T assertInstanceOf(Object o, Class<T> aClass) {
   Assert.assertNotNull("Expected instance of: " + aClass.getName() + " actual: " + null, o);
   Assert.assertTrue(
       "Expected instance of: " + aClass.getName() + " actual: " + o.getClass().getName(),
       aClass.isInstance(o));
   @SuppressWarnings("unchecked")
   T t = (T) o;
   return t;
 }
示例#14
0
 @Nonnull
 public static <T> Class<T> requireAnnotation(
     @Nonnull Class<T> klass, @Nonnull Class<? extends Annotation> annotationType) {
   if (!isAnnotatedWith(klass, annotationType)) {
     throw new IllegalArgumentException(
         "Class " + klass.getName() + " is not annotated with " + annotationType.getName());
   }
   return klass;
 }
示例#15
0
  public void shutdown() {
    LOGGER.warn("shutting down");
    {
      // send system audit event
      final SystemAuditRecord auditRecord =
          SystemAuditRecord.create(AuditEvent.SHUTDOWN, null, getInstanceID());
      try {
        getAuditManager().submit(auditRecord);
      } catch (PwmException e) {
        LOGGER.warn("unable to submit alert event " + JsonUtil.serialize(auditRecord));
      }
    }

    {
      final List<Class> reverseServiceList = new ArrayList<Class>(PWM_SERVICE_CLASSES);
      Collections.reverse(reverseServiceList);
      for (final Class serviceClass : reverseServiceList) {
        if (pwmServices.containsKey(serviceClass)) {
          LOGGER.trace("closing service " + serviceClass.getName());
          final PwmService loopService = pwmServices.get(serviceClass);
          LOGGER.trace("successfully closed service " + serviceClass.getName());
          try {
            loopService.close();
          } catch (Exception e) {
            LOGGER.error(
                "error closing " + loopService.getClass().getSimpleName() + ": " + e.getMessage(),
                e);
          }
        }
      }
    }

    if (localDBLogger != null) {
      try {
        localDBLogger.close();
      } catch (Exception e) {
        LOGGER.error("error closing localDBLogger: " + e.getMessage(), e);
      }
      localDBLogger = null;
    }

    if (localDB != null) {
      try {
        localDB.close();
      } catch (Exception e) {
        LOGGER.fatal("error closing localDB: " + e, e);
      }
      localDB = null;
    }

    LOGGER.info(
        PwmConstants.PWM_APP_NAME
            + " "
            + PwmConstants.SERVLET_VERSION
            + " closed for bidness, cya!");
  }
 @Override
 public Settings getComponentSettings(Class component) {
   if (component.getName().startsWith("org.elasticsearch")) {
     return getComponentSettings("org.elasticsearch", component);
   }
   // not starting with org.elasticsearch, just remove the first package part (probably
   // org/net/com)
   return getComponentSettings(
       component.getName().substring(0, component.getName().indexOf('.')), component);
 }
示例#17
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;
 }
示例#18
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();
    }
  }
示例#19
0
  protected Method findBaseAccessor(Class clazz, Method accessor) {
    Method baseAccessor = null;
    if (clazz.getName().contains("$$EnhancerByCGLIB$$")) {
      try {
        baseAccessor =
            Thread.currentThread()
                .getContextClassLoader()
                .loadClass(clazz.getName().substring(0, clazz.getName().indexOf("$$")))
                .getMethod(accessor.getName(), accessor.getParameterTypes());
      } catch (Exception ex) {
        LOG.debug(ex.getMessage(), ex);
      }
    } else if (clazz.getName().contains("$$_javassist")) {
      try {
        baseAccessor =
            Class.forName(clazz.getName().substring(0, clazz.getName().indexOf("_$$")))
                .getMethod(accessor.getName(), accessor.getParameterTypes());
      } catch (Exception ex) {
        LOG.debug(ex.getMessage(), ex);
      }

      // in hibernate4.3.7,because javassist3.18.1's class name generate rule is '_$$_jvst'+...
    } else if (clazz.getName().contains("$$_jvst")) {
      try {
        baseAccessor =
            Class.forName(clazz.getName().substring(0, clazz.getName().indexOf("_$$")))
                .getMethod(accessor.getName(), accessor.getParameterTypes());
      } catch (Exception ex) {
        LOG.debug(ex.getMessage(), ex);
      }
    } else {
      return accessor;
    }
    return baseAccessor;
  }
  /**
   * Gets all the annotation info for a particular class and puts it in our annotation info cache.
   *
   * @param c
   * @return
   */
  public AnnotationInfo putAnnotationInfo(Class c) {
    {
      Entity entity = (Entity) c.getAnnotation(Entity.class);
      if (entity == null) {
        throw new PersistenceException("Class not marked as an @Entity: " + c.getName());
      }
    }
    AnnotationInfo ai = new AnnotationInfo();
    ai.setClassAnnotations(c.getAnnotations());
    ai.setMainClass(c);
    Class superClass = c;
    Class rootClass = null;
    while ((superClass = superClass.getSuperclass()) != null) {
      MappedSuperclass mappedSuperclass =
          (MappedSuperclass) superClass.getAnnotation(MappedSuperclass.class);
      Entity entity = (Entity) superClass.getAnnotation(Entity.class);
      Inheritance inheritance = (Inheritance) superClass.getAnnotation(Inheritance.class);
      if (mappedSuperclass != null || entity != null) {
        putProperties(ai, superClass);
        putMethods(ai, superClass);
        if (entity != null) {
          rootClass = superClass;
        }
        putEntityListeners(ai, superClass);
      }
    }
    if (rootClass != null) {
      ai.setRootClass(rootClass);
      DiscriminatorValue dv = (DiscriminatorValue) c.getAnnotation(DiscriminatorValue.class);
      String discriminatorValue;
      if (dv != null) {
        discriminatorValue = dv.value();
        if (discriminatorValue == null) {
          throw new PersistenceException(
              "You must specify a value= for @DiscriminatorValue on " + c.getName());
        }
      } else {
        discriminatorValue = c.getSimpleName();
      }
      ai.setDiscriminatorValue(discriminatorValue);
      discriminatorMap.put(discriminatorValue, ai);
    } else {
      ai.setRootClass(c);
    }
    putTableDeclaration(ai, c);
    putProperties(ai, c);
    putMethods(ai, c);
    if (ai.getIdMethod() == null) {
      throw new PersistenceException("No ID method specified for: " + c.getName());
    }
    putEntityListeners(ai, c);

    getAnnotationMap().put(c.getName(), ai);
    return ai;
  }
示例#21
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);
     }
   }
 }
 /**
  * Builds a new page stream transform using the given PDF operator processors (represented by
  * their class) to process the given PDF operators (represented by their operator string), and
  * imposing a default of {@link SimpleOperatorProcessor} for all others.
  *
  * @param pdfOperatorString1 A PDF operator string.
  * @param pdfOperatorProcessor1 A PDF operator processor class for <code>pdfOperatorString1</code>
  *     .
  * @param pdfOperatorString2 A PDF operator string.
  * @param pdfOperatorProcessor2 A PDF operator processor class for <code>pdfOperatorString2</code>
  *     .
  * @throws IOException if any processing error occurs.
  * @see #PageStreamTransform(Properties)
  * @see PropUtil#fromArgs(String, String, String, String)
  * @deprecated Use {@link #PageStreamTransform(OperatorProcessorFactory, String, Class, String,
  *     Class)}.
  */
 public PageStreamTransform(
     String pdfOperatorString1,
     Class pdfOperatorProcessor1,
     String pdfOperatorString2,
     Class pdfOperatorProcessor2)
     throws IOException {
   this(
       PropUtil.fromArgs(
           pdfOperatorString1, pdfOperatorProcessor1.getName(),
           pdfOperatorString2, pdfOperatorProcessor2.getName()));
 }
  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);
      }
    }
  }
 /**
  * This strips the cglib class name out of the enhanced classes.
  *
  * @param c
  * @return
  */
 public static Class stripEnhancerClass(Class c) {
   String className = c.getName();
   className = stripEnhancerClass(className);
   if (className.equals(c.getName())) {
     // no change, did this to fix groovy issue
     return c;
   } else {
     c = getClass(className);
   }
   return c;
 }
 /**
  * Get hold of the GrailsDomainClassProperty represented by the targetClass' propertyName,
  * assuming targetClass corresponds to a GrailsDomainClass.
  */
 private static PersistentProperty getGrailsDomainClassProperty(
     AbstractHibernateDatastore datastore, Class<?> targetClass, String propertyName) {
   PersistentEntity grailsClass =
       datastore != null
           ? datastore.getMappingContext().getPersistentEntity(targetClass.getName())
           : null;
   if (grailsClass == null) {
     throw new IllegalArgumentException(
         "Unexpected: class is not a domain class:" + targetClass.getName());
   }
   return grailsClass.getPropertyByName(propertyName);
 }
示例#26
0
 /**
  * If a system property was setup, load the class (if not already registered) and move it in front
  * of any other factory. This is done for compatibility with legacy {@code FactoryFinder}
  * implementation.
  *
  * @param loader The class loader to use.
  * @param category The category to scan for plug-ins.
  * @param message A buffer where to write the logging message.
  * @return {@code true} if at least one factory has been registered.
  */
 private <T> boolean registerFromSystemProperty(
     final ClassLoader loader, final Class<T> category, final StringBuilder message) {
   boolean newServices = false;
   try {
     final String classname = System.getProperty(category.getName());
     if (classname != null)
       try {
         final Class<?> candidate = loader.loadClass(classname);
         if (category.isAssignableFrom(candidate)) {
           final Class<? extends T> factoryClass = candidate.asSubclass(category);
           T factory = getServiceProviderByClass(factoryClass);
           if (factory == null)
             try {
               factory = factoryClass.newInstance();
               if (registerServiceProvider(factory, category)) {
                 message.append(System.getProperty("line.separator", "\n"));
                 message.append("  ");
                 message.append(factoryClass.getName());
                 newServices = true;
               }
             } catch (IllegalAccessException exception) {
               throw new FactoryRegistryException(
                   Errors.format(ErrorKeys.CANT_CREATE_FACTORY_$1, classname), exception);
             } catch (InstantiationException exception) {
               throw new FactoryRegistryException(
                   Errors.format(ErrorKeys.CANT_CREATE_FACTORY_$1, classname), exception);
             }
           /*
            * Put this factory in front of every other factories (including the ones loaded
            * in previous class loaders, which is why we don't inline this ordering in the
            * 'register' loop). Note: if some factories were not yet registered, they will
            * not be properly ordered. Since this code exists more for compatibility reasons
            * than as a commited API, we ignore this short comming for now.
            */
           for (final Iterator<T> it = getServiceProviders(category, false); it.hasNext(); ) {
             final T other = it.next();
             if (other != factory) {
               setOrdering(category, factory, other);
             }
           }
         }
       } catch (ClassNotFoundException exception) {
         // The class has not been found, maybe because we are not using the appropriate
         // class loader. Ignore (do not thrown an exception), in order to give a chance
         // to the caller to invokes this method again with a different class loader.
       }
   } catch (SecurityException exception) {
     // We are not allowed to read property, probably
     // because we are running in an applet. Ignore...
   }
   return newServices;
 }
 public static Class<?> malform(Class<?> type) throws Exception {
   ClassReader classReader = new ClassReader(type.getName());
   ClassWriter classWriter = new ClassWriter(classReader, 0);
   classReader.accept(new SignatureMalformer(classWriter), 0);
   ClassLoader classLoader =
       new ByteArrayClassLoader(
           null,
           Collections.singletonMap(type.getName(), classWriter.toByteArray()),
           null,
           ByteArrayClassLoader.PersistenceHandler.MANIFEST,
           PackageDefinitionStrategy.NoOp.INSTANCE);
   return classLoader.loadClass(type.getName());
 }
示例#28
0
  public static void expectException(Callable<?> callable, Class<?> exception) {
    boolean thrown = false;

    try {
      callable.call();
    } catch (Throwable e) {
      assert e.getClass().equals(exception)
          : e.getClass().getName() + " is not " + exception.getName();
      thrown = true;
    }

    assert thrown : exception.getName() + " not received";
  }
示例#29
0
  @Override
  @SuppressWarnings("unchecked")
  public <T> T fromString(String content, Class<T> classOfT) {
    if (!classOfT.isArray()) {
      if (Collection.class.isAssignableFrom(classOfT)) {
        // Collections are NOT supported for deserialization from CSV
        throw new RuntimeException(
            "Collection types are not supported. Please specify an array[] type.");
      }
      throw new RuntimeException(
          String.format("Array[] types are required. Please specify %s[]", classOfT.getName()));
    }

    Class<?> objectType = classOfT.getComponentType();
    int currentLine = 0;
    try (CSVParser parser = new CSVParser(new StringReader(content), getCSVFormat().withHeader())) {
      Set<String> columns = parser.getHeaderMap().keySet();
      Map<String, Field> fieldMap = getFieldMap(objectType);

      Constructor<?> objectConstructor;
      try {
        objectConstructor = objectType.getConstructor();
      } catch (NoSuchMethodException e) {
        throw new RuntimeException("A default constructor is required for " + objectType.getName());
      }

      List objects = new ArrayList<>();
      for (CSVRecord record : parser) {
        currentLine++;

        Object o = objectConstructor.newInstance();
        for (String column : columns) {
          Field field = fieldMap.get(caseSensitiveFieldNames ? column : column.toLowerCase());
          String value = record.get(column);
          Object object = objectFromString(value, field.getType());
          field.set(o, object);
        }

        objects.add(o);
      }

      Object array = Array.newInstance(objectType, objects.size());
      for (int i = 0; i < objects.size(); i++) {
        Array.set(array, i, objects.get(i));
      }

      return (T) array;
    } catch (Exception e) {
      throw new RuntimeException("Failed to parse CSV near line #" + currentLine, e);
    }
  }
示例#30
0
  private void initServices() throws PwmUnrecoverableException {
    for (final Class<? extends PwmService> serviceClass : PWM_SERVICE_CLASSES) {
      final Date startTime = new Date();
      final PwmService newServiceInstance;
      try {
        final Object newInstance = serviceClass.newInstance();
        newServiceInstance = (PwmService) newInstance;
      } catch (Exception e) {
        final String errorMsg =
            "unexpected error instantiating service class '"
                + serviceClass.getName()
                + "', error: "
                + e.toString();
        LOGGER.fatal(errorMsg, e);
        throw new PwmUnrecoverableException(
            new ErrorInformation(PwmError.ERROR_STARTUP_ERROR, errorMsg));
      }

      try {
        LOGGER.debug("initializing service " + serviceClass.getName());
        newServiceInstance.init(this);
        LOGGER.debug(
            "completed initialization of service "
                + serviceClass.getName()
                + " in "
                + TimeDuration.fromCurrent(startTime).asCompactString()
                + ", status="
                + newServiceInstance.status());
      } catch (PwmException e) {
        LOGGER.warn(
            "error instantiating service class '"
                + serviceClass.getName()
                + "', service will remain unavailable, error: "
                + e.getMessage());
      } catch (Exception e) {
        String errorMsg =
            "unexpected error instantiating service class '"
                + serviceClass.getName()
                + "', cannot load, error: "
                + e.getMessage();
        if (e.getCause() != null) {
          errorMsg += ", cause: " + e.getCause();
        }
        LOGGER.fatal(errorMsg);
        throw new PwmUnrecoverableException(
            new ErrorInformation(PwmError.ERROR_STARTUP_ERROR, errorMsg));
      }
      pwmServices.put(serviceClass, newServiceInstance);
    }
  }