Example #1
1
  @SuppressWarnings("unchecked")
  static void annotatedWith(Set<Class<?>> contracts, Object obj, Class annotation) {
    if (null != obj) {
      Class<?> clazz = obj.getClass();

      while (Object.class != clazz) {
        if (!clazz.isAnonymousClass()) {
          Object t = clazz.getAnnotation(annotation);
          if (null != t) {
            contracts.add(clazz);
          } else {
            annotatedWith(contracts, annotation, clazz);
          }

          for (Class<?> iface : clazz.getInterfaces()) {
            t = iface.getAnnotation(annotation);
            if (null != t) {
              contracts.add(iface);
            } else {
              annotatedWith(contracts, annotation, iface);
            }
          }
        }

        clazz = clazz.getSuperclass();
      }
    }
  }
 private void addControllerServlet(Class<?> klass)
     throws InstantiationException, IllegalAccessException {
   assert klass != null;
   ControllerServlet servlet = null;
   Controller controller;
   if (Controller.class.isAssignableFrom(klass)) {
     controller = controllerFactory.createController(klass.asSubclass(Controller.class));
   } else {
     SimpleControllerWrapper.checkValidSimpleControllerClass(klass);
     SimpleControllerWrapper simpleController =
         SimpleControllerWrapper.createInstance(controllerFactory.createController(klass));
     configure(simpleController);
     controller = simpleController;
   }
   URL url = klass.getAnnotation(URL.class);
   servlet = new ControllerServlet(controller);
   AllowedHttpMethods httpMethods = klass.getAnnotation(AllowedHttpMethods.class);
   if (httpMethods != null) {
     servlet.setValidHttpMethods(httpMethods.value());
   }
   ControllerServlet.AfterControllerAction action = null;
   if (klass.isAnnotationPresent(ForwardTo.class)) {
     action = new ControllerServlet.ForwardAction(klass.getAnnotation(ForwardTo.class).value());
   } else if (klass.isAnnotationPresent(RedirectTo.class)) {
     action = new ControllerServlet.ForwardAction(klass.getAnnotation(RedirectTo.class).value());
   }
   servlet.setAfterControllerAction(action);
   ServletRegistration.Dynamic dynamic = context.addServlet(klass.getSimpleName(), servlet);
   dynamic.addMapping(url.value());
 }
Example #3
0
 /** 获取表名 */
 public static <T> String getTableName(Class<T> clazz) {
   if (clazz.getAnnotation(Entity.class) != null && clazz.getAnnotation(Table.class) != null) {
     return clazz.getAnnotation(Table.class).name();
   } else {
     return clazz.getSimpleName().toLowerCase();
   }
 }
  @Override
  public void beforeTestMethod(TestContext testContext) throws Exception {

    checkInitialized();

    Method testMethod = getTestMethod(testContext);

    Expectations expectations = testMethod.getAnnotation(Expectations.class);
    Expectation expectation = testMethod.getAnnotation(Expectation.class);
    NoQueriesAllowed notAllowedQueries = testMethod.getAnnotation(NoQueriesAllowed.class);

    // If no annotations present, check the test class and its superclasses
    for (Class<?> testClass = testMethod.getDeclaringClass();
        null == expectations
            && null == expectation
            && null == notAllowedQueries
            && !Object.class.equals(testClass);
        testClass = testClass.getSuperclass()) {
      expectations = testClass.getAnnotation(Expectations.class);
      expectation = testClass.getAnnotation(Expectation.class);
      notAllowedQueries = testClass.getAnnotation(NoQueriesAllowed.class);
    }

    if (null != expectation && null != notAllowedQueries) {
      throw new IllegalArgumentException(
          "Cannot specify @Expectation and @NotAllowedQueries on one test method");
    } else if (null != expectations && null != notAllowedQueries) {
      throw new IllegalArgumentException(
          "Cannot specify @Expectations and @NotAllowedQueries on one test method");
    } else if (null != expectations || null != expectation) {

      List<Expectation> expectationList = new ArrayList<Expectation>();

      if (null != expectation) {
        expectationList.add(expectation);
      }

      if (null != expectations) {
        expectationList.addAll(Arrays.asList(expectations.value()));
      }

      for (Expectation expectation1 : expectationList) {
        if (expectation1.value() != -1) {
          if (expectation1.atMost() != -1 || expectation1.atLeast() != -1) {
            throw new IllegalArgumentException(
                "Cannot specify value parameter together with atLeast or atMost parameters");
          }
        }
      }

      setAttribute(testContext, SPY_ATTRIBUTE_NAME, Sniffer.expect(expectationList));

    } else if (null != notAllowedQueries) {
      setAttribute(
          testContext,
          SPY_ATTRIBUTE_NAME,
          Sniffer.expect(
              Collections.singletonList(NoQueriesAllowed.class.getAnnotation(Expectation.class))));
    }
  }
  /**
   * Creates results from @Results and @Result annotations
   *
   * @param actionClass class to check for annotations
   * @param packageConfig packageConfig where the action will be located
   * @param defaultResultPath default result path
   * @param results map of results
   * @param resultsByExtension map of result types keyed by extension
   */
  protected void createResultsFromAnnotations(
      Class<?> actionClass,
      PackageConfig packageConfig,
      String defaultResultPath,
      Map<String, ResultConfig> results,
      Map<String, ResultTypeConfig> resultsByExtension) {
    Results resultsAnn = actionClass.getAnnotation(Results.class);
    if (resultsAnn != null) {
      createFromAnnotations(
          results,
          defaultResultPath,
          packageConfig,
          resultsAnn.value(),
          actionClass,
          resultsByExtension);
    }

    Result resultAnn = actionClass.getAnnotation(Result.class);
    if (resultAnn != null) {
      createFromAnnotations(
          results,
          defaultResultPath,
          packageConfig,
          new Result[] {resultAnn},
          actionClass,
          resultsByExtension);
    }
  }
