Esempio n. 1
0
 private void predicate(
     JPAQuery query,
     QSpecial special,
     Integer[] siteId,
     Integer[] categoryId,
     Date beginDate,
     Date endDate,
     Boolean isWithImage,
     Boolean isRecommend) {
   query.from(special);
   BooleanBuilder exp = new BooleanBuilder();
   if (ArrayUtils.isNotEmpty(siteId)) {
     exp = exp.and(special.site.id.in(siteId));
   }
   if (ArrayUtils.isNotEmpty(categoryId)) {
     exp = exp.and(special.category.id.in(categoryId));
   }
   if (beginDate != null) {
     exp = exp.and(special.creationDate.goe(beginDate));
   }
   if (endDate != null) {
     exp = exp.and(special.creationDate.goe(endDate));
   }
   if (isWithImage != null) {
     exp = exp.and(special.withImage.eq(isWithImage));
   }
   if (isRecommend != null) {
     exp = exp.and(special.recommend.eq(isRecommend));
   }
   query.where(exp);
 }
    private void retrieveMonitorDetails(final HttpResponse res) {
      Header[] headers = res.getHeaders(HttpHeader.LOCATION);
      if (ArrayUtils.isNotEmpty(headers)) {
        this.location = URI.create(headers[0].getValue());
      } else {
        throw new AsyncRequestException(
            "Invalid async request response. Monitor URL '" + headers[0].getValue() + "'");
      }

      headers = res.getHeaders(HttpHeader.RETRY_AFTER);
      if (ArrayUtils.isNotEmpty(headers)) {
        this.retryAfter = Integer.parseInt(headers[0].getValue());
      }

      headers = res.getHeaders(HttpHeader.PREFERENCE_APPLIED);
      if (ArrayUtils.isNotEmpty(headers)) {
        for (Header header : headers) {
          if (header.getValue().equalsIgnoreCase(new ODataPreferences().respondAsync())) {
            preferenceApplied = true;
          }
        }
      }
      try {
        EntityUtils.consume(res.getEntity());
      } catch (IOException ex) {
        Logger.getLogger(AsyncRequestWrapperImpl.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  /**
   * 部署classpath下面的流程定义
   *
   * <p>从属性配置文件中获取属性<b>workflow.modules</b>扫描**deployments**
   *
   * <p>然后从每个**deployments/${module}**查找在属性配置文件中的属性**workflow.module.keys.${ submodule}**
   *
   * <p>配置实例:
   *
   * <p>
   *
   * <pre>
   * #workflow for deploy
   * workflow.modules=budget,erp,oa
   * workflow.module.keys.budget=budget
   * workflow.module.keys.erp=acceptInsurance,billing,effectInsurance,endorsement,payment
   * workflow.module.keys.oa=caruse,leave,officalstamp,officesupply,out,overtime
   * </pre>
   *
   * <p>
   *
   * @param processKey 流程定义KEY
   * @throws Exception
   */
  public void deployFromClasspath(String exportDir, String... processKey) throws Exception {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    String[] processKeys = {"leave", "leave-dynamic-from", "leave-formkey", "dispatch"};
    for (String loopProcessKey : processKeys) {

      /*
       * 需要过滤指定流程
       */
      if (ArrayUtils.isNotEmpty(processKey)) {
        if (ArrayUtils.contains(processKey, loopProcessKey)) {
          logger.debug("hit module of {}", processKey);
          deploySingleProcess(resourceLoader, loopProcessKey, exportDir);
        } else {
          logger.debug(
              "module: {} not equals process key: {}, ignore and continue find next.",
              loopProcessKey,
              processKey);
        }
      } else {
        /*
         * 所有流程
         */
        deploySingleProcess(resourceLoader, loopProcessKey, exportDir);
      }
    }
  }
Esempio n. 4
0
  @Override
  protected SecurityQuestionTO resolveReference(final Method method, final Object... args)
      throws UnresolvedReferenceException {

    Long key = null;

    if (ArrayUtils.isNotEmpty(args)) {
      for (int i = 0; key == null && i < args.length; i++) {
        if (args[i] instanceof Long) {
          key = (Long) args[i];
        } else if (args[i] instanceof SecurityQuestionTO) {
          key = ((SecurityQuestionTO) args[i]).getKey();
        }
      }
    }

    if ((key != null) && !key.equals(0L)) {
      try {
        return binder.getSecurityQuestionTO(securityQuestionDAO.find(key));
      } catch (Throwable ignore) {
        LOG.debug("Unresolved reference", ignore);
        throw new UnresolvedReferenceException(ignore);
      }
    }

    throw new UnresolvedReferenceException();
  }
    @Override
    public R getODataResponse() {
      HttpResponse res = null;
      for (int i = 0; response == null && i < MAX_RETRY; i++) {
        res = checkMonitor(location);

        if (res.getStatusLine().getStatusCode() == HttpStatusCode.ACCEPTED.getStatusCode()) {

          final Header[] headers = res.getHeaders(HttpHeader.RETRY_AFTER);
          if (ArrayUtils.isNotEmpty(headers)) {
            this.retryAfter = Integer.parseInt(headers[0].getValue());
          }

          try {
            // wait for retry-after
            Thread.sleep(retryAfter * 1000);
          } catch (InterruptedException ignore) {
            // ignore
          }

        } else {
          location = null;
          return instantiateResponse(res);
        }
      }

      if (response == null) {
        throw new ODataClientErrorException(res == null ? null : res.getStatusLine());
      }

      return response;
    }
Esempio n. 6
0
  static {
    // 获取所有的bean类与bean实例之间的映射关系(简称Bean Map)
    Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
    if (MapUtils.isNotEmpty(beanMap)) {
      // 遍历 bean map
      for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
        // 从bean map中获取bean类和bean实例
        Class<?> beanClass = beanEntry.getKey();
        Object beanInstance = beanEntry.getValue();

        // 获取bean定义的所有成员变量
        Field[] beanFields = beanClass.getDeclaredFields();
        if (ArrayUtils.isNotEmpty(beanFields)) {
          // 遍历 bean field
          for (Field beanField : beanFields) {
            // 判断当前bean field是否带有Inject注解
            if (beanField.isAnnotationPresent(Inject.class)) {
              // 在bean map中获取bean field对应的实例
              Class<?> beanFieldClass = beanField.getType();
              Object beanFieldInstance = beanMap.get(beanFieldClass);
              if (null != beanFieldInstance) {
                // 通过反射初始化bean field的值
                ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
              }
            }
          }
        }
      }
    }
  }
Esempio n. 7
0
  public QueryParams addParam(String name, String... values) {
    String[] oldValues = params.get(name);
    if (ArrayUtils.isNotEmpty(oldValues)) {
      values = ArrayUtils.addAll(oldValues, values);
    }

    params.put(name, values);

    return this;
  }
Esempio n. 8
0
  public QueryParams addParam(String name, String value) {
    String[] oldValues = params.get(name);
    String[] values;

    if (ArrayUtils.isNotEmpty(oldValues)) {
      values = ArrayUtils.add(oldValues, value);
    } else {
      values = new String[1];
      values[0] = value;
    }

    params.put(name, values);

    return this;
  }
  /**
   * 取得本类中所有的属性列表
   *
   * @param targetClass 要反射的目标
   * @param ignoreParen 是否忽略父类中的属性
   * @return
   */
  public static List<Field> getAccessibleFileds(final Class<?> targetClass, boolean ignoreParen) {
    Assert.notNull(targetClass, "targetClass不能为空");
    List<Field> list = new ArrayList<Field>();
    Class<?> superClass = targetClass;
    do {
      Field[] fields = superClass.getDeclaredFields();
      if (ArrayUtils.isNotEmpty(fields)) {
        for (Field field : fields) {
          field.setAccessible(true);
        }
        CollectionUtils.addAll(list, fields);
      }
      superClass = superClass.getSuperclass();
    } while (superClass != Object.class && !ignoreParen);

    return list;
  }
  /**
   * 通过字典类别代码获取数据字典集合
   *
   * @param code 字典列别
   * @param ignoreValue 忽略字典的值
   * @return List
   */
  public List<DataDictionary> getByCategoryCode(SystemDictionaryCode code, String... ignoreValue) {
    StringBuffer hql = new StringBuffer("from DataDictionary dd where dd.category.code = ?");

    List<String> args = Lists.newArrayList(code.getCode());

    if (ArrayUtils.isNotEmpty(ignoreValue)) {

      String[] qm = new String[ignoreValue.length];

      for (int i = 0; i < ignoreValue.length; i++) {
        qm[i] = "?";
      }

      CollectionUtils.addAll(args, ignoreValue);
      hql.append(MessageFormat.format(" and dd.value not in({0})", StringUtils.join(qm, ",")));
    }

    return findByQuery(hql.toString(), args.toArray());
  }
 protected void logInWithToken() throws AuthenticationException {
   if (StringUtils.isBlank(this.getUserID())) {
     if (StringUtils.isBlank(this.getUsername())) {
       this.setUserid(this.getUsername());
     } else {
       throw new InvalidCredentialsException("Invalid access token");
     }
   }
   if (StringUtils.isBlank(this.getAuthenticatedToken())) {
     throw new InvalidCredentialsException("Invalid access token");
   }
   logger.info("Logging in with access token");
   if (this.checkTokenValidity()) {
     logger.debug("Skipping refresh call as we're safely logged in.");
     this.isOnline = true;
     return;
   }
   RefreshRequest request = new RefreshRequest(this);
   RefreshResponse response =
       this.getAuthenticationService().makeRequest(routeRefresh, request, RefreshResponse.class);
   if (!response.getClientToken().equals(this.getAuthenticationService().getClientToken())) {
     throw new AuthenticationException(
         "Server requested we change out client token. Don't know how to handle this!");
   }
   if (response.getSelectedProfile() != null) {
     this.setUserType(
         response.getSelectedProfile().isLegacy() ? UserType.LEGACY : UserType.MOJANG);
   } else if (ArrayUtils.isNotEmpty(response.getAvailableProfiles())) {
     this.setUserType(
         response.getAvailableProfiles()[0].isLegacy() ? UserType.LEGACY : UserType.MOJANG);
   }
   if (response.getUser() != null && response.getUser().getId() != null) {
     this.setUserid(response.getUser().getId());
   } else {
     this.setUserid(this.getUsername());
   }
   this.isOnline = true;
   this.accessToken = response.getAccessToken();
   this.profiles = response.getAvailableProfiles();
   this.setSelectedProfile(response.getSelectedProfile());
   this.getModifiableUserProperties().clear();
   this.updateUserProperties(response.getUser());
 }
 protected Set<FileStoreMapper> addToFileStore(final MultipartFile[] files) {
   if (ArrayUtils.isNotEmpty(files))
     return Arrays.asList(files)
         .stream()
         .filter(file -> !file.isEmpty())
         .map(
             file -> {
               try {
                 return fileStoreService.store(
                     file.getInputStream(),
                     file.getOriginalFilename(),
                     file.getContentType(),
                     PGRConstants.MODULE_NAME);
               } catch (final Exception e) {
                 throw new ApplicationRuntimeException("err.input.stream", e);
               }
             })
         .collect(Collectors.toSet());
   else return null;
 }
  private void initializeHandlerRegistry() {
    if (this.registeredHandlers == null) {
      this.registeredHandlers = new HashMap<>();

      final String[] commandHandlerBeans =
          this.applicationContext.getBeanNamesForAnnotation(CommandType.class);
      if (ArrayUtils.isNotEmpty(commandHandlerBeans)) {
        for (final String commandHandlerName : commandHandlerBeans) {
          LOGGER.info("Register command handler '" + commandHandlerName + "' ...");
          final CommandType commandType =
              this.applicationContext.findAnnotationOnBean(commandHandlerName, CommandType.class);
          try {
            this.registeredHandlers.put(
                commandType.entity() + "|" + commandType.action(), commandHandlerName);
          } catch (final Throwable th) {
            LOGGER.error("Unable to register command handler '" + commandHandlerName + "'!", th);
          }
        }
      }
    }
  }
Esempio n. 14
0
  /**
   * 获取对象的所有DeclaredMethod,并强制设置为可访问
   *
   * @param targetClass 要反射的对象
   * @param ignoreParent 是否忽略父类
   * @return
   */
  public static List<Method> getAccessibleMethods(
      final Class<?> targetClass, boolean ignoreParent) {
    Assert.notNull(targetClass, "targetClass不能为空");
    List<Method> list = new ArrayList<Method>();
    Class<?> superClass = targetClass;

    do {
      Method[] ms = superClass.getDeclaredMethods();
      // 方法数组不为空
      if (ArrayUtils.isNotEmpty(ms)) {
        // 修改访问权限
        for (Method method : ms) {
          method.setAccessible(true);
        }
        CollectionUtils.addAll(list, ms);
      }
      superClass = superClass.getSuperclass();
      logger.debug("superClass {}", superClass);
    } while (superClass != Object.class && !ignoreParent);
    return list;
  }
 protected void logInWithPassword() throws AuthenticationException {
   if (StringUtils.isBlank(this.getUsername())) {
     throw new InvalidCredentialsException("Invalid username");
   }
   if (StringUtils.isBlank(this.getPassword())) {
     throw new InvalidCredentialsException("Invalid password");
   }
   logger.info("Logging in with username & password");
   AuthenticationRequest request =
       new AuthenticationRequest(this, this.getUsername(), this.getPassword());
   AuthenticationResponse response =
       this.getAuthenticationService()
           .makeRequest(routeAuthenticate, request, AuthenticationResponse.class);
   if (!response.getClientToken().equals(this.getAuthenticationService().getClientToken())) {
     throw new AuthenticationException(
         "Server requested we change our client token, Don't know how to handle this!");
   }
   if (response.getSelectedProfile() != null) {
     this.setUserType(
         response.getSelectedProfile().isLegacy() ? UserType.LEGACY : UserType.MOJANG);
   } else if (ArrayUtils.isNotEmpty(response.getAvailableProfiles())) {
     this.setUserType(
         response.getAvailableProfiles()[0].isLegacy() ? UserType.LEGACY : UserType.MOJANG);
   }
   User user = response.getUser();
   if (user != null && user.getId() != null) {
     this.setUserid(user.getId());
   } else {
     this.setUserid(this.getUsername());
   }
   this.isOnline = true;
   this.accessToken = response.getAccessToken();
   this.profiles = response.getAvailableProfiles();
   this.setSelectedProfile(response.getSelectedProfile());
   this.getModifiableUserProperties().clear();
   this.updateUserProperties(user);
 }
  private boolean needRemove(String beanName, BeanDefinition beanDefinition) {

    if (ArrayUtils.isNotEmpty(removedBeanNames)) {
      for (String removedBeanName : removedBeanNames) {
        if (beanName.equals(removedBeanName)) {
          return true;
        }
        if (beanDefinition.getBeanClassName().equals(removedBeanName)) {
          return true;
        }
      }
    }

    if (this.removedBeanProperties != null) {
      Set<String[]> propertiesSet = removedBeanProperties.get(beanName);
      if (propertiesSet != null) {
        Iterator<String[]> iter = propertiesSet.iterator();
        MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();

        while (iter.hasNext()) {
          String[] properties = iter.next();
          if (properties.length == 1) {

            // 先移除
            propertyValues.removePropertyValue(properties[0]);

            // 如果需要替换,替换掉值(只支持基本属性)
            if (this.replaceBeanProperties != null) {
              String key = beanName + "@" + properties[0];
              if (this.replaceBeanProperties.containsKey(key)) {
                propertyValues.add(properties[0], this.replaceBeanProperties.get(key));
              }
            }
          } else {
            PropertyValue propertyValue = propertyValues.getPropertyValue(properties[0]);
            if (propertyValue != null) {
              Object nextValue = propertyValue.getValue();
              // 目前只支持 二级 + 移除Map的
              if (nextValue instanceof ManagedMap) {

                TypedStringValue typedStringValue = new TypedStringValue(properties[1]);
                ((ManagedMap) nextValue).remove(typedStringValue);

                // 如果需要替换,替换掉值(只支持基本属性)
                if (this.replaceBeanProperties != null) {
                  String key = beanName + "@" + properties[0] + "@" + properties[1];
                  if (this.replaceBeanProperties.containsKey(key)) {
                    ((ManagedMap) nextValue)
                        .put(properties[1], this.replaceBeanProperties.get(key));
                  }
                }
              }
            }
          }
        }
      }
    }

    String className = beanDefinition.getBeanClassName();

    // spring data jpa
    if (className.equals("com.sishuok.es.common.repository.support.SimpleBaseRepositoryFactoryBean")
        || className.equals(
            "org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean")) {
      PropertyValue repositoryInterfaceValue =
          beanDefinition.getPropertyValues().getPropertyValue("repositoryInterface");
      if (repositoryInterfaceValue != null) {
        className = repositoryInterfaceValue.getValue().toString();
      }
    }

    if (ArrayUtils.isEmpty(this.removedClassPatterns)) {
      return false;
    }

    if (ArrayUtils.isNotEmpty(this.includeClassPatterns)) {
      for (String includeClassPattern : includeClassPatterns) {
        if (className.matches(includeClassPattern)) {
          return false;
        }
      }
    }

    for (String removedClassPattern : removedClassPatterns) {
      if (className.matches(removedClassPattern)) {
        return true;
      }
    }

    return false;
  }
 /** {@inheritDoc} */
 @Override
 public void setToFile(Integer[] value) {
   if (ArrayUtils.isNotEmpty(value)) {
     getPropertiesFile().setIntArray(getKey(), ArrayUtils.toPrimitive(value), getSpacer());
   }
 }