@SuppressWarnings("unchecked")
  public void add(Class<?> klass, Scheduled scheduled) throws SchedulerException {
    String name = klass.getName();
    if (!Strings.isBlank(scheduled.cron())) {
      try {
        log.debugf("job define name=%s cron=%s", name, scheduled.cron());
        cron(scheduled.cron(), klass);
        return;
      } catch (SchedulerException e) {
        throw new RuntimeException(e);
      }
    }
    if (scheduled.fixedRate() > 0) {
      log.debugf(
          "job define name=%s fixedRate=%s count=%s initialDelay=%s",
          name, scheduled.fixedRate(), scheduled.count(), scheduled.initialDelay());
      SimpleScheduleBuilder schedule = SimpleScheduleBuilder.simpleSchedule();
      if (scheduled.fixedRate() > 0) schedule.withIntervalInSeconds(scheduled.fixedRate());
      if (scheduled.count() > 0) {
        schedule.withRepeatCount(scheduled.count());
      } else {
        schedule.repeatForever();
      }
      TriggerBuilder<SimpleTrigger> trigger =
          TriggerBuilder.newTrigger().withIdentity(name).withSchedule(schedule);
      if (scheduled.initialDelay() > 0)
        trigger.startAt(new Date(System.currentTimeMillis() + scheduled.initialDelay() * 1000));

      JobDetail job = JobBuilder.newJob((Class<? extends Job>) klass).withIdentity(name).build();
      scheduler.scheduleJob(job, trigger.build());
    }
  }
Example #2
0
 @Aop("redis")
 public boolean updateTags(String topicId, @Param("tags") Set<String> tags) {
   if (Strings.isBlank(topicId) || tags == null) {
     return false;
   }
   Topic topic = dao.fetch(Topic.class, topicId);
   if (topic == null) return false;
   Set<String> oldTags = topic.getTags();
   if (oldTags == null) oldTags = new HashSet<>();
   log.debugf("update from '%s' to '%s'", oldTags, tags);
   topic.setTags(tags);
   dao.update(topic, "tags");
   Set<String> newTags = new HashSet<>(tags);
   newTags.removeAll(oldTags);
   Set<String> removeTags = new HashSet<>(oldTags);
   ;
   removeTags.remove(tags);
   fillTopic(topic, null);
   Date lastReplyTime = topic.getCreateTime();
   if (topic.getLastComment() != null) lastReplyTime = topic.getLastComment().getCreateTime();
   Pipeline pipe = jedis().pipelined();
   for (String tag : removeTags) {
     pipe.zrem(RKEY_TOPIC_TAG + tag.toLowerCase().trim(), topic.getId());
     pipe.zincrby(RKEY_TOPIC_TAG_COUNT, -1, tag.toLowerCase().trim());
   }
   for (String tag : newTags) {
     pipe.zadd(RKEY_TOPIC_TAG + tag.toLowerCase().trim(), lastReplyTime.getTime(), topic.getId());
     pipe.zincrby(RKEY_TOPIC_TAG_COUNT, 1, tag.toLowerCase().trim());
   }
   pipe.sync();
   return true;
 }
Example #3
0
 // ==========================================================
 // 下面是 3 个构造函数
 public NutDao() {
   super();
   _selfId = atomLong.getAndIncrement();
   // 设置默认的回调
   _pojo_queryEntity = new PojoQueryEntityCallback();
   _pojo_fetchEntity = new PojoFetchEntityCallback();
   _pojo_eachEntity = new PojoEachEntityCallback();
   _pojo_fetchInt = new PojoFetchIntCallback();
   _pojo_fetchObject = new PojoFetchObjectCallback();
   _pojo_queryRecord = new PojoQueryRecordCallback();
   _pojo_fetchRecord = new PojoFetchRecordCallback();
   _pojo_eachRecord = new PojoEachRecordCallback();
   if (log.isDebugEnabled())
     log.debugf("%s[_selfId=%d] init ...", getClass().getSimpleName(), _selfId);
 }
