Ejemplo n.º 1
0
 @Override
 protected String getResource() {
   if (null == href) {
     this.href = Strings.concat("/security/user!dashboard?user.id=", user.getId().toString());
   }
   return this.href;
 }
 public Authentication authenticate(Authentication authentication) throws AuthenticationException {
   CasAuthentication casauth = (CasAuthentication) authentication;
   // If an existing CasAuthenticationToken, just check we created it
   if (casauth.isAuthenticated()) {
     if (key.hashCode() == casauth.getKeyHash()) {
       return authentication;
     } else {
       throw new BadCredentialsException("CasAuthenticationProvider.incorrectKey");
     }
   }
   // Ensure credentials are presented
   if (Strings.isEmpty(String.valueOf(casauth.getCredentials()))) {
     throw new BadCredentialsException("CasAuthenticationProvider.noServiceTicket");
   }
   boolean stateless = false;
   if (STATELESS_ID.equals(casauth.getPrincipal())) {
     stateless = true;
   }
   CasAuthentication result = null;
   // Try to obtain from cache
   if (stateless) {
     result = statelessTicketCache.get(casauth.getCredentials().toString());
   }
   if (result == null) {
     result = authenticateNow(casauth);
     result.setDetails(casauth.getDetails());
   }
   // Add to cache
   if (stateless) {
     statelessTicketCache.put(result);
   }
   return result;
 }
Ejemplo n.º 3
0
 /**
  * Constructor for MultiPropertyComparator.
  *
  * @param propertyStr a {@link java.lang.String} object.
  */
 public MultiPropertyComparator(final String propertyStr) {
   super();
   final String[] properties = Strings.split(propertyStr, ',');
   for (int i = 0; i < properties.length; i++) {
     addComparator(new PropertyComparator(properties[i].trim()));
   }
 }
Ejemplo n.º 4
0
  @Override
  protected void evaluateParams() {
    String[] nameArray = Strings.split(name, ',');
    dates = new Date[nameArray.length];
    String format2 = Date.ResvervedFormats.get(format);
    if (null != format2) format = format2;
    String[] requiredArray = Strings.split(required, ',');
    String[] commentArray = Strings.split(comment, ',');
    String[] labelArray = Strings.split(label, ',');
    for (int i = 0; i < nameArray.length; i++) {
      if (i >= 2) break;
      dates[i] = new Date(stack);
      String name = nameArray[i];
      dates[i].setName(name);
      dates[i].setFormat(format);
      if (requiredArray != null) {
        dates[i].setRequired(requiredArray.length == 1 ? required : requiredArray[i]);
      }
      if (commentArray != null) {
        dates[i].setComment(commentArray.length == 1 ? comment : commentArray[i]);
      }
      if (labelArray != null) {
        dates[i].setLabel(labelArray.length == 1 ? label : labelArray[i]);
      }
      dates[i].setTitle(dates[i].getLabel());
      if (i == 0) dates[0].setValue(start);
      else dates[1].setValue(end);

      dates[i].evaluateParams();
    }
    if (dates.length == 2) {
      dates[0].setMaxDate("#F{$dp.$D(\\'" + dates[1].id + "\\')}");
      dates[1].setMinDate("#F{$dp.$D(\\'" + dates[0].id + "\\')}");

      if (labelArray.length == 1) {
        boolean containTime = format.contains("HH:mm");
        dates[0].setTitle(
            dates[0].getTitle() + getText(containTime ? "common.beginAt" : "common.beginOn"));
        dates[1].setTitle(
            dates[1].getTitle() + getText(containTime ? "common.endAt" : "common.endOn"));
      }
    }
  }
Ejemplo n.º 5
0
 public static void main(String[] args) throws IOException {
   String host, username, password, base;
   if (args.length < 4) {
     println("Usage: LdapMain host:port username password base");
     return;
   } else {
     host = args[0];
     username = args[1];
     password = args[2];
     base = args[3];
   }
   LdapMain a = new LdapMain();
   println("Connecting to ldap://" + host);
   println("Using base:" + base);
   SimpleLdapUserStore store = a.getStore("ldap://" + host, username, password, base);
   println("Enter query user[/password]: ");
   BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
   String value = stdin.readLine();
   while (Strings.isNotBlank(value)) {
     String myname = value;
     String mypass = null;
     if (value.contains("/")) {
       myname = Strings.substringBefore(value, "/");
       mypass = Strings.substringAfter(value, "/");
     }
     try {
       a.tryGet(store, myname);
       if (null != mypass) {
         a.tryTestPassword(store, myname, mypass);
       }
     } catch (Exception e) {
       e.printStackTrace();
     } finally {
       println("Enter query user[/password]: ");
     }
     value = stdin.readLine();
   }
 }
Ejemplo n.º 6
0
 /** {@inheritDoc} 安静的拷贝属性,如果属性非法或其他错误则记录日志 */
 public boolean populateValue(
     final Object target, String entityName, final String attr, final Object value) {
   try {
     if (attr.indexOf('.') > -1)
       initProperty(target, entityName, Strings.substringBeforeLast(attr, "."));
     beanUtils.copyProperty(target, attr, value);
     return true;
   } catch (Exception e) {
     logger.warn(
         "copy property failure:[class:" + entityName + " attr:" + attr + " value:" + value + "]:",
         e);
     return false;
   }
 }
