Example #1
1
  /**
   * Convert a method call into a string according to TcpRest protocol that can be transmitted
   * across network.
   *
   * @param clazz Calling class
   * @param method Calling method
   * @param params parameters of calling method
   * @param mappers mapper for each parameter
   * @return
   * @throws MapperNotFoundException
   */
  public String encode(Class clazz, Method method, Object[] params, Map<String, Mapper> mappers)
      throws MapperNotFoundException {
    StringBuilder paramTokenBuffer = new StringBuilder();
    if (params != null) {
      for (Object param : params) {
        if (param == null) param = new NullObj();
        logger.log("***DefaultConverter - encode for class: " + param.getClass());

        Mapper mapper = getMapper(mappers, param.getClass());

        paramTokenBuffer
            .append(encodeParam(mapper.objectToString(param)))
            .append(TcpRestProtocol.PATH_SEPERATOR);

        logger.debug("***DefaultConverter - paramTokenBuffer " + paramTokenBuffer.toString());
      }

      return clazz.getCanonicalName()
          + "/"
          + method.getName()
          + "("
          + paramTokenBuffer.substring(
              0, paramTokenBuffer.length() - TcpRestProtocol.PATH_SEPERATOR.length())
          + ")";
    } else {
      return clazz.getCanonicalName() + "/" + method.getName() + "()";
    }
  }