Example #4
0
  private void reload() {
    HashMap<Class<?>, Method> settingMap = new HashMap<Class<?>, Method>();
    for (Method m1 : setting.getClass().getMethods()) {
      Class<?>[] pts = m1.getParameterTypes();
      if (pts.length == 1 && Castor.class.isAssignableFrom(pts[0])) settingMap.put(pts[0], m1);
    }

    this.map = new HashMap<Integer, Castor<?, ?>>();
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    classes.addAll(defaultCastorList);
    for (Class<?> klass : classes) {
      try {
        if (Modifier.isAbstract(klass.getModifiers())) continue;
        if (!Castor.class.isAssignableFrom(klass)) continue;
        fillMap(klass, settingMap);
      } catch (Throwable e) {
        if (log.isWarnEnabled())
          log.warnf("Fail to create castor [%s] because: %s", klass, e.getMessage());
      }
    }
    if (log.isDebugEnabled()) log.debugf("Using %s castor for Castors", map.size());
  }
Example #5
0
 public void setupEntityField(Connection conn, Entity<?> en) {
   Statement stat = null;
   ResultSet rs = null;
   ResultSetMetaData rsmd = null;
   try {
     // 获取数据库元信息
     stat = conn.createStatement();
     rs = stat.executeQuery(createResultSetMetaSql(en));
     rsmd = rs.getMetaData();
     // 循环字段检查
     for (MappingField mf : en.getMappingFields()) {
       try {
         int ci = Daos.getColumnIndex(rsmd, mf.getColumnName());
         // 是否只读,如果人家已经是指明是只读了,那么就不要自作聪明得再从数据库里验证了
         // if (!mf.isReadonly() && rsmd.isReadOnly(ci))
         // mf.setAsReadonly();
         // 是否非空
         if (ResultSetMetaData.columnNoNulls == rsmd.isNullable(ci)) mf.setAsNotNull();
         // 枚举类型在数据库中的值
         if (mf.getTypeMirror().isEnum()) {
           if (Daos.isIntLikeColumn(rsmd, ci)) {
             mf.setColumnType(ColType.INT);
           } else {
             mf.setColumnType(ColType.VARCHAR);
           }
         }
       } catch (Exception e) {
         // TODO 需要log一下不?
       }
     }
   } catch (Exception e) {
     if (log.isDebugEnabled()) log.debugf("Table '%s' doesn't exist!", en.getViewName());
   }
   // Close ResultSet and Statement
   finally {
     Daos.safeClose(stat, rs);
   }
 }
 public void init() throws Exception {
   String prefix = "cron.";
   for (String key : conf.getKeys()) {
     if (key.length() < prefix.length() + 1 || !key.startsWith(prefix)) continue;
     String name = key.substring(prefix.length());
     if ("pkgs".equals(name)) {
       log.debug("found cron job packages = " + conf.get(key));
       for (String pkg : Strings.splitIgnoreBlank(conf.get(key), ",")) {
         addPackage(pkg);
       }
       continue;
     }
     String cron = conf.get(key);
     log.debugf("job define name=%s cron=%s", name, cron);
     Class<?> klass = null;
     if (name.contains(".")) {
       klass = Lang.loadClass(name);
     } else {
       klass = Lang.loadClass(getClass().getPackage().getName() + ".job." + name);
     }
     cron(cron, klass);
   }
 }