Ejemplo n.º 7
0
 private int updateFile(File path) {
   int count = 0;
   if (path.isDirectory()) {
     String[] fileNames = path.list();
     for (String fileName : fileNames) {
       File file = new File(path.getAbsolutePath() + "/" + fileName);
       if (file.isDirectory()) {
         count += updateFile(file);
         file.delete();
       } else {
         String type = Strings.substringAfter(fileName, ".");
         boolean passed = containType(type);
         if (passed) {
           logger.debug("updating avatar by {}", file.getName());
           updateAvatar(Strings.substringBefore(fileName, "."), file, type);
           count++;
         }
         file.delete();
       }
     }
   }
   return count;
 }
Ejemplo n.º 8
0
 public String test(CodeFixture fixture, CodeScript codeScript) {
   try {
     Class<?> codeClass = Class.forName(codeScript.getCodeClassName());
     Entity<?> entity = (Entity<?>) codeClass.newInstance();
     PropertyUtils.getProperty(entity, codeScript.getAttr());
     if (null != fixture) {
       for (Iterator<?> iter = fixture.getParams().keySet().iterator(); iter.hasNext(); ) {
         String param = (String) iter.next();
         interpreter.set(param, fixture.getParams().get(param));
       }
       if (Strings.isNotEmpty(fixture.getScript())) {
         interpreter.eval(fixture.getScript());
       }
     }
     return gen(new CodeFixture(entity, codeScript.getScript()));
   } catch (Exception e) {
     return Throwables.getStackTrace(e);
   }
 }
Ejemplo n.º 9
0
 public static boolean isValid(
     String remoteip, String privatekey, String challenge, String response) {
   if (Strings.isEmpty(response)) {
     return false;
   }
   String result =
       HttpUtils.getResponseText(
           "http://www.google.com/recaptcha/api/verify?remoteip="
               + remoteip
               + "&privatekey="
               + privatekey
               + "&challenge="
               + challenge
               + "&response="
               + response);
   if (!result.contains("true")) {
     return false;
   }
   return true;
 }
 private CasAuthentication authenticateNow(CasAuthentication auth) throws AuthenticationException {
   try {
     final Assertion assertion =
         ticketValidator.validate(auth.getCredentials().toString(), auth.getLoginUrl());
     String name = assertion.getPrincipal();
     final UserDetail userDetail = userDetailService.loadDetail(name);
     if (null == userDetail) {
       logger.error("cannot load {}'s detail from system", name);
       throw new UsernameNotFoundException(Strings.concat("user ", name, " not found in system"));
     }
     userDetailChecker.check(userDetail);
     return new CasAuthentication(
         key,
         userDetail,
         auth.getCredentials(),
         userDetail.getAuthorities(),
         userDetail,
         assertion);
   } catch (final TicketValidationException e) {
     throw new BadCredentialsException("Bad credentials :" + auth.getCredentials().toString(), e);
   }
 }