Example #6
0
	/**
	 * Create a new HandlerMethodResolver for the specified handler type.
	 * @param handlerType the handler class to introspect
	 */
	public HandlerMethodResolver(final Class<?> handlerType,final String baseurls[]) {
		this.typeLevelMapping = handlerType.getAnnotation(HandlerMapping.class);
		Method[] methods = handlerType.getMethods();
		for(Method method:methods)
		{
				
				if (HandlerUtils.isHandlerMethod(handlerType,method)) {
					//System.out.println(method);
					handlerMethods.add(new MethodInfo(ClassUtils.getMostSpecificMethod(method, handlerType),baseurls));
				}
//				else if (method.isAnnotationPresent(InitBinder.class)) {
//					initBinderMethods.add(ClassUtils.getMostSpecificMethod(method, handlerType));
//				}
				else if (method.isAnnotationPresent(ModelAttribute.class)) {
					modelAttributeMethods.add(ClassUtils.getMostSpecificMethod(method, handlerType));
				}
			}
		
		SessionAttributes sessionAttributes = handlerType.getAnnotation(SessionAttributes.class);
		this.sessionAttributesFound = (sessionAttributes != null);
		if (this.sessionAttributesFound) {
			this.sessionAttributeNames.addAll(Arrays.asList(sessionAttributes.value()));
			this.sessionAttributeTypes.addAll(Arrays.asList(sessionAttributes.types()));
		}
	}
  private void injectTestResult(final ITestResult testResult) throws ReflectiveOperationException {

    final Object testInstance = testResult.getInstance();
    if (testInstance == null) {
      return;
    }

    final Class<?> testClass = testInstance.getClass();
    if (TESTS.containsKey(testClass)) {
      return;
    }

    final Dagger dagger = testClass.getAnnotation(Dagger.class);
    if (dagger == null) {
      return;
    }

    final Class<?>[] moduleClasses = dagger.modules();
    final Object[] moduleInstances = new Object[moduleClasses.length];
    for (int i = 0; i < moduleClasses.length; i++) {
      final Class<?> moduleClass = moduleClasses[i];
      if (moduleClass.getAnnotation(Module.class) == null) {
        continue;
      }
      moduleInstances[i] = MODULES.get(moduleClass);
      if (moduleInstances[i] == null) {
        moduleInstances[i] = moduleClass.newInstance();
        MODULES.put(moduleClass, moduleInstances[i]);
      }
    }

    ObjectGraph.create(moduleInstances).inject(testInstance);

    TESTS.put(testClass, testInstance);
  }
  protected static String getSegmentTag(Field field, boolean inner) {
    Class<?> clz = field.getType();

    if (Collection.class.isAssignableFrom(clz)) {
      clz = getCollectionType(field);
    }

    if (clz.isAnnotationPresent(EDISegment.class)) {
      EDISegment es = clz.getAnnotation(EDISegment.class);
      return es.tag();
    } else if (clz.isAnnotationPresent(EDISegmentGroup.class)) {
      EDISegmentGroup esg = clz.getAnnotation(EDISegmentGroup.class);

      String ediSegmentGroupTag = esg.header();

      if (!inner && StringUtils.isNotBlank(ediSegmentGroupTag)) {
        return ediSegmentGroupTag;
      } else {
        // get the segement group's first field, and recurse.
        if (clz.getDeclaredFields().length > 0) {
          return getSegmentTag(clz.getDeclaredFields()[0], false);
        }
      }
    }

    return null;
  }