Example #7
0
  @Override
  public String doHandle(String name, Timering ing) {
    final Map<String, List<Message>> map = new HashMap<String, List<Message>>();
    // 分组
    factory
        .messages()
        .each(
            null,
            "!R!N:",
            null,
            0,
            new Each<Message>() {
              public void invoke(int index, Message msg, int length) {
                List<Message> list = map.get(msg.getOwner());
                if (null == list) {
                  list = new LinkedList<Message>();
                  map.put(msg.getOwner(), list);
                }
                list.add(msg);
              }
            });

    if (log.isDebugEnabled())
      log.debugf("MailMaker: found %d users %s", map.size(), Strings.dup('*', 40));

    // 循环为每个用户发送通知邮件
    for (String unm : map.keySet()) {

      User u = factory.users().get(unm);
      if (null == u || null == u.getEmail()) continue;

      List<Message> list = map.get(unm);

      if (null == list || list.isEmpty()) {
        continue;
      }

      if (log.isDebugEnabled()) log.debugf(" - MailMaker: will send to '%s'", unm);

      Date now = Times.now();

      // 准备消息
      StringBuilder sb = new StringBuilder();
      sb.append("Message in zTask @ " + Times.sDT(now) + " : \n\n");
      for (Message msg : list) {
        sb.append("   [").append(Times.sDT(msg.getCreateTime())).append("] - ");
        sb.append(msg.getText());
        sb.append("\n");
      }
      sb.append("\n\n");

      Message firstMsg = list.get(0);
      String subject =
          String.format(
              "[zTask:%d] %s ",
              list.size(), firstMsg.getText().replaceAll("[\\[]?[0-9a-f]{24}[\\]]?", ""));

      if (log.isDebugEnabled()) log.debugf(" - MailMaker: mail is: '%s':\n%s", subject, sb);

      // 设置收件人
      MailObj mo = ZTasks.textMail(subject, sb.toString());
      mo.setTos(Lang.array(u.getName()));

      if (log.isDebugEnabled())
        log.debugf(" - MailMaker: mail to @%s(%s)", u.getName(), u.getEmail());

      // 加入队列
      factory.mails().joinMail(mo);

      if (log.isDebugEnabled())
        log.debugf(" - MailMaker: after join, queue(%d)", factory.mails().count());

      // 设置通知状态
      for (Message msg : list) factory.messages().setNotified(msg, now);

      if (log.isDebugEnabled()) {
        log.debugf(" - MailMaker: set noti for %d messages", list.size());
        log.debugf(" - MailMaker: %s -- NEXT LOOP --", Strings.dup('-', 28));
      }
    }

    // 返回成功
    return "OK:" + map.size() + " users";
  }
Example #8
0
 /**
  * 当本对象被GC的时候,打印之.
  *
  * <p>因为NutDao是线程安全的,用户反复创建NutDao的话,下面的方法将有提示作用
  */
 protected void finalize() throws Throwable {
   log.debugf("%s[_selfId=%d] finalize", getClass().getSimpleName(), _selfId);
   super.finalize();
 }
Example #9
0
  private void addClass(Class<?> classZ) {
    if (classZ.isInterface()
        || classZ.isMemberClass()
        || classZ.isEnum()
        || classZ.isAnnotation()
        || classZ.isAnonymousClass()) return;
    int modify = classZ.getModifiers();
    if (Modifier.isAbstract(modify) || (!Modifier.isPublic(modify))) return;
    IocBean iocBean = classZ.getAnnotation(IocBean.class);
    if (iocBean != null) {
      if (log.isDebugEnabled()) log.debugf("Found a Class with Ioc-Annotation : %s", classZ);

      // 采用 @IocBean->name
      String beanName = iocBean.name();
      if (Strings.isBlank(beanName)) {
        // 否则采用 @InjectName
        InjectName innm = classZ.getAnnotation(InjectName.class);
        if (null != innm && !Strings.isBlank(innm.value())) {
          beanName = innm.value();
        }
        // 大哥(姐),您都不设啊!? 那就用 simpleName 吧
        else {
          beanName = Strings.lowerFirst(classZ.getSimpleName());
        }
      }

      if (map.containsKey(beanName))
        throw Lang.makeThrow(
            IocException.class,
            "Duplicate beanName=%s, by %s !!  Have been define by %s !!",
            beanName,
            classZ,
            map.get(beanName).getClass());

      IocObject iocObject = new IocObject();
      iocObject.setType(classZ);
      map.put(beanName, iocObject);

      iocObject.setSingleton(iocBean.singleton());
      if (!Strings.isBlank(iocBean.scope())) iocObject.setScope(iocBean.scope());

      // 看看构造函数都需要什么函数
      String[] args = iocBean.args();
      // if (null == args || args.length == 0)
      // args = iocBean.param();
      if (null != args && args.length > 0)
        for (String value : args) iocObject.addArg(convert(value));

      // 设置Events
      IocEventSet eventSet = new IocEventSet();
      iocObject.setEvents(eventSet);
      if (!Strings.isBlank(iocBean.create())) eventSet.setCreate(iocBean.create().trim().intern());
      if (!Strings.isBlank(iocBean.depose())) eventSet.setDepose(iocBean.depose().trim().intern());
      if (!Strings.isBlank(iocBean.fetch())) eventSet.setFetch(iocBean.fetch().trim().intern());

      // 处理字段(以@Inject方式,位于字段)
      List<String> fieldList = new ArrayList<String>();
      Mirror<?> mirror = Mirror.me(classZ);
      Field[] fields = mirror.getFields(Inject.class);
      for (Field field : fields) {
        Inject inject = field.getAnnotation(Inject.class);
        // 无需检查,因为字段名是唯一的
        // if(fieldList.contains(field.getName()))
        // throw duplicateField(classZ,field.getName());
        IocField iocField = new IocField();
        iocField.setName(field.getName());
        IocValue iocValue;
        if (Strings.isBlank(inject.value())) {
          iocValue = new IocValue();
          iocValue.setType(IocValue.TYPE_REFER);
          iocValue.setValue(field.getName());
        } else iocValue = convert(inject.value());
        iocField.setValue(iocValue);
        iocObject.addField(iocField);
        fieldList.add(iocField.getName());
      }
      // 处理字段(以@Inject方式,位于set方法)
      Method[] methods;
      try {
        methods = classZ.getMethods();
      } catch (Exception e) {
        // 如果获取失败,就忽略之
        log.info("Fail to call getMethods(), miss class or Security Limit, ignore it", e);
        methods = new Method[0];
      }
      for (Method method : methods) {
        Inject inject = method.getAnnotation(Inject.class);
        if (inject == null) continue;
        // 过滤特殊方法
        int m = method.getModifiers();
        if (Modifier.isAbstract(m) || (!Modifier.isPublic(m)) || Modifier.isStatic(m)) continue;
        String methodName = method.getName();
        if (methodName.startsWith("set")
            && methodName.length() > 3
            && method.getParameterTypes().length == 1) {
          IocField iocField = new IocField();
          iocField.setName(Strings.lowerFirst(methodName.substring(3)));
          if (fieldList.contains(iocField.getName()))
            throw duplicateField(classZ, iocField.getName());
          IocValue iocValue;
          if (Strings.isBlank(inject.value())) {
            iocValue = new IocValue();
            iocValue.setType(IocValue.TYPE_REFER);
            iocValue.setValue(Strings.lowerFirst(methodName.substring(3)));
          } else iocValue = convert(inject.value());
          iocField.setValue(iocValue);
          iocObject.addField(iocField);
          fieldList.add(iocField.getName());
        }
      }
      // 处理字段(以@IocBean.field方式)
      String[] flds = iocBean.fields();
      if (flds != null && flds.length > 0) {
        for (String fieldInfo : flds) {
          if (fieldList.contains(fieldInfo)) throw duplicateField(classZ, fieldInfo);
          IocField iocField = new IocField();
          if (fieldInfo.contains(":")) { // dao:jndi:dataSource/jdbc形式
            String[] datas = fieldInfo.split(":", 2);
            // 完整形式, 与@Inject完全一致了
            iocField.setName(datas[0]);
            iocField.setValue(convert(datas[1]));
            iocObject.addField(iocField);
          } else {
            // 基本形式, 引用与自身同名的bean
            iocField.setName(fieldInfo);
            IocValue iocValue = new IocValue();
            iocValue.setType(IocValue.TYPE_REFER);
            iocValue.setValue(fieldInfo);
            iocField.setValue(iocValue);
            iocObject.addField(iocField);
          }
          fieldList.add(iocField.getName());
        }
      }
    } else {
      if (log.isWarnEnabled()) {
        Field[] fields = classZ.getDeclaredFields();
        for (Field field : fields)
          if (field.getAnnotation(Inject.class) != null) {
            log.warnf(
                "class(%s) don't has @IocBean, but field(%s) has @Inject! Miss @IocBean ??",
                classZ.getName(), field.getName());
            break;
          }
      }
    }
  }