예제 #1
0
 /**
  * get parameter names of given {@code constructor}
  *
  * <p>depends on MethodParameterNamesScanner configured
  */
 public List<String> getConstructorParamNames(Constructor constructor) {
   Iterable<String> names =
       store.get(index(MethodParameterNamesScanner.class), Utils.name(constructor));
   return !Iterables.isEmpty(names)
       ? Arrays.asList(Iterables.getOnlyElement(names).split(", "))
       : Arrays.<String>asList();
 }
예제 #2
0
 /**
  * get all fields annotated with a given annotation
  *
  * <p>depends on FieldAnnotationsScanner configured
  */
 public Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation) {
   final Set<Field> result = Sets.newHashSet();
   for (String annotated : store.get(index(FieldAnnotationsScanner.class), annotation.getName())) {
     result.add(getFieldFromString(annotated, loaders()));
   }
   return result;
 }
예제 #3
0
  /**
   * collect saved Reflections resources from all urls that contains the given packagePrefix and
   * matches the given resourceNameFilter and de-serializes them using the default serializer {@link
   * org.reflections.serializers.XmlSerializer} or using the optionally supplied optionalSerializer
   *
   * <p>it is preferred to use a designated resource prefix (for example META-INF/reflections but
   * not just META-INF), so that relevant urls could be found much faster
   *
   * @param optionalSerializer - optionally supply one serializer instance. if not specified or
   *     null, {@link org.reflections.serializers.XmlSerializer} will be used
   */
  public static Reflections collect(
      final String packagePrefix,
      final Predicate<String> resourceNameFilter,
      @Nullable Serializer... optionalSerializer) {
    Serializer serializer =
        optionalSerializer != null && optionalSerializer.length == 1
            ? optionalSerializer[0]
            : new XmlSerializer();

    Collection<URL> urls = ClasspathHelper.forPackage(packagePrefix);
    if (urls.isEmpty()) return null;
    long start = System.currentTimeMillis();
    final Reflections reflections = new Reflections();
    Iterable<Vfs.File> files = Vfs.findFiles(urls, packagePrefix, resourceNameFilter);
    for (final Vfs.File file : files) {
      InputStream inputStream = null;
      try {
        inputStream = file.openInputStream();
        reflections.merge(serializer.read(inputStream));
      } catch (IOException e) {
        throw new ReflectionsException("could not merge " + file, e);
      } finally {
        close(inputStream);
      }
    }

    if (log != null) {
      Store store = reflections.getStore();
      int keys = 0;
      int values = 0;
      for (String index : store.keySet()) {
        keys += store.get(index).keySet().size();
        values += store.get(index).size();
      }

      log.info(
          format(
              "Reflections took %d ms to collect %d url%s, producing %d keys and %d values [%s]",
              System.currentTimeMillis() - start,
              urls.size(),
              urls.size() > 1 ? "s" : "",
              keys,
              values,
              Joiner.on(", ").join(urls)));
    }
    return reflections;
  }
예제 #4
0
 /**
  * get types annotated with a given annotation, both classes and annotations
  *
  * <p>{@link java.lang.annotation.Inherited} is honored according to given honorInherited.
  *
  * <p>when honoring @Inherited, meta-annotation should only effect annotated super classes and
  * it's sub types
  *
  * <p>when not honoring @Inherited, meta annotation effects all subtypes, including annotations
  * interfaces and classes
  *
  * <p><i>Note that this (@Inherited) meta-annotation type has no effect if the annotated type is
  * used for anything other then a class. Also, this meta-annotation causes annotations to be
  * inherited only from superclasses; annotations on implemented interfaces have no effect.</i>
  *
  * <p>depends on TypeAnnotationsScanner and SubTypesScanner configured
  */
 public Set<Class<?>> getTypesAnnotatedWith(
     final Class<? extends Annotation> annotation, boolean honorInherited) {
   Iterable<String> annotated =
       store.get(index(TypeAnnotationsScanner.class), annotation.getName());
   Iterable<String> classes =
       getAllAnnotated(annotated, annotation.isAnnotationPresent(Inherited.class), honorInherited);
   return Sets.newHashSet(concat(forNames(annotated, loaders()), forNames(classes, loaders())));
 }