Example #9
0
  /**
   * Retrieve or create a persisted class, using the annotations built into the class.
   *
   * @param persistClass The annotated Class to persist
   * @return The persisted class definition, or null if failure
   */
  public PersistedClass getPersistedClass(Class<? extends Object> persistClass) {
    /*
     * Look for Class annotations
     */

    // TODO: Lookup from schema/name map ... hm... uh, how to do this without the annotation?
    // I guess pass in one, and then other persisted classes can request data from their own
    // schema...
    PersistedClass persistedClass = persistedClassMap.get(persistClass);
    if (persistedClass == null) {
      PersistClass entityAnnotation = persistClass.getAnnotation(PersistClass.class);
      Migrate migrationAnnotation = persistClass.getAnnotation(Migrate.class);

      if (entityAnnotation == null) {
        log.warning(
            "Persistence: class "
                + persistClass.getName()
                + " does not have the @PersistClass annotation.");
        return null;
      }

      persistedClass = getPersistedClass(persistClass, new EntityInfo(entityAnnotation));

      if (migrationAnnotation != null) {
        persistedClass.setMigrationInfo(new MigrationInfo(persistedClass, migrationAnnotation));
      }
    }

    return persistedClass;
  }
  @Override
  public ConfigProgram introspectType(AnnotatedType<?> type) {
    for (Class<?> parentClass = type.getJavaClass().getSuperclass();
        parentClass != null;
        parentClass = parentClass.getSuperclass()) {
      Resources resources = parentClass.getAnnotation(Resources.class);

      if (resources != null) {
        for (Resource resource : resources.value()) {
          introspectClass(getClass().getName(), resource);
        }
      }

      Resource resource = parentClass.getAnnotation(Resource.class);

      if (resource != null) introspectClass(getClass().getName(), resource);
    }

    Resources resources = type.getAnnotation(Resources.class);

    if (resources != null) {
      for (Resource resource : resources.value()) {
        introspectClass(getClass().getName(), resource);
      }
    }

    Resource resource = type.getAnnotation(Resource.class);

    if (resource != null) introspectClass(getClass().getName(), resource);

    return new NullProgram();
  }
  /**
   * Checks for PrettyFaces mapping annotations on a single class
   *
   * @param clazz Class to scan
   * @return The IDs of the mappings found on the class
   */
  public String[] processClassMappingAnnotations(final Class clazz) {

    // list of all mapping IDs found on the class
    List<String> classMappingIds = new ArrayList<String>();

    // get reference to @URLMapping annotation
    URLMapping mappingAnnotation = (URLMapping) clazz.getAnnotation(URLMapping.class);

    // process annotation if it exists
    if (mappingAnnotation != null) {
      String mappingId = processPrettyMappingAnnotation(clazz, mappingAnnotation);
      classMappingIds.add(mappingId);
    }

    // container annotation
    URLMappings mappingsAnnotation = (URLMappings) clazz.getAnnotation(URLMappings.class);

    if (mappingsAnnotation != null) {

      // process all contained @URLMapping annotations
      for (URLMapping child : mappingsAnnotation.mappings()) {
        String mappingId = processPrettyMappingAnnotation(clazz, child);
        classMappingIds.add(mappingId);
      }
    }

    // return list of mappings found
    return classMappingIds.toArray(new String[classMappingIds.size()]);
  }
 private void addSingleton(Object instance) {
   Class clazz = instance.getClass();
   if (clazz.getAnnotation(Provider.class) != null) {
     // singleton provider
     if (instance instanceof ContextResolver) {
       providers.addContextResolver((ContextResolver) instance);
     }
     if (instance instanceof ExceptionMapper) {
       providers.addExceptionMapper((ExceptionMapper) instance);
     }
     if (instance instanceof MessageBodyReader) {
       providers.addMessageBodyReader((MessageBodyReader) instance);
     }
     if (instance instanceof MessageBodyWriter) {
       providers.addMessageBodyWriter((MessageBodyWriter) instance);
     }
   } else if (clazz.getAnnotation(Filter.class) != null) {
     // singleton filter
     if (instance instanceof MethodInvokerFilter) {
       providers.addMethodInvokerFilter((MethodInvokerFilter) instance);
     }
     if (instance instanceof RequestFilter) {
       providers.addRequestFilter((RequestFilter) instance);
     }
     if (instance instanceof ResponseFilter) {
       providers.addResponseFilter((ResponseFilter) instance);
     }
   } else if (clazz.getAnnotation(Path.class) != null) {
     // singleton resource
     resources.addResource(instance, null);
   }
 }
 @SuppressWarnings({"unchecked"})
 private void addFactory(ObjectFactory factory) {
   Class clazz = factory.getObjectModel().getObjectClass();
   if (clazz.getAnnotation(Provider.class) != null) {
     // per-request provider
     if (ContextResolver.class.isAssignableFrom(clazz)) {
       providers.addContextResolver(factory);
     }
     if (ExceptionMapper.class.isAssignableFrom(clazz)) {
       providers.addExceptionMapper(factory);
     }
     if (MessageBodyReader.class.isAssignableFrom(clazz)) {
       providers.addMessageBodyReader(factory);
     }
     if (MessageBodyWriter.class.isAssignableFrom(clazz)) {
       providers.addMessageBodyWriter(factory);
     }
   } else if (clazz.getAnnotation(Filter.class) != null) {
     // per-request filter
     if (MethodInvokerFilter.class.isAssignableFrom(clazz)) {
       providers.addMethodInvokerFilter(factory);
     }
     if (RequestFilter.class.isAssignableFrom(clazz)) {
       providers.addRequestFilter(factory);
     }
     if (ResponseFilter.class.isAssignableFrom(clazz)) {
       providers.addResponseFilter(factory);
     }
   } else if (clazz.getAnnotation(Path.class) != null) {
     // per-request resource
     resources.addResource(factory);
   }
 }
 @SuppressWarnings({"unchecked"})
 private void addPerRequest(Class clazz) {
   if (clazz.getAnnotation(Provider.class) != null) {
     // per-request provider
     if (ContextResolver.class.isAssignableFrom(clazz)) {
       providers.addContextResolver(clazz);
     }
     if (ExceptionMapper.class.isAssignableFrom(clazz)) {
       providers.addExceptionMapper(clazz);
     }
     if (MessageBodyReader.class.isAssignableFrom(clazz)) {
       providers.addMessageBodyReader(clazz);
     }
     if (MessageBodyWriter.class.isAssignableFrom(clazz)) {
       providers.addMessageBodyWriter(clazz);
     }
   } else if (clazz.getAnnotation(Filter.class) != null) {
     // per-request filter
     if (MethodInvokerFilter.class.isAssignableFrom(clazz)) {
       providers.addMethodInvokerFilter(clazz);
     }
     if (RequestFilter.class.isAssignableFrom(clazz)) {
       providers.addRequestFilter(clazz);
     }
     if (ResponseFilter.class.isAssignableFrom(clazz)) {
       providers.addResponseFilter(clazz);
     }
   } else if (clazz.getAnnotation(Path.class) != null) {
     // per-request resource
     resources.addResource(clazz, null);
   }
 }