Ejemplo n.º 11
0
  /**
   * {@inheritDoc} 初始化对象指定路径的属性。<br>
   * 例如给定属性a.b.c,方法会依次检查a a.b a.b.c是否已经初始化
   */
  public ObjectAndType initProperty(final Object target, String entityName, final String attr) {
    Object propObj = target;
    Object property = null;

    int index = 0;
    String[] attrs = Strings.split(attr, ".");
    Type type = Model.getType(entityName);
    while (index < attrs.length) {
      try {
        property = PropertyUtils.getProperty(propObj, attrs[index]);
        Type propertyType = type.getPropertyType(attrs[index]);
        // 初始化
        if (null == propertyType) {
          logger.error("Cannot find property type [{}] of {}", attrs[index], propObj.getClass());
          throw new RuntimeException(
              "Cannot find property type " + attrs[index] + " of " + propObj.getClass().getName());
        }
        if (null == property) {
          property = propertyType.newInstance();
          try {
            PropertyUtils.setProperty(propObj, attrs[index], property);
          } catch (NoSuchMethodException e) {
            // Try fix jdk error for couldn't find correct setter when object's Set required type is
            // diffent with Get's return type declared in interface.
            Method setter = Reflections.getSetter(propObj.getClass(), attrs[index]);
            if (null != setter) setter.invoke(propObj, property);
            else throw e;
          }
        }
        index++;
        propObj = property;
        type = propertyType;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    return new ObjectAndType(property, type);
  }
Ejemplo n.º 12
0
 public static boolean isValidRedirectUrl(String url) {
   return Strings.isBlank(url) || url.startsWith("/") || url.toLowerCase().startsWith("http");
 }
Ejemplo n.º 13
0
 /**
  * 将params中的属性([attr(string)->value(object)],放入到实体类中。
  *
  * <p>如果引用到了别的实体,那么<br>
  * 如果params中的id为null,则将该实体的置为null.<br>
  * 否则新生成一个实体,将其id设为params中指定的值。 空字符串按照null处理
  */
 public Object populate(Object entity, String entityName, Map<String, Object> params) {
   Type type = Model.getType(entityName);
   for (final Map.Entry<String, Object> paramEntry : params.entrySet()) {
     String attr = paramEntry.getKey();
     Object value = paramEntry.getValue();
     if (value instanceof String) {
       if (Strings.isEmpty((String) value)) {
         value = null;
       } else if (TRIM_STR) {
         value = ((String) value).trim();
       }
     }
     // 主键
     if (null != type
         && type.isEntityType()
         && attr.equals(((EntityType) type).getIdPropertyName())) {
       if (ValidEntityKeyPredicate.INSTANCE.evaluate(value)) {
         setValue(attr, value, entity);
       } else {
         try {
           PropertyUtils.setProperty(entity, attr, null);
         } catch (Exception e) {
           throw new RuntimeException(e.getMessage());
         }
       }
       continue;
     }
     // 普通属性
     if (-1 == attr.indexOf('.')) {
       setValue(attr, value, entity);
     } else {
       String parentAttr = Strings.substring(attr, 0, attr.lastIndexOf('.'));
       try {
         ObjectAndType ot = initProperty(entity, entityName, parentAttr);
         if (null == ot) {
           logger.error("error attr:[" + attr + "] value:[" + value + "]");
           continue;
         }
         // 属性也是实体类对象
         if (ot.getType().isEntityType()) {
           String foreignKey = ((EntityType) ot.getType()).getIdPropertyName();
           if (attr.endsWith("." + foreignKey)) {
             if (null == value) {
               setValue(parentAttr, null, entity);
             } else {
               Object foreignValue = PropertyUtils.getProperty(entity, attr);
               // 如果外键已经有值
               if (null != foreignValue) {
                 if (!foreignValue.toString().equals(value.toString())) {
                   setValue(parentAttr, null, entity);
                   initProperty(entity, entityName, parentAttr);
                   setValue(attr, value, entity);
                 }
               } else {
                 setValue(attr, value, entity);
               }
             }
           } else {
             setValue(attr, value, entity);
           }
         } else {
           setValue(attr, value, entity);
         }
       } catch (Exception e) {
         logger.error("error attr:[" + attr + "] value:[" + value + "]", e);
       }
     }
     if (logger.isDebugEnabled()) logger.debug("populate attr:[{}] value:[{}]", attr, value);
   }
   return entity;
 }
Ejemplo n.º 14
0
  /** 根据请求的实体,生成代码 */
  @SuppressWarnings("unchecked")
  public String gen(CodeFixture fixture) {
    // 在必要时查找相应的生成脚本
    String script = fixture.getScript();
    CodeScript codeScript = null;
    if (null == script) {
      codeScript = getCodeScript(EntityUtils.getEntityClassName(fixture.getEntity().getClass()));
      if (null == codeScript) {
        return null;
      }
      script = codeScript.getScript();
      try {
        String code = (String) PropertyUtils.getProperty(fixture.getEntity(), codeScript.getAttr());
        if (isValidCode(code)) {
          return code;
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
    int seqLength = -1;
    // 替换自动代码生成中的seq[x]
    if (Strings.contains(script, SEQ)) {
      seqLength = Numbers.toInt(Strings.substringBetween(script, SEQ + "[", "]"));

      script =
          Strings.replace(
              script, SEQ + "[" + Strings.substringBetween(script, SEQ + "[", "]") + "]", SEQ);
    }
    fixture.setScript(script);
    String code = super.gen(fixture);
    List<String> seqs = CollectUtils.newArrayList();
    if (-1 != seqLength) {
      try {
        OqlBuilder<?> builder =
            OqlBuilder.from(Class.forName(codeScript.getCodeClassName()), "entity");
        builder.select(
            "select substr(entity."
                + codeScript.getAttr()
                + ","
                + (code.indexOf(SEQ) + 1)
                + ","
                + seqLength
                + ")");
        builder.where(
            " entity." + codeScript.getAttr() + " like :codeExample",
            Strings.replace(code, SEQ, "%"));
        builder.where(
            "length(entity."
                + codeScript.getAttr()
                + ")="
                + (code.length() - SEQ.length() + seqLength));
        seqs = (List<String>) entityDao.search(builder);
        Collections.sort(seqs);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
      synchronized (this) {
        int newSeqNo = 0;
        for (Iterator<String> iter = seqs.iterator(); iter.hasNext(); ) {
          String seqNo = iter.next();
          if (Numbers.toInt(seqNo) - newSeqNo >= 2) {
            break;
          } else {
            newSeqNo = Numbers.toInt(seqNo);
          }
        }
        newSeqNo++;
        String seqNo = String.valueOf(newSeqNo);
        if (0 != seqLength) {
          seqNo = Strings.repeat("0", seqLength - seqNo.length()) + newSeqNo;
        }
        code = Strings.replace(code, SEQ, seqNo);
      }
    }
    return code;
  }