예제 #5
0
  /**
   * constructs a Reflections instance and scan according to given {@link Configuration}
   *
   * <p>it is preferred to use {@link org.jboss.errai.reflections.util.ConfigurationBuilder}
   */
  public Reflections(final Configuration configuration) {
    this.configuration = configuration;
    store = new Store(configuration);

    // inject to scanners
    for (Scanner scanner : configuration.getScanners()) {
      scanner.setConfiguration(configuration);
      scanner.setStore(store.get(scanner));
    }
  }
예제 #6
0
 /**
  * expand super types after scanning, for super types that were not scanned. this is helpful in
  * finding the transitive closure without scanning all 3rd party dependencies. it uses {@link
  * ReflectionUtils#getSuperTypes(Class)}.
  *
  * <p>for example, for classes A,B,C where A supertype of B, B supertype of C:
  *
  * <ul>
  *   <li>if scanning C resulted in B (B->C in store), but A was not scanned (although A supertype
  *       of B) - then getSubTypes(A) will not return C
  *   <li>if expanding supertypes, B will be expanded with A (A->B in store) - then getSubTypes(A)
  *       will return C
  * </ul>
  */
 public void expandSuperTypes() {
   if (store.keySet().contains(index(SubTypesScanner.class))) {
     Multimap<String, String> mmap = store.get(index(SubTypesScanner.class));
     Sets.SetView<String> keys = Sets.difference(mmap.keySet(), Sets.newHashSet(mmap.values()));
     Multimap<String, String> expand = HashMultimap.create();
     for (String key : keys) {
       expandSupertypes(expand, key, forName(key));
     }
     mmap.putAll(expand);
   }
 }
예제 #7
0
 /**
  * get types annotated with a given annotation, both classes and annotations, including annotation
  * member values matching
  *
  * <p>{@link java.lang.annotation.Inherited} is honored according to given honorInherited
  *
  * <p>depends on TypeAnnotationsScanner configured
  */
 public Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited) {
   Iterable<String> annotated =
       store.get(index(TypeAnnotationsScanner.class), annotation.annotationType().getName());
   Iterable<Class<?>> filter = filter(forNames(annotated, loaders()), withAnnotation(annotation));
   Iterable<String> classes =
       getAllAnnotated(
           names(filter),
           annotation.annotationType().isAnnotationPresent(Inherited.class),
           honorInherited);
   return Sets.newHashSet(
       concat(filter, forNames(filter(classes, not(in(Sets.newHashSet(annotated)))), loaders())));
 }
예제 #8
0
 protected Iterable<String> getAllAnnotated(
     Iterable<String> annotated, boolean inherited, boolean honorInherited) {
   if (honorInherited) {
     if (inherited) {
       Iterable<String> subTypes =
           store.get(
               index(SubTypesScanner.class),
               filter(
                   annotated,
                   new Predicate<String>() {
                     public boolean apply(@Nullable String input) {
                       return !ReflectionUtils.forName(input, loaders()).isInterface();
                     }
                   }));
       return concat(subTypes, store.getAll(index(SubTypesScanner.class), subTypes));
     } else {
       return annotated;
     }
   } else {
     Iterable<String> subTypes =
         concat(annotated, store.getAll(index(TypeAnnotationsScanner.class), annotated));
     return concat(subTypes, store.getAll(index(SubTypesScanner.class), subTypes));
   }
 }
예제 #9
0
 /**
  * get resources relative paths where simple name (key) matches given namePredicate
  *
  * <p>depends on ResourcesScanner configured
  */
 public Set<String> getResources(final Predicate<String> namePredicate) {
   Iterable<String> resources =
       Iterables.filter(store.get(index(ResourcesScanner.class)).keySet(), namePredicate);
   return Sets.newHashSet(store.get(index(ResourcesScanner.class), resources));
 }