Example #2
1
  /**
   * Recursively iterate the given package, and attempt to resolve all annotated references for
   * <code>RequestHandler</code> implementations.
   *
   * @param handlerPackage the base package to scan, for example "org.apache.awf".
   * @return a <code>Map&lt;String, RequestHandler&gt;</code> of handlers, which may be empty but
   *     not <code>null</code>.
   */
  public Map<String, RequestHandler> findHandlers(String handlerPackage) {

    if (Strings.isNullOrEmpty(handlerPackage)) {
      logger.warn("No RequestHandler package defined");
      return pathHandlers;
    }

    List<Class<?>> classes = findClasses(handlerPackage);
    for (Class<?> clazz : classes) {
      if (clazz.isAnnotationPresent(Path.class)) {

        RequestHandler handler =
            (RequestHandler) ReflectionTools.createInstance(clazz.getCanonicalName());
        Path path = clazz.getAnnotation(Path.class);
        pathHandlers.put(path.value(), handler);

        logger.info(
            "Added RequestHandler ["
                + clazz.getCanonicalName()
                + "] for Path ["
                + path.value()
                + "]");
      }
    }

    return pathHandlers;
  }
 /**
  * Discover default encodeables. Encodeables are discovered by inspecting all fields from
  * Identifiers class using reflection.
  *
  * @param map encodeable table to fill with builtin encodeables
  */
 @SuppressWarnings("unchecked")
 public static void discoverDefaultEncodeables(Map<NodeId, Class<IEncodeable>> map) {
   // Discover builtin classes
   Class<?> clazz = Identifiers.class;
   ClassLoader cl = clazz.getClassLoader();
   int index = clazz.getCanonicalName().lastIndexOf(".");
   String prefix = clazz.getCanonicalName().substring(0, index);
   for (Field f : clazz.getFields()) {
     f.setAccessible(true);
     try {
       String className = prefix + "." + f.getName();
       Class<IEncodeable> c = (Class<IEncodeable>) cl.loadClass(className);
       if (!IEncodeable.class.isAssignableFrom(c)) continue;
       for (Field cf : c.getFields()) {
         cf.setAccessible(true);
         if (!cf.getType().equals(NodeId.class)) continue;
         NodeId nodeId;
         try {
           nodeId = (NodeId) cf.get(null);
         } catch (IllegalArgumentException e) {
           throw new RuntimeException("Failed to load default identifiers", e);
         } catch (IllegalAccessException e) {
           throw new RuntimeException("Failed to load default identifiers", e);
         }
         if (nodeId == null) throw new RuntimeException("Failed to load default identifiers");
         map.put(nodeId, c);
       }
     } catch (ClassNotFoundException e) {
       continue;
     }
   }
 }
  // Verify that the test method level events for the test methods declared in the specified class
  // run in the same
  // thread for each instance of the test class for the specified suite and test
  public static void verifyEventsForTestMethodsRunInTheSameThread(
      Class<?> testClass, String suiteName, String testName) {

    for (Method method : testClass.getMethods()) {
      if (method.getDeclaringClass().equals(testClass)) {
        Multimap<Object, EventLog> testMethodEventLogs =
            getTestMethodEventLogsForMethod(
                suiteName, testName, testClass.getCanonicalName(), method.getName());

        for (Object instanceKey : testMethodEventLogs.keySet()) {
          long threadId = -1;

          for (EventLog eventLog : testMethodEventLogs.get(instanceKey)) {
            if (threadId == -1) {
              threadId = eventLog.getThreadId();
            } else {
              assertEquals(
                  eventLog.getThreadId(),
                  threadId,
                  "All of the method level events for the test "
                      + "method "
                      + method.getName()
                      + " in the test class "
                      + testClass.getCanonicalName()
                      + " for the test "
                      + suiteName
                      + " should be run in the same thread");
            }
          }
        }
      }
    }
  }
 /**
  * Checks type and its supertypes for {@link ExtraTypes} annotations.
  *
  * @param type the type to examine
  * @param addModelExtraTypes if {@code true} the contents of the {@link #extraTypes} field will be
  *     added to the returned list.
  */
 private List<EntityProxyModel> checkExtraTypes(JClassType type, boolean addModelExtraTypes)
     throws UnableToCompleteException {
   Set<EntityProxyModel> toReturn = new LinkedHashSet<EntityProxyModel>();
   if (addModelExtraTypes && extraTypes != null) {
     toReturn.addAll(extraTypes);
   }
   for (JClassType toExamine : type.getFlattenedSupertypeHierarchy()) {
     ExtraTypes proxyExtraTypes = toExamine.getAnnotation(ExtraTypes.class);
     if (proxyExtraTypes != null) {
       for (Class<? extends BaseProxy> clazz : proxyExtraTypes.value()) {
         JClassType proxy = oracle.findType(clazz.getCanonicalName());
         if (proxy == null) {
           poison(
               "Unknown class %s in @%s",
               clazz.getCanonicalName(), ExtraTypes.class.getSimpleName());
         } else {
           toReturn.add(getEntityProxyType(proxy));
         }
       }
     }
   }
   if (toReturn.isEmpty()) {
     return Collections.emptyList();
   }
   return new ArrayList<EntityProxyModel>(toReturn);
 }
  // Verify that all the test methods declared in the specified class have the same instances of the
  // class associated /
  // with them for the specified suite and test.
  public static void verifySameInstancesOfTestClassAssociatedWithMethods(
      String suiteName, String testName, Class<?> clazz) {

    Set<Object> instanceKeys = null;

    for (String methodName : getDeclaredTestMethods(clazz)) {
      Multimap<Object, EventLog> eventLogMap =
          getTestMethodEventLogsForMethod(
              suiteName, testName, clazz.getCanonicalName(), methodName);

      if (instanceKeys == null) {
        instanceKeys = eventLogMap.keySet();
      } else {
        assertTrue(
            instanceKeys.containsAll(eventLogMap.keySet())
                && eventLogMap.keySet().containsAll(instanceKeys),
            "The same instances of "
                + clazz.getCanonicalName()
                + " should be associated with its methods for the test "
                + testName
                + " in the suite "
                + suiteName);
      }
    }
  }
Example #7
1
 public ClassDefinition(Class<?> cls) {
   this.definedClass = cls;
   this.setClassName(cls.getCanonicalName());
   this.setSuperClass(cls.getSuperclass() != null ? cls.getSuperclass().getCanonicalName() : null);
   String[] interfaces = new String[cls.getInterfaces().length];
   int i = 0;
   for (Class<?> interfaze : cls.getInterfaces()) {
     interfaces[i++] = interfaze.getCanonicalName();
   }
   this.setInterfaces(interfaces);
 }
Example #8
0
  public <T> Class<T> inferValueClassForListOrSet(Type genericType, Class<?> entityClass) {
    log.debug(
        "Infer parameterized value class for collection type {} of entity class {} ",
        genericType.toString(),
        entityClass.getCanonicalName());

    Class<T> valueClass;
    if (genericType instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) genericType;
      Type[] actualTypeArguments = pt.getActualTypeArguments();
      if (actualTypeArguments.length > 0) {
        Type type = actualTypeArguments[actualTypeArguments.length - 1];
        valueClass = getClassFromType(type);
      } else {
        throw new AchillesBeanMappingException(
            "The type '"
                + genericType.getClass().getCanonicalName()
                + "' of the entity '"
                + entityClass.getCanonicalName()
                + "' should be parameterized");
      }
    } else {
      throw new AchillesBeanMappingException(
          "The type '"
              + genericType.getClass().getCanonicalName()
              + "' of the entity '"
              + entityClass.getCanonicalName()
              + "' should be parameterized");
    }

    log.trace("Inferred value class : {}", valueClass.getCanonicalName());

    return valueClass;
  }
Example #9
0
  @Override
  @SuppressWarnings("unchecked")
  public void unregisterEntityTypes() {
    try {
      Field EntityTypes_d = ReflectionUtil.getField(EntityTypes.class, "d");
      Field EntityTypes_f = ReflectionUtil.getField(EntityTypes.class, "f");

      Map<Class, String> d = (Map) EntityTypes_d.get(EntityTypes_d);
      Map<Class, Integer> f = (Map) EntityTypes_f.get(EntityTypes_f);

      Iterator dIterator = d.keySet().iterator();
      while (dIterator.hasNext()) {
        Class clazz = (Class) dIterator.next();
        if (clazz.getCanonicalName().startsWith("de.Keyle.MyPet")) {
          dIterator.remove();
        }
      }

      Iterator fIterator = f.keySet().iterator();
      while (fIterator.hasNext()) {
        Class clazz = (Class) fIterator.next();
        if (clazz.getCanonicalName().startsWith("de.Keyle.MyPet")) {
          fIterator.remove();
        }
      }
    } catch (Exception e) {
      MyPetApi.getLogger().warning("Error while unregistering MyPet entities");
    }
  }
Example #10
0
  private boolean export(Object oSource, String className) {
    m_nNbItemSet = 0;
    if (oSource != null) {
      beginNewLine(m_sbOut);
      m_sbOut.append("{");
      if (m_bSetLines) m_sbOut.append(EndOfLine.CR);
      m_nTabDepth++;

      if (className == null) {
        // Dump current class and it's hierarchy
        Class programClass = oSource.getClass();
        String csClassName = programClass.getCanonicalName();
        while (!csClassName.equals("java.lang.Object")) {
          dumpJSonClass(programClass, oSource); // Dump current class

          programClass = programClass.getSuperclass();
          csClassName = programClass.getCanonicalName();
        }
      } else {
        m_sbOut.append("\"" + className + "\":");
        exportItem(oSource);
      }

      if (m_bSetLines) m_sbOut.append(EndOfLine.CR);
      beginNewLine(m_sbOut);
      m_sbOut.append("}");
      if (m_bSetLines) m_sbOut.append(EndOfLine.CR);
    }
    return true;
  }
 @Override
 public String getId(Class<?> permissionClass) {
   String permission = permissionClass.getCanonicalName();
   int firstFolderIndex = permission.indexOf(".");
   firstFolderIndex++; // remove dot too.
   return permissionClass.getCanonicalName().substring(firstFolderIndex);
 }
 public <T extends DataManipulator<T, I>, I extends ImmutableDataManipulator<I, T>>
     void registerBlockProcessorAndImpl(
         Class<I> manipulatorClass,
         Class<? extends I> implClass,
         BlockDataProcessor<I> processor) {
   checkState(allowRegistrations, "Registrations are no longer allowed!");
   checkState(
       !this.blockDataMap.containsKey(checkNotNull(manipulatorClass)),
       "Already registered a DataProcessor for the given "
           + "ImmutableDataManipulator: "
           + manipulatorClass.getCanonicalName());
   checkState(
       !this.blockDataMap.containsKey(checkNotNull(implClass)),
       "Already registered a DataProcessor for the given "
           + "DataManipulator: "
           + implClass.getCanonicalName());
   List<BlockDataProcessor<?>> processorList = this.blockDataMap.get(manipulatorClass);
   if (processorList == null) {
     processorList = Collections.synchronizedList(Lists.<BlockDataProcessor<?>>newArrayList());
     this.blockDataMap.put(manipulatorClass, processorList);
     this.blockDataMap.put(implClass, processorList);
   }
   checkArgument(!processorList.contains(processor), "Duplicate DataProcessor Registration!");
   processorList.add(processor);
 }
  /**
   * Adds the class to the circuit pool, allowing players to create circuits of this class.
   *
   * @param c The class to add. must extend org.tal.redstonechips.Circuit.
   */
  public void addCircuitClass(Class c) {
    String name = c.getSimpleName();

    if (name.length() > maxClassNameLength) {
      rc.log(
          Level.WARNING,
          "While trying to add "
              + c.getCanonicalName()
              + " to circuit pool: Class name is longer than "
              + maxClassNameLength
              + " characters.");
    } else if (circuitClasses.containsKey(name)) {
      rc.log(
          Level.WARNING,
          "While trying to add "
              + c.getCanonicalName()
              + " to circuit pool: Another circuit class named "
              + name
              + " was found. ");
    } else if (!Circuit.class.isAssignableFrom(c)) {
      rc.log(
          Level.WARNING,
          "While trying to add "
              + c.getCanonicalName()
              + ": Class does not extend org.tal.redstonechips.circuits.Circuit");
    } else {
      circuitClasses.put(name, c);
    }
  }
  public void addToCache(
      Class<? extends Plugin> plugin,
      final RemoteManagerEndpoint manager,
      final DiscoveredPlugin src) {
    synchronized (this.cache) {
      // 1) get all managers providing this plugin
      HashMap<RemoteManagerEndpoint, Entry> managers = this.cache.get(plugin);
      if (null == managers) { // if we dont have one, so create
        managers = new HashMap<RemoteManagerEndpoint, Entry>();
        managers.put(manager, new Entry(plugin.getCanonicalName(), manager, src));

        this.cache.put(plugin, managers);

        return;
      }

      // 2) get the entry providing this plugin.
      Entry entry = managers.get(manager);
      if (null == entry) { // no entry
        managers.put(manager, new Entry(plugin.getCanonicalName(), manager, src));
        return;
      }

      // 3) here it means we have already an entry... so skip!!!
    }
  }
Example #15
0
  /**
   * Finds the reflected class for the class under test.
   *
   * @return the reflected class, or null if not found.
   */
  @SuppressWarnings("unchecked")
  private Class<?> findMatchingClass() {
    // even if there are no . in the string, split will return an
    // array of length 1
    String[] classNameParts = mShortClassName.split("\\.");
    String currentName = mPackageName + "." + classNameParts[0];

    try {
      // Check to see if the class we're looking for is the top
      // level class.
      Class<?> clz = Class.forName(currentName, false, this.getClass().getClassLoader());
      if (clz.getCanonicalName().equals(mAbsoluteClassName)) {
        return clz;
      }

      // Then it must be an inner class.
      for (int x = 1; x < classNameParts.length; x++) {
        clz = findInnerClassByName(clz, classNameParts[x]);
        if (clz == null) {
          return null;
        }
        if (clz.getCanonicalName().equals(mAbsoluteClassName)) {
          return clz;
        }
      }
    } catch (ClassNotFoundException e) {
      SignatureTestLog.e("ClassNotFoundException for " + mPackageName + "." + mShortClassName, e);
      return null;
    }
    return null;
  }
Example #16
0
  public Mapper getMapper(Map<String, Mapper> mappers, Class targetClazz)
      throws MapperNotFoundException {
    Mapper mapper = mappers.get(targetClazz.getCanonicalName());

    if (mapper == null) {
      // now we try to find if the target param is serizialiable, if so we could use
      // RawTypeMapper
      //                    java.io.Serializable
      for (Class clazz : targetClazz.getInterfaces()) {
        if (clazz.equals(java.io.Serializable.class) || clazz.isArray()) {
          mapper = new RawTypeMapper();
          break;
        }
      }

      if (mapper == null)
        throw new MapperNotFoundException(
            "***DefaultConverter - cannot find mapper for: " + targetClazz.getCanonicalName());
    }

    logger.debug(
        "found mapper: "
            + mapper.getClass().getCanonicalName()
            + " for: "
            + targetClazz.getCanonicalName());
    return mapper;
  }
 /**
  * Overwrite this method if you want to filter the input, apply hashing, etc.
  *
  * @param feature the current feature.
  * @param document the current document.
  * @param featureFieldName the field hashFunctionsFileName of the feature.
  */
 protected void addToDocument(LireFeature feature, Document document, String featureFieldName) {
   if (run == 0) {
   } // just count documents
   else if (run == 1) { // Select the representatives ...
     if (representativesID.contains(docCount)
         && feature
             .getClass()
             .getCanonicalName()
             .equals(featureClass.getCanonicalName())) { // it's a representative.
       // put it into a temporary data structure ...
       representatives.add(feature);
     }
   } else if (run
       == 2) { // actual hashing: find the nearest representatives and put those as a hash into a
     // document.
     if (feature
         .getClass()
         .getCanonicalName()
         .equals(featureClass.getCanonicalName())) { // it's a feature to be hashed
       int[] hashes = getHashes(feature);
       document.add(
           new TextField(
               featureFieldName + "_hash",
               createDocumentString(hashes, hashes.length),
               Field.Store.YES));
       document.add(
           new TextField(
               featureFieldName + "_hash_q", createDocumentString(hashes, 10), Field.Store.YES));
     }
     document.add(new StoredField(featureFieldName, feature.getByteArrayRepresentation()));
   }
 }
Example #18
0
  @SuppressWarnings("unchecked")
  public void registerEntityType(
      MyPetType type, Class<? extends MyPetMinecraftEntity> entityClass) {
    try {
      Field EntityTypes_d = ReflectionUtil.getField(EntityTypes.class, "d");
      Field EntityTypes_f = ReflectionUtil.getField(EntityTypes.class, "f");

      Map<Class, String> d = (Map) EntityTypes_d.get(EntityTypes_d);
      Map<Class, Integer> f = (Map) EntityTypes_f.get(EntityTypes_f);

      Iterator cIterator = d.keySet().iterator();
      while (cIterator.hasNext()) {
        Class clazz = (Class) cIterator.next();
        if (clazz.getCanonicalName().equals(entityClass.getCanonicalName())) {
          cIterator.remove();
        }
      }

      Iterator eIterator = f.keySet().iterator();
      while (eIterator.hasNext()) {
        Class clazz = (Class) eIterator.next();
        if (clazz.getCanonicalName().equals(entityClass.getCanonicalName())) {
          eIterator.remove();
        }
      }

      d.put(entityClass, type.getMinecraftName());
      f.put(entityClass, type.getTypeID());

    } catch (Exception e) {
      MyPetApi.getLogger().warning("Error while registering " + entityClass.getCanonicalName());
    }
  }
Example #19
0
  public <T> T load(PersistenceContext context, Class<T> entityClass) {
    log.debug("Loading entity of class {} using PersistenceContext {}", entityClass, context);
    EntityMeta entityMeta = context.getEntityMeta();
    Object primaryKey = context.getPrimaryKey();

    Validator.validateNotNull(entityClass, "Entity class should not be null");
    Validator.validateNotNull(
        primaryKey, "Entity '%s' key should not be null", entityClass.getCanonicalName());
    Validator.validateNotNull(
        entityMeta, "Entity meta for '%s' should not be null", entityClass.getCanonicalName());

    T entity = null;

    if (entityMeta.isClusteredCounter()) {
      entity = counterLoader.loadClusteredCounters(context);
    } else {
      Row row = context.loadEntity();
      if (row != null) {
        entity = entityMeta.instanciate();
        mapper.setNonCounterPropertiesToEntity(row, entityMeta, entity);
      }
    }

    return entity;
  }
Example #20
0
 public MethodBuffer setReturnType(final Class<?> cls) {
   final String pkgName = cls.getPackage().getName();
   if (pkgName.length() == 0) {
     returnType = new TypeData("", cls.getCanonicalName());
   } else {
     returnType = new TypeData(pkgName, cls.getCanonicalName().replace(pkgName + ".", ""));
   }
   return this;
 }
Example #21
0
  @Test(groups = "unit", timeOut = 1000)
  public void test() throws ClassNotFoundException {
    final Collection<Class<?>> descriptionClasses = Lists.newArrayList();
    final URL url =
        AnnotationTests.class.getClassLoader().getResource("META-INF/jobs/persistence.xml");
    final String jpaConfigContents = InputContexts.toString(InputContexts.forUrl(url));
    final List<Class<? extends ActivityDescription>> activityDescriptionsMapped =
        Lists.newArrayList();
    for (final Class<? extends ActivityFactory<?>> factoryClass : FACTORIES) {
      // Make sure the class is make as a ManageBean to DI context picks it up.
      assert factoryClass.getAnnotation(ManagedBean.class) != null
          : "Factory class " + factoryClass + " is not annotated with @ManagedBean";

      // assert factoryClass.getDeclaredConstructors().length == 1;
      boolean foundInjectedConstructor = false;
      for (Constructor<?> constructor : factoryClass.getDeclaredConstructors()) {
        if (constructor.getParameterTypes().length == 0
            || constructor.getAnnotation(Inject.class) != null) {
          foundInjectedConstructor = true;
        }
      }
      assert foundInjectedConstructor;

      final ActivityFactoryFor factoryAnnotation =
          factoryClass.getAnnotation(ActivityFactoryFor.class);
      // Make sure this class specifies which ActivityDescription it acts an ActivityFactory for.
      assert factoryAnnotation != null;
      final Class<? extends ActivityDescription> descriptionClass = factoryAnnotation.value();
      activityDescriptionsMapped.add(descriptionClass);
      assert ActivityDescription.class.isAssignableFrom(descriptionClass);
      // Make sure there are not multiple descriptions per factory
      assert !descriptionClasses.contains(descriptionClass);

      // Make sure the description can be persisted
      assert descriptionClass.getAnnotation(Entity.class) != null
          : descriptionClass + " is not annotated with entity.";
      assert jpaConfigContents.contains(descriptionClass.getCanonicalName())
          : "Class " + descriptionClass.getCanonicalName() + " not found in JPA configuration.";
    }

    final Pattern pattern = Pattern.compile("\\<class\\>.*\\<");
    final Matcher matcher = pattern.matcher(jpaConfigContents);
    int start = 0;
    while (matcher.find(start)) {
      final int startIdx = matcher.start() + "<class>".length();
      final int endIdx = jpaConfigContents.indexOf("<", startIdx);
      final String classStr = jpaConfigContents.substring(startIdx, endIdx);
      final Class<?> clazz = Class.forName(classStr);
      if (ActivityDescription.class.isAssignableFrom(clazz)) {
        if (!Modifier.isAbstract(clazz.getModifiers())) {
          assert activityDescriptionsMapped.contains(clazz)
              : "No activity factory found for description class " + clazz;
        }
      }
      start = endIdx;
    }
  }
Example #22
0
 /**
  * Checks the component type of the given array against the expected component type.
  *
  * @param array the array to be checked. May not be <code>null</code>.
  * @param expectedComponentType the expected component type of the array. May not be <code>null
  *     </code>.
  * @return the unchanged array.
  * @throws ArrayStoreException if the expected runtime {@code componentType} does not match the
  *     actual runtime component type.
  */
 private static Object checkComponentType(Object array, Class<?> expectedComponentType) {
   Class<?> actualComponentType = array.getClass().getComponentType();
   if (!expectedComponentType.isAssignableFrom(actualComponentType)) {
     throw new ArrayStoreException(
         String.format(
             "The expected component type %s is not assignable from the actual type %s",
             expectedComponentType.getCanonicalName(), actualComponentType.getCanonicalName()));
   }
   return array;
 }
Example #23
0
 /**
  * Find a constructor in the class for the argument types. This method converts any checked
  * exception in unchecked exception.
  *
  * @param cls the class whos constructor will be found.
  * @param types the types of the parameters of the constructor.
  * @return the constructor of the given class which has the given parameter types.
  */
 public static Constructor safeGetConstructor(Class cls, Class[] types) {
   try {
     return cls.getDeclaredConstructor(types);
   } catch (Exception ex) {
     logger.error(
         "Error while trying to find constructor for class " + cls.getCanonicalName(), ex);
     throw new RuntimeException(
         "Error while trying to find constructor for class " + cls.getCanonicalName(), ex);
   }
 }
 private void processRegularClass(BeanDefinitionRegistry registry, Class implementation) {
   LOG.debug(
       String.format(
           "Registering bean definition for implementation class %s",
           implementation.getCanonicalName()));
   String beanName = implementation.getCanonicalName();
   GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
   beanDefinition.setBeanClass(implementation);
   beanDefinition.setAutowireMode(AUTOWIRE_BY_TYPE);
   registry.registerBeanDefinition(beanName, beanDefinition);
 }
Example #25
0
 /**
  * Helper method to determine if this object implements CharSequence
  *
  * @param aClass Class to check for CharSequence-esqueness
  * @return True if the given class implements CharSequence, false otherwise.
  */
 public static boolean isCharSequence(Class aClass) {
   if (aClass.getCanonicalName().equals("java.lang.CharSequence")) {
     return true;
   }
   Class[] interfaces = aClass.getInterfaces();
   for (Class c : interfaces) {
     if (c.getCanonicalName().equals("java.lang.CharSequence")) {
       return true;
     }
   }
   return false;
 }
 /**
  * Find all the Java classes that have proper @ClientDtoFactoryVisitor annotation.
  *
  * @throws java.io.IOException
  */
 @SuppressWarnings("unchecked")
 private static void findDtoFactoryVisitors() throws IOException {
   Reflections reflection = new Reflections(getConfigurationBuilder());
   Set<Class<?>> classes = reflection.getTypesAnnotatedWith(ClientDtoFactoryVisitor.class);
   int i = 0;
   for (Class clazz : classes) {
     dtoFactoryVisitors.put(clazz.getCanonicalName(), "provider_" + i++);
     System.out.println(
         String.format("New DtoFactoryVisitor found: %s", clazz.getCanonicalName()));
   }
   System.out.println(String.format("Found: %d DtoFactoryVisitor(s)", dtoFactoryVisitors.size()));
 }
  /**
   * Creates a support map that maintain for each method name (name as key) a list of Methods found
   * in the Class.
   */
  @SuppressWarnings("deprecation")
  private Map<String, List<Method>> buildAnnotatedMethodsCache(Class<?> clazz) {
    ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
    IProject currProj = JDTUtils.getCurrentProjectForOpenEditor();
    String classCanonicalName = clazz.getCanonicalName();
    if (currProj != null
        && !classCanonicalName.startsWith("net.sf.jasperreports.functions.standard")) {
      // Try to reload a fresh new instance of the Class instance.
      // Useful for code being developed directly inside JSS.
      // We skip the standard ones contributed via jar.
      OutputFolderClassLoader reloaderCL =
          new OutputFolderClassLoader(JavaCore.create(currProj), ctxClassLoader);
      Class<?> reloadedClazz = reloaderCL.reloadClass(clazz.getCanonicalName());
      if (reloadedClazz != null) {
        clazz = reloadedClazz;
      }
    }

    Map<String, List<Method>> methodsByNameMap = new HashMap<String, List<Method>>();

    // First round locate all methods with the JRFunction annotation
    // in order to have a list of what will be the functions
    for (Method m : clazz.getMethods()) {
      JRExprFunction jrFunctionAnn = m.getAnnotation(JRExprFunction.class);
      Function jrNewFunctionAnn = m.getAnnotation(Function.class);
      if (jrNewFunctionAnn != null || jrFunctionAnn != null) {
        String methodName = m.getName();
        List<Method> methods = methodsByNameMap.get(methodName);
        if (methods == null) {
          methods = new ArrayList<Method>();
        }
        methods.add(m);
        methodsByNameMap.put(methodName, methods);
      }
    }

    // After that enrich the map with the remaining methods that have the same function
    // name but a different list of parameters
    for (Method m : clazz.getMethods()) {
      JRExprFunction jrFunctionAnn = m.getAnnotation(JRExprFunction.class);
      Function jrNewFunctionAnn = m.getAnnotation(Function.class);
      if (jrNewFunctionAnn == null || jrFunctionAnn == null) {
        String methodName = m.getName();
        List<Method> methods = methodsByNameMap.get(methodName);
        if (methods != null) {
          methods.add(m);
        }
      }
    }

    return methodsByNameMap;
  }
Example #28
0
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName(args[0]);
      out.format("Class:%n  %s%n%n", c.getCanonicalName());
      out.format("Modifiers:%n  %s%n%n", Modifier.toString(c.getModifiers()));

      out.format("Type Parameters:%n");
      TypeVariable<?>[] tv = c.getTypeParameters();
      if (tv.length != 0) {
        out.format("  ");
        for (TypeVariable<?> t : tv) out.format("%s ", t.getName());
        out.format("%n%n");
      } else {
        out.format("  -- No Type Parameters --%n%n");
      }

      out.format("Implemented Interfaces:%n");
      Type[] intfs = c.getGenericInterfaces();
      if (intfs.length != 0) {
        for (Type intf : intfs) out.format("  %s%n", intf.toString());
        out.format("%n");
      } else {
        out.format("  -- No Implemented Interfaces --%n%n");
      }

      out.format("Inheritance Path:%n");
      List<Class<?>> l = new ArrayList<Class<?>>();
      printAncestor(c, l);
      if (l.size() != 0) {
        for (Class<?> cl : l) out.format("  %s%n", cl.getCanonicalName());
        out.format("%n");
      } else {
        out.format("  -- No Super Classes --%n%n");
      }

      out.format("Annotations:%n");
      Annotation[] ann = c.getAnnotations();
      if (ann.length != 0) {
        for (Annotation a : ann) out.format("  %s%n", a.toString());
        out.format("%n");
      } else {
        out.format("  -- No Annotations --%n%n");
      }

      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
  public static boolean validClass(Class<?> clazz) {
    try {
      Method serialize = clazz.getDeclaredMethod("serialize");
      if (!serialize.getReturnType().equals(String.class)) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not serializable because it does not return a String");
        return false;
      }
      if (!Modifier.isPublic(serialize.getModifiers())) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not serializable because the method 'serialize' is not public");
        return false;
      }
      if (!Modifier.isStatic(serialize.getModifiers())) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not serializable because the method 'serialize' is static");
        return false;
      }

      Method deserialize = clazz.getDeclaredMethod("deserialize", String.class);
      if (!deserialize.getReturnType().equals(clazz)) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not deserializable because the method 'deserialize' does not return the class '"
                + clazz.getCanonicalName()
                + "'");
        return false;
      }

      if (!Modifier.isStatic(deserialize.getModifiers())) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not deserializable because the method 'deserialize' is not static");
        return false;
      }
      if (!Modifier.isPublic(deserialize.getModifiers())) {
        System.out.println(
            "Class '"
                + clazz.getCanonicalName()
                + "' is not deserializable because the method 'deserialize' is not public");
        return false;
      }
    } catch (NoSuchMethodException e) {
      System.out.println(
          "Class '"
              + clazz.getCanonicalName()
              + "' is not deserializable because the method 'deserialize' is does not have either the serialize and/or deserialize method(s)");
      return false;
    }
    return true;
  }
Example #30
0
 private Map<String, Object> getStagesMap(DatabaseFile df) {
   Map<String, Object> map = new HashMap<String, Object>();
   try {
     for (Class<?> c : pipelineScanner.getStageClasses(new File(TMP_DIR), df)) {
       try {
         map.put(c.getCanonicalName(), new StageInformation(c));
       } catch (NoSuchElementException e) {
         logger.error("Unable to get stage information for class " + c.getCanonicalName(), e);
       }
     }
   } catch (IOException e) {
     logger.error("Unable to get stage classes", e);
   }
   return map;
 }