Example #15
0
  private static <A extends Annotation> A getAnnotation(
      Class<?> type, Class<A> annotationType, boolean checkType) {
    A annotation;
    if (checkType) {
      annotation = type.getAnnotation(annotationType);
      if (annotation != null) {
        return annotation;
      }
    }

    if (annotationType.getAnnotation(Inherited.class) != null) {
      for (Class<?> anInterface : type.getInterfaces()) {
        annotation = getAnnotation(anInterface, annotationType, true);
        if (annotation != null) {
          return annotation;
        }
      }
    }

    if (type.isInterface() || type.equals(Object.class)) {
      return null;
    } else {
      return getAnnotation(type.getSuperclass(), annotationType, false);
    }
  }
 /** Creates a Bukkit Inventory for a Menu class */
 Inventory generateFreshMenu(Menu menu, Class clazz) {
   MenuInventory menuInv = (MenuInventory) clazz.getAnnotation(MenuInventory.class);
   Inventory inv = Bukkit.createInventory(null, menuInv.slots(), menuInv.name());
   for (int i = 0; i < inv.getSize(); i++)
     inv.setItem(i, ItemUtils.annotationToItemStack(menuInv.filler()));
   for (Method m : loadedMenus.get(clazz)) {
     MenuItem menuItem = m.getAnnotation(MenuItem.class);
     ItemStack item = ItemUtils.annotationToItemStack(menuItem.item());
     inv.setItem(menuItem.slot(), item);
   }
   if (clazz.isAnnotationPresent(IgnoreSlots.class)) {
     IgnoreSlots ignoreSlots = (IgnoreSlots) clazz.getAnnotation(IgnoreSlots.class);
     if (ignoreSlots.slots().length == ignoreSlots.items().length)
       for (int i = 0; i < ignoreSlots.slots().length; i++)
         inv.setItem(
             ignoreSlots.slots()[i], ItemUtils.annotationToItemStack(ignoreSlots.items()[i]));
   }
   for (Method m : loadedPreprocessors.get(clazz)) {
     try {
       m.invoke(menu, inv);
     } catch (IllegalAccessException e) {
       System.out.println("All @PreProcessor methods must be static!");
       e.printStackTrace();
     } catch (InvocationTargetException e) {
       System.out.println("All @PreProcessor methods must take 1 Inventory as a parameter!");
       e.printStackTrace();
     }
   }
   return inv;
 }
    @Override
    @SuppressWarnings("unchecked")
    protected void doConfigure() {
      for (Class<?> clazz : testCase.getClass().getDeclaredClasses()) {
        BindTo bindTo = clazz.getAnnotation(BindTo.class);
        if (bindTo == null) continue;
        List<Annotation> qualifiers = harvestQualifiers(clazz);
        Annotation classifier = qualifiers.isEmpty() ? null : qualifiers.get(0);
        boolean isSingleton = clazz.getAnnotation(Singleton.class) != null;

        AnnotatedBindingBuilder<?> abuilder = bind(bindTo.value());
        if (classifier != null) {
          LinkedBindingBuilder<?> lbuilder = abuilder.withClassifier(classifier);
          if (Provider.class.isAssignableFrom(clazz)) {
            SingletonBindingBuilder<?> sbuilder = lbuilder.toProvider((Class) clazz);
            if (isSingleton) sbuilder.asSingleton();
          } else {
            SingletonBindingBuilder<?> sbuilder = lbuilder.to((Class) clazz);
            if (isSingleton) sbuilder.asSingleton();
          }
        } else {
          if (Provider.class.isAssignableFrom(clazz)) {
            SingletonBindingBuilder<?> sbuilder = abuilder.toProvider((Class) clazz);
            if (isSingleton) sbuilder.asSingleton();
          } else {
            SingletonBindingBuilder<?> sbuilder = abuilder.to((Class) clazz);
            if (isSingleton) sbuilder.asSingleton();
          }
        }
      }
    }
  protected static boolean matchesSegment(Field field, String segmentTag) {
    Class<?> clz = field.getType();

    if (Collection.class.isAssignableFrom(clz)) {
      clz = getCollectionType(field);
    }

    if (clz.isAnnotationPresent(EDISegment.class)) {
      EDISegment es = clz.getAnnotation(EDISegment.class);
      if (StringUtils.equals(segmentTag, es.tag())) {
        return true;
      }
    } else if (clz.isAnnotationPresent(EDISegmentGroup.class)) {
      EDISegmentGroup esg = clz.getAnnotation(EDISegmentGroup.class);

      String ediSegmentGroupTag = esg.header();

      if (StringUtils.isNotBlank(ediSegmentGroupTag)) {
        if (StringUtils.equals(segmentTag, ediSegmentGroupTag)) {
          return true;
        }
      } else {
        // get the segement group's first field, and recurse.
        if (clz.getDeclaredFields().length > 0) {
          return matchesSegment(clz.getDeclaredFields()[0], segmentTag);
        }
      }
    }

    return false;
  }
Example #19
0
 /** 获取public菜单,未登陆时使用 */
 public static Map<String, List<String[]>> getPublicMenu() {
   Map<String, List<String[]>> map = MENU.get(-10);
   if (map == null) {
     map = new LinkedHashMap<String, List<String[]>>();
     List<String[]> list = new LinkedList<String[]>();
     for (Class<?> clazz : Scans.me().scanPackage("app.module")) {
       if (clazz.getAnnotation(At.class) != null) {
         for (Method method : clazz.getMethods()) {
           Menu menu = method.getAnnotation(Menu.class);
           At at = method.getAnnotation(At.class);
           if (menu != null
               && at != null
               && (clazz.getAnnotation(Public.class) != null
                   || method.getAnnotation(Public.class) != null)) {
             String[] tmp = new String[2];
             tmp[0] = menu.value();
             tmp[1] = clazz.getSimpleName().toLowerCase() + "/" + method.getName().toLowerCase();
             list.add(tmp);
           }
         }
       }
     }
     map.put("", list);
     MENU.put(-10, map);
   }
   return map;
 }
Example #20
0
  private File generateSaveFolder(Class<?> c) throws IOException {

    if (!INexObject.class.isAssignableFrom(c)) {
      return null;
    }

    String mediaFolder = Settings.MediaFolder().get();
    String folder = "unknown";

    if (c.getAnnotation(FileDetails.class) != null) {
      folder = c.getAnnotation(FileDetails.class).folder();
    }

    if (!mediaFolder.endsWith(dir_sep)) mediaFolder = mediaFolder.concat(dir_sep);
    if (folder.startsWith(dir_sep)) folder = folder.substring(1);
    if (!folder.endsWith(dir_sep)) folder = folder.concat(dir_sep);

    if (folder.equals("unknown\\")) {
      return null;
    }

    File f = new File(mediaFolder + folder);
    f.mkdirs();

    return f;
  }
 @Override
 public boolean isReadable(
     Class<?> type, Type genericType, Annotation annotations[], MediaType mediaType) {
   return (type.getAnnotation(XmlRootElement.class) != null
           || type.getAnnotation(XmlType.class) != null)
       && isSupported(mediaType);
 }
  /**
   * Create component descriptors for the passed component implementation class and component role
   * class. There can be more than one descriptor if the component class has specified several
   * hints.
   *
   * @param componentClass the component implementation class
   * @param componentRoleClass the component role class
   * @return the component descriptors with resolved component dependencies
   */
  public List<ComponentDescriptor> createComponentDescriptors(
      Class<?> componentClass, Class<?> componentRoleClass) {
    List<ComponentDescriptor> descriptors = new ArrayList<ComponentDescriptor>();

    // If there's a @Named annotation, use it and ignore hints specified in the @Component
    // annotation.
    String[] hints;
    Named named = componentClass.getAnnotation(Named.class);
    if (named != null) {
      hints = new String[] {named.value()};
    } else {
      // If the Component annotation has several hints specified ignore the default hint value and
      // for each
      // specified hint create a Component Descriptor
      Component component = componentClass.getAnnotation(Component.class);
      if (component != null && component.hints().length > 0) {
        hints = component.hints();
      } else {
        if (component != null && component.value().trim().length() > 0) {
          hints = new String[] {component.value().trim()};
        } else {
          hints = new String[] {"default"};
        }
      }
    }

    // Create the descriptors
    for (String hint : hints) {
      descriptors.add(createComponentDescriptor(componentClass, hint, componentRoleClass));
    }

    return descriptors;
  }
  private void createObject(File file) {
    if (file.isFile() && file.getName().endsWith(".class")) {
      String classNameWithPackage =
          file.getPath().replace("./bin/", "").replace(".class", "").replace("/", ".");
      try {
        Class<?> clazz = Class.forName(classNameWithPackage);

        // @Component 또는 @Controller 애노테이션을 구분하여 처리한다.
        if (clazz.getAnnotation(Component.class) != null) {
          // System.out.printf("%s --> %s\n", clazz.getName(), "Component");
          processComponentAnnotation(clazz);

        } else if (clazz.getAnnotation(Controller.class) != null) {
          // System.out.printf("%s --> %s\n", clazz.getName(), "Controller");
          processControllerAnnotation(clazz);
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
      return;
    }

    File[] subfiles = file.listFiles();
    for (File subfile : subfiles) {
      createObject(subfile);
    }
  }
Example #24
0
  static String getPortType(Class impl, Class api) throws WebServiceException {
    WebService webService = (WebService) impl.getAnnotation(WebService.class);

    if (webService != null) {
      if ("".equals(webService.name()) && "".equals(webService.endpointInterface()))
        return impl.getSimpleName();

      if (!"".equals(webService.name()) && "".equals(webService.endpointInterface()))
        return webService.name();

      if ("".equals(webService.name()) && !"".equals(webService.endpointInterface())) {
        webService = (WebService) api.getAnnotation(WebService.class);

        if (webService != null && !"".equals(webService.name())) return webService.name();
        else return api.getSimpleName();
      }

      if (!"".equals(webService.name()) && !"".equals(webService.endpointInterface()))
        throw new WebServiceException(
            L.l(
                "Cannot specify both name and endpointInterface properties in a WebService annotation: {0}",
                impl));
    }

    return impl.getSimpleName();
  }
  /**
   * @param componentClass the component class from which to extract the component instantiation
   *     strategy
   * @return the component instantiation strategy to use
   */
  private ComponentInstantiationStrategy createComponentInstantiationStrategy(
      Class<?> componentClass) {
    ComponentInstantiationStrategy strategy;

    // Support both InstantiationStrategy and JSR 330's Singleton annotations.
    Singleton singleton = componentClass.getAnnotation(Singleton.class);
    if (singleton != null) {
      strategy = ComponentInstantiationStrategy.SINGLETON;
    } else {
      InstantiationStrategy instantiationStrategy =
          componentClass.getAnnotation(InstantiationStrategy.class);
      if (instantiationStrategy != null) {
        strategy = instantiationStrategy.value();
      } else {
        // TODO: In order to be JSR330 compliant we need to change this behavior and consider
        // components are
        // per lookup when no annotation is specified. Before we can do this we need to modify the
        // full xwiki
        // code base and possibly introduce a configuration option. To be discussed.
        strategy = ComponentInstantiationStrategy.SINGLETON;
      }
    }

    return strategy;
  }
Example #26
0
  public static String getEntityName(Class entity) {

    if (mappedName.get(entity) != null) {
      return mappedName.get(entity);
    }

    String name = null;

    Table table = (Table) entity.getAnnotation(Table.class);
    if (table != null && table.name() != null && !table.name().isEmpty()) {
      name = table.name();
    } else {
      Entity entityAnnotation = (Entity) entity.getAnnotation(Entity.class);
      if (entityAnnotation != null
          && entityAnnotation.name() != null
          && !entityAnnotation.name().isEmpty()) {
        name = entityAnnotation.name();
      } else {
        name = entity.getSimpleName();
      }
    }

    mappedName.put(entity, name);

    return name;
  }
  /**
   * @param uri The uri to identify the component with.
   * @param type The type to create the metadata for
   * @param factory A reflection library to provide class construction and field get/set
   *     functionality
   * @param copyStrategies A copy strategy library
   * @throws NoSuchMethodException If the component has no default constructor
   */
  public ComponentMetadata(
      SimpleUri uri, Class<T> type, ReflectFactory factory, CopyStrategyLibrary copyStrategies)
      throws NoSuchMethodException {
    super(uri, type, factory, copyStrategies, Predicates.<Field>alwaysTrue());
    replicated = type.getAnnotation(Replicate.class) != null;
    blockLifecycleEventsRequired = type.getAnnotation(RequiresBlockLifecycleEvents.class) != null;
    ForceBlockActive forceBlockActiveAnnotation = type.getAnnotation(ForceBlockActive.class);
    if (forceBlockActiveAnnotation != null) {
      forceBlockActive = true;
      retainUnalteredOnBlockChange = forceBlockActiveAnnotation.retainUnalteredOnBlockChange();
    }

    for (ComponentFieldMetadata<T, ?> field : getFields()) {
      if (field.isReplicated()) {
        replicated = true;
        if (field.getReplicationInfo().value().isReplicateFromOwner()) {
          replicatedFromOwner = true;
        }
      }
      if (field.isOwnedReference()) {
        referenceOwner = true;
      }
    }

    annotations = Lists.newArrayList(type.getAnnotations());
  }
Example #28
0
  /**
   * 从类定义中解析表定义<br>
   * 仅解析传入类型:不对传入类型的接口,以及父类进行注解获取<br>
   * <功能详细描述>
   *
   * @param type
   * @return [参数说明]
   * @return JPAEntityTableDef [返回类型说明]
   * @exception throws [异常类型] [异常说明]
   * @see [类、类#方法、类#成员]
   */
  private static JPAEntityTableDef doAnalyzeTableDef(Class<?> type) {
    // 没有注解的时候默认使用类名当作表名
    String tableName = type.getSimpleName();
    String comment = "";
    // 如果存在javax注解中的Entity读取其Name
    // org.hibernate.annotations.Entity该类中不含有表名,不进行解析
    if (type.isAnnotationPresent(Entity.class)) {
      String entityName = type.getAnnotation(Entity.class).name();
      if (!StringUtils.isEmpty(entityName)) {
        tableName = entityName.toUpperCase();
      }
    }
    if (type.isAnnotationPresent(Table.class)) {
      // 如果含有注解:javax.persistence.Table
      String annoTableName = type.getAnnotation(Table.class).name();
      if (!StringUtils.isEmpty(annoTableName)) {
        tableName = annoTableName.toUpperCase();
      }
    }
    if (type.isAnnotationPresent(org.hibernate.annotations.Table.class)) {
      // 如果含有注解:javax.persistence.Table
      String annoTableComment = type.getAnnotation(org.hibernate.annotations.Table.class).comment();
      if (!StringUtils.isEmpty(annoTableComment)) {
        comment = annoTableComment;
      }
    }

    JPAEntityTableDef tableDef = new JPAEntityTableDef();
    tableDef.setTableName(tableName);
    tableDef.setComment(comment);
    return tableDef;
  }
  private DeployInheritInfo createInfo(Class<?> cls) {

    DeployInheritInfo info = new DeployInheritInfo(cls);

    Class<?> parent = findParent(cls);
    if (parent != null) {
      info.setParent(parent);
    } else {
      // its the root of inheritance tree...
    }

    Inheritance ia = (Inheritance) cls.getAnnotation(Inheritance.class);
    if (ia != null) {
      ia.strategy();
    }
    DiscriminatorColumn da = (DiscriminatorColumn) cls.getAnnotation(DiscriminatorColumn.class);
    if (da != null) {
      // lowercase the discriminator column for RawSql and JSON
      info.setDiscriminatorColumn(da.name().toLowerCase());
      DiscriminatorType discriminatorType = da.discriminatorType();
      if (discriminatorType.equals(DiscriminatorType.INTEGER)) {
        info.setDiscriminatorType(Types.INTEGER);
      } else {
        info.setDiscriminatorType(Types.VARCHAR);
      }
      info.setDiscriminatorLength(da.length());
    }

    DiscriminatorValue dv = (DiscriminatorValue) cls.getAnnotation(DiscriminatorValue.class);
    if (dv != null) {
      info.setDiscriminatorValue(dv.value());
    }

    return info;
  }
Example #30
0
 private String getId(Class<?> c) {
   if (c.isAnnotationPresent(Controller.class)) return c.getAnnotation(Controller.class).value();
   else if (c.isAnnotationPresent(Interceptor.class))
     return c.getAnnotation(Interceptor.class).value();
   else if (c.isAnnotationPresent(Component.class))
     return c.getAnnotation(Component.class).value();
   else return "";
 }