예제 #10
0
 /**
  * get parameter names of given {@code method}
  *
  * <p>depends on MethodParameterNamesScanner configured
  */
 public List<String> getMethodParamNames(Method method) {
   Iterable<String> names = store.get(index(MethodParameterNamesScanner.class), name(method));
   return !Iterables.isEmpty(names)
       ? Arrays.asList(Iterables.getOnlyElement(names).split(", "))
       : Arrays.<String>asList();
 }
예제 #11
0
 /** get constructors with any parameter annotated with given annotation */
 public Set<Constructor> getConstructorsWithAnyParamAnnotated(
     Class<? extends Annotation> annotation) {
   return getConstructorsFromDescriptors(
       store.get(index(MethodParameterScanner.class), annotation.getName()), loaders());
 }
예제 #12
0
 public int read(byte[] b, int off, int len) {
   return buf.get(b, off, len);
 }
예제 #13
0
 /** get constructors with parameter types matching given {@code types} */
 public Set<Constructor> getConstructorsMatchParams(Class<?>... types) {
   return getConstructorsFromDescriptors(
       store.get(index(MethodParameterScanner.class), names(types).toString()), loaders());
 }
예제 #14
0
 public int read(byte[] b) {
   return buf.get(b, 0, b.length);
 }
예제 #15
0
  /**
   * \ // Object[][] prizeArr = new Object[][]{ // //id,min,max,prize【奖项】,v【中奖率】 // //外面的转盘转动 // //
   * {1,1,14,"一等奖",1}, // // {2,346,364,"一等奖",1}, // // {3,16,44,"不要灰心",10}, // //
   * {4,46,74,"神马也没有",10}, // // {5,76,104,"祝您好运",10}, // // {6,106,134,"二等奖",2}, // //
   * {7,136,164,"再接再厉",10}, // // {8,166,194,"神马也没有",10}, // // {9,196,224,"运气先攒着",10}, // //
   * {10,226,254,"三等奖",5}, // // {11,256,284,"要加油哦",10}, // // {12,286,314,"神马也没有",10}, // //
   * {13,316,344,"谢谢参与",10} // // //里面的指针转动 // {1,1,14,"一等奖",1}, // {2,346,364,"一等奖",1}, //
   * {3,16,44,"不要灰心",10}, // {4,46,74,"神马也没有",10}, // {5,76,104,"祝您好运",10}, // {6,106,134,"二等奖",2},
   * // {7,136,164,"再接再厉",10}, // {8,166,194,"神马也没有",10}, // {9,196,224,"运气先攒着",10}, //
   * {10,226,254,"三等奖",5}, // {11,256,284,"要加油哦",10}, // {12,286,314,"神马也没有",10}, //
   * {13,316,344,"谢谢参与",10} // };
   */
  public void award() {
    JSONObject json = new JSONObject();
    Member member = Member.dao.findById(getUserIds());
    String storeId = getPara("storeId");
    String programId = getPara("programId");
    ActiveProgram activeProgram = ActiveProgram.dao.findById(programId);
    // 查询是否中奖
    Integer prizeCount =
        ActivePrizeInfo.dao.prizeCount(
            member.getStr("id"), DateUtil.format(new Date(), "yyyyMMdd") + "%", storeId, programId);
    if (prizeCount > 0) {
      json.put("msg", "你已中奖,今天不能在抽奖了");
      json.put("isRight", false);
      renderJson(json.toString());
      return;
    }

    // 查询是否超过限制
    // String time = "";

    Integer count =
        ActivePrizeInfo.dao.findCountBydate(
            member.getStr("id"),
            storeId,
            activeProgram.getStr("activetype_id"),
            programId,
            DateUtil.format(new Date(), "yyyyMMdd") + "%");
    if (count >= activeProgram.getInt("repeat_prize_count")) {
      json.put("msg", "你的抽奖次数已经用完!");
      json.put("isRight", false);
      renderJson(json.toString());
      return;
    }

    List<ActiveProgramItem> activeProgramItems =
        ActiveProgramItem.dao.findActiveProgramItem(programId);
    // 封装

    List<Object[]> prizeArr = new ArrayList<Object[]>();

    Integer totalCount = 0; // 计算总数
    for (int i = 0; i < activeProgramItems.size(); i++) {
      totalCount += activeProgramItems.get(i).getInt("item_count");
    }

    // 设置未中奖信息
    double cal_isPrize = totalCount / (double) activeProgram.getInt("partake_num"); // 中奖概率
    Object[] result_ = new Object[6];
    result_[0] = "-1";
    result_[1] = 31;
    result_[2] = 89;
    result_[3] = "你未中奖";
    result_[4] = (int) ((1 - cal_isPrize) * 100);
    result_[5] = "";
    prizeArr.add(result_);

    // 设置中奖信息
    for (int i = 0; i < activeProgramItems.size(); i++) {
      ActiveProgramItem item = activeProgramItems.get(i);
      if (totalCount == 0) continue;
      double cal = item.getInt("item_count") / (double) activeProgram.getInt("partake_num"); // 每次概率
      if (item.getInt("px") == 1) {
        Object[] r1 = new Object[6];
        r1[0] = item.get("id");
        r1[1] = 1;
        r1[2] = 29;
        r1[3] = item.get("name");
        r1[4] = (int) (cal * 100);
        r1[5] = item.get("active_prize_item_id");
        prizeArr.add(r1);

        Object[] r2 = new Object[6];
        r2[0] = item.get("id");
        r2[1] = 331;
        r2[2] = 359;
        r2[3] = item.get("name");
        r2[4] = (int) (cal * 100);
        r2[5] = item.get("active_prize_item_id");
        prizeArr.add(r2);
      } else {
        Object[] result = new Object[6];
        result[0] = item.get("id");
        result[1] = 360 - (item.getInt("px") - 1) * 60 - 30 + 1;
        result[2] = 360 - (item.getInt("px") - 2) * 60 - 30 - 1;
        result[3] = item.getStr("name");
        result[4] = (int) (cal * 100);
        result[5] = item.get("active_prize_item_id");
        prizeArr.add(result);
      }
    }
    Object result[] = award(prizeArr); // 抽奖后返回角度和奖品等级
    // 1 得到奖项 更新数量
    String itemId = (String) result[3]; // 判断是否中奖
    String provavilit = (String) result[4]; // 奖项类型ID

    // 1.更新奖品数量
    if (StringUtil.isNotBlank(itemId) && !"-1".equals(itemId)) {
      ActiveProgramItem.dao.updateCount(itemId); // 更新数量
    }

    Store store = Store.dao.findById(activeProgram.get("store_id"));

    ActivePrizeItem item = ActivePrizeItem.dao.findById(provavilit);

    ActivePrizeInfo info = new ActivePrizeInfo();
    info.set("id", ToolUtil.getUuidByJdk(true))
        .set("user_id", member.get("id"))
        .set("store_id", activeProgram.get("store_id"))
        .set("store_name", store.get("name"))
        .set("active_type_id", activeProgram.get("activetype_id"))
        .set("active_program_id", activeProgram.get("id"))
        .set("active_program_name", activeProgram.get("name"))
        .set("active_program_item_id", itemId)
        .set("prize_code", "JL" + GenerateUtils.consumCode())
        .set("status", 1)
        .set("loose_time", activeProgram.get("end_time"))
        .set("prize_time", DateUtil.format(new Date(), "yyyyMMddHHmmss"))
        .set("prize_item_name", item != null ? item.get("item_name") : "");
    ActivePrizeInfo.dao.saveInfo(info, item, member.getStr("id"));

    json.put("angle", result[0]);
    json.put("msg", result[2]);
    json.put("isRight", true);
    renderJson(json.toString());
  }
예제 #16
0
 /**
  * get all given {@code method} usages in methods and constructors
  *
  * <p>depends on MemberUsageScanner configured
  */
 public Set<Member> getMethodUsage(Method method) {
   return getMembersFromDescriptors(store.get(index(MemberUsageScanner.class), name(method)));
 }
예제 #17
0
  protected void scan() {
    if (configuration.getUrls() == null || configuration.getUrls().isEmpty()) {
      if (log != null) log.warn("given scan urls are empty. set urls in the configuration");
      return;
    }

    if (log != null && log.isDebugEnabled()) {
      log.debug("going to scan these urls:\n" + Joiner.on("\n").join(configuration.getUrls()));
    }

    long time = System.currentTimeMillis();
    int scannedUrls = 0;
    ExecutorService executorService = configuration.getExecutorService();
    List<Future<?>> futures = Lists.newArrayList();

    for (final URL url : configuration.getUrls()) {
      try {
        if (executorService != null) {
          futures.add(
              executorService.submit(
                  new Runnable() {
                    public void run() {
                      if (log != null && log.isDebugEnabled())
                        log.debug("[" + Thread.currentThread().toString() + "] scanning " + url);
                      scan(url);
                    }
                  }));
        } else {
          scan(url);
        }
        scannedUrls++;
      } catch (ReflectionsException e) {
        if (log != null && log.isWarnEnabled())
          log.warn("could not create Vfs.Dir from url. ignoring the exception and continuing", e);
      }
    }

    // todo use CompletionService
    if (executorService != null) {
      for (Future future : futures) {
        try {
          future.get();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    }

    time = System.currentTimeMillis() - time;

    if (log != null) {
      int keys = 0;
      int values = 0;
      for (String index : store.keySet()) {
        keys += store.get(index).keySet().size();
        values += store.get(index).size();
      }

      log.info(
          format(
              "Reflections took %d ms to scan %d urls, producing %d keys and %d values %s",
              time,
              scannedUrls,
              keys,
              values,
              executorService != null && executorService instanceof ThreadPoolExecutor
                  ? format(
                      "[using %d cores]",
                      ((ThreadPoolExecutor) executorService).getMaximumPoolSize())
                  : ""));
    }
  }
예제 #18
0
 /**
  * get all given {@code field} usages in methods and constructors
  *
  * <p>depends on MemberUsageScanner configured
  */
 public Set<Member> getFieldUsage(Field field) {
   return getMembersFromDescriptors(store.get(index(MemberUsageScanner.class), name(field)));
 }
예제 #19
0
 /** get methods with return type match given type */
 public Set<Method> getMethodsReturn(Class returnType) {
   return getMethodsFromDescriptors(
       store.get(index(MethodParameterScanner.class), names(returnType)), loaders());
 }
예제 #20
0
 /**
  * get all given {@code constructors} usages in methods and constructors
  *
  * <p>depends on MemberUsageScanner configured
  */
 public Set<Member> getConstructorUsage(Constructor constructor) {
   return getMembersFromDescriptors(store.get(index(MemberUsageScanner.class), name(constructor)));
 }
예제 #21
0
 /**
  * get all constructors annotated with a given annotation
  *
  * <p>depends on MethodAnnotationsScanner configured
  */
 public Set<Constructor> getConstructorsAnnotatedWith(
     final Class<? extends Annotation> annotation) {
   Iterable<String> methods =
       store.get(index(MethodAnnotationsScanner.class), annotation.getName());
   return getConstructorsFromDescriptors(methods, loaders());
 }
예제 #22
0
 public Object get(String key, int index) {
   Store store = (Store) super.get(index);
   return store.get(key);
 }
예제 #23
0
 public int read() {
   return buf.get();
 }