Beispiel #1
0
 @SuppressWarnings("unchecked")
 @Override
 public List<T> findBy(List<String> propertyNames, List<Object> values) {
   Assert.notEmpty(propertyNames);
   Assert.notEmpty(values);
   Assert.state(propertyNames.size() == values.size());
   List<Criterion> criterions = new ArrayList<Criterion>(5);
   for (int i = 0; i < propertyNames.size(); i++) {
     Criterion criterion = Restrictions.eq(propertyNames.get(i), values.get(i));
     criterions.add(criterion);
   }
   return createCriteria(criterions).list();
 }
 public ProductTag[] updateTagName(Long[] ids, String[] tagNames) {
   Assert.notEmpty(ids);
   Assert.notEmpty(tagNames);
   if (ids.length != tagNames.length) {
     throw new IllegalArgumentException("ids length not equals tagNames length");
   }
   ProductTag[] tags = new ProductTag[ids.length];
   ProductTag tag;
   for (int i = 0, len = ids.length; i < len; i++) {
     tag = findById(ids[i]);
     tag.setName(tagNames[i]);
     tags[i] = tag;
   }
   return tags;
 }
Beispiel #3
0
 @Test
 public void testGetMenuList() {
   Map<Object, Object> condition = new HashMap<Object, Object>();
   condition.put("paging", new Paging());
   condition.put("user", new User());
   Assert.notEmpty(menuDao.getMenuList(condition), "查询数据没有值");
 }
  private <T> MultiGetResponse getMultiResponse(Query searchQuery, Class<T> clazz) {

    String indexName =
        isNotEmpty(searchQuery.getIndices())
            ? searchQuery.getIndices().get(0)
            : getPersistentEntityFor(clazz).getIndexName();
    String type =
        isNotEmpty(searchQuery.getTypes())
            ? searchQuery.getTypes().get(0)
            : getPersistentEntityFor(clazz).getIndexType();

    Assert.notNull(indexName, "No index defined for Query");
    Assert.notNull(type, "No type define for Query");
    Assert.notEmpty(searchQuery.getIds(), "No Id define for Query");

    MultiGetRequestBuilder builder = client.prepareMultiGet();

    for (String id : searchQuery.getIds()) {

      MultiGetRequest.Item item = new MultiGetRequest.Item(indexName, type, id);

      if (searchQuery.getRoute() != null) {
        item = item.routing(searchQuery.getRoute());
      }

      if (searchQuery.getFields() != null && !searchQuery.getFields().isEmpty()) {
        item = item.fields(toArray(searchQuery.getFields()));
      }
      builder.add(item);
    }
    return builder.execute().actionGet();
  }
Beispiel #5
0
 /**
  * 创建Zipper对象
  *
  * @param out 输出流
  * @param filter 文件过滤,不过滤可以为null。
  * @param srcFilename 源文件名。可以有多个源文件,如果源文件是目录,那么所有子目录都将被包含。
  */
 protected Zipper(OutputStream out, List<FileEntry> fileEntrys, String encoding) {
   Assert.notEmpty(fileEntrys);
   long begin = System.currentTimeMillis();
   log.debug("开始制作压缩包");
   try {
     try {
       zipOut = new ZipOutputStream(out);
       if (!StringUtils.isBlank(encoding)) {
         log.debug("using encoding: {}", encoding);
         zipOut.setEncoding(encoding);
       } else {
         log.debug("using default encoding");
       }
       for (FileEntry fe : fileEntrys) {
         zip(fe.getFile(), fe.getFilter(), fe.getZipEntry(), fe.getPrefix());
       }
     } finally {
       zipOut.close();
     }
   } catch (IOException e) {
     throw new RuntimeException("制作压缩包时,出现IO异常!", e);
   }
   long end = System.currentTimeMillis();
   log.info("制作压缩包成功。耗时:{}ms。", end - begin);
 }
Beispiel #6
0
  /**
   * Initiate a copy operation using a command-line style (arguments are specified as {@link
   * String}s).
   *
   * @param arguments the copy arguments
   */
  public void copy(String... arguments) {
    Assert.notEmpty(arguments, "invalid number of arguments");
    // sanitize the arguments
    final List<String> parsedArguments = new ArrayList<String>();
    for (String arg : arguments) {
      parsedArguments.addAll(Arrays.asList(StringUtils.tokenizeToStringArray(arg, " ")));
    }

    try {
      if (StringUtils.hasText(user)) {
        UserGroupInformation ugi =
            UserGroupInformation.createProxyUser(user, UserGroupInformation.getLoginUser());
        ugi.doAs(
            new PrivilegedExceptionAction<Void>() {
              @Override
              public Void run() throws Exception {
                invokeCopy(
                    configuration, parsedArguments.toArray(new String[parsedArguments.size()]));
                return null;
              }
            });
      } else {
        invokeCopy(configuration, parsedArguments.toArray(new String[parsedArguments.size()]));
      }
    } catch (Exception ex) {
      throw new IllegalStateException("Cannot run distCp impersonated as '" + user + "'", ex);
    }
  }
 /**
  * Create a custom CustomAnnotationTransactionAttributeSource.
  *
  * @param annotationParsers the TransactionAnnotationParsers to use
  */
 public CustomAnnotationTransactionAttributeSource(
     Set<TransactionAnnotationParser> annotationParsers) {
   this.publicMethodsOnly = true;
   Assert.notEmpty(
       annotationParsers, "At least one TransactionAnnotationParser needs to be specified");
   this.annotationParsers = annotationParsers;
 }
 /**
  * Perform a scan within the specified base packages, returning the registered bean definitions.
  *
  * <p>This method does <i>not</i> register an annotation config processor but rather leaves this
  * up to the caller.
  *
  * @param basePackages the packages to check for annotated classes
  * @return set of beans registered if any for tooling registration purposes (never {@code null})
  */
 protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
   Assert.notEmpty(basePackages, "At least one base package must be specified");
   Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
   mylog.debug("遍历basePackages,获取包路径下面的.class所有类");
   for (String basePackage : basePackages) {
     Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
     mylog.debug("获取到有注解的bean集合并遍历,每个bean设置scope");
     for (BeanDefinition candidate : candidates) {
       ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
       candidate.setScope(scopeMetadata.getScopeName());
       String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
       if (candidate instanceof AbstractBeanDefinition) {
         postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
       }
       if (candidate instanceof AnnotatedBeanDefinition) {
         AnnotationConfigUtils.processCommonDefinitionAnnotations(
             (AnnotatedBeanDefinition) candidate);
       }
       if (checkCandidate(beanName, candidate)) {
         BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
         definitionHolder =
             AnnotationConfigUtils.applyScopedProxyMode(
                 scopeMetadata, definitionHolder, this.registry);
         beanDefinitions.add(definitionHolder);
         mylog.debug("登记AnnotatedBeanDefinition类型的bean");
         registerBeanDefinition(definitionHolder, this.registry);
       }
     }
   }
   return beanDefinitions;
 }
 /** Initialize the selector chain. Removes any existing selectors. */
 public void setSelectors(List<MessageSelector> selectors) {
   Assert.notEmpty(selectors, "selectors must not be empty");
   synchronized (this.selectors) {
     this.selectors.clear();
     this.selectors.addAll(selectors);
   }
 }
Beispiel #10
0
  @Override
  public void returns(Order order, Returns returns, Admin operator) {
    Assert.notNull(order);
    Assert.notNull(returns);
    Assert.notEmpty(returns.getReturnsItems());

    orderDao.lock(order, LockModeType.PESSIMISTIC_WRITE);

    returns.setOrder(order);
    returnsDao.persist(returns);
    for (ReturnsItem returnsItem : returns.getReturnsItems()) {
      OrderItem orderItem = order.getOrderItem(returnsItem.getSn());
      if (orderItem != null) {
        orderItemDao.lock(orderItem, LockModeType.PESSIMISTIC_WRITE);
        orderItem.setReturnQuantity(orderItem.getReturnQuantity() + returnsItem.getQuantity());
      }
    }
    if (order.getReturnQuantity() >= order.getShippedQuantity()) {
      order.setShippingStatus(ShippingStatus.returned);
    } else if (order.getReturnQuantity() > 0) {
      order.setShippingStatus(ShippingStatus.partialReturns);
    }
    order.setExpire(null);
    orderDao.merge(order);

    OrderLog orderLog = new OrderLog();
    orderLog.setType(Type.returns);
    orderLog.setOperator(operator != null ? operator.getUsername() : null);
    orderLog.setOrder(order);
    orderLogDao.persist(orderLog);
  }
 public JythonScriptFactory(String scriptSourceLocator, Class[] scriptInterfaces) {
   Assert.hasText(scriptSourceLocator);
   Assert.notEmpty(scriptInterfaces);
   this.scriptSourceLocator = scriptSourceLocator;
   this.scriptInterfaces = scriptInterfaces;
   this.arguments = null;
 }
  @Override
  public PrivateCoachInfoDto getCoachProfile(String coachId) {
    StringBuffer sql = new StringBuffer();

    sql.append("SELECT ")
        .append("s.portrait_photo as portraitPhoto, ")
        .append("CONCAT (s.given_name, ' ' ,s.surname) AS nickname, ")
        .append(
            "(SELECT position_name FROM position_title WHERE position_code = m.position_title_code) as positionTitle, ")
        .append("(CASE (s.gender) when 'F' then 'F' when 'M' then 'M' else 'N' end) as sex, ")
        .append("s.date_of_birth as dateOfBirth, ")
        .append(
            "(SELECT code_display FROM sys_code where category = 'nationality' and code_value = s.nationality) as nationality, ")
        .append("c.personal_info as qualification, ")
        .append("c.speciality ")
        .append("FROM ")
        .append("user_master u ")
        .append("LEFT JOIN ")
        .append("staff_profile s ON (s.user_id = u.user_id) ")
        .append("LEFT JOIN ")
        .append("staff_master m ON (u.user_id = m.user_id) ")
        .append("LEFT JOIN ")
        .append("staff_coach_info c ON (c.user_id = u.user_id) ")
        .append("WHERE ")
        .append("u.user_id = '")
        .append(coachId)
        .append("'");

    List<PrivateCoachInfoDto> dtoList =
        this.getDtoBySql(sql.toString(), null, PrivateCoachInfoDto.class);
    Assert.notEmpty(dtoList, "No such coach");
    Assert.isTrue(dtoList.size() == 1, "More than one coach have the same coach id");
    return dtoList.get(0);
  }
Beispiel #13
0
  /**
   * Genera un pago para el grupo de cargos indicado
   *
   * @param c
   * @param cargos
   * @return
   */
  public PagoM crearPago(final Cliente c, final List<NotaDeCredito> cargos) {
    Assert.notEmpty(cargos, "La collecion de cargos debe tener elementos");
    final PagoM pago = new PagoM();
    pago.setCliente(c);
    pago.setClave(c.getClave());
    pago.setTipoDeDocumento("M");
    CollectionUtils.forAllDo(
        cargos,
        new Closure() {

          public void execute(Object input) {
            NotaDeCredito cargo = (NotaDeCredito) input;
            Pago p = new Pago();
            p.setCliente(pago.getCliente());
            p.setClave(pago.getClave());
            p.setPagoM(pago);
            p.setNota(cargo);
            pago.getPagos().add(p);

            p.setOrigen(cargo.getOrigen());
            p.setTipoDocto(cargo.getTipo());
            p.setNumero(cargo.getNumero());
            p.setSucursal(1);
          }
        });
    return pago;
  }
 /**
  * Set the names of the beans that should automatically get wrapped with proxies. A name can
  * specify a prefix to match by ending with "*", e.g. "myBean,tx*" will match the bean named
  * "myBean" and all beans whose name start with "tx".
  *
  * <p><b>NOTE:</b> In case of a FactoryBean, only the objects created by the FactoryBean will get
  * proxied. This default behavior applies as of Spring 2.0. If you intend to proxy a FactoryBean
  * instance itself (a rare use case, but Spring 1.2's default behavior), specify the bean name of
  * the FactoryBean including the factory-bean prefix "&": e.g. "&myFactoryBean".
  *
  * @see org.springframework.beans.factory.FactoryBean
  * @see org.springframework.beans.factory.BeanFactory#FACTORY_BEAN_PREFIX
  */
 public void setBeanNames(String... beanNames) {
   Assert.notEmpty(beanNames, "'beanNames' must not be empty");
   this.beanNames = new ArrayList<String>(beanNames.length);
   for (String mappedName : beanNames) {
     this.beanNames.add(StringUtils.trimWhitespace(mappedName));
   }
 }
  public AbstractStompEndpointRegistration(
      String[] paths, WebSocketHandler webSocketHandler, TaskScheduler sockJsTaskScheduler) {

    Assert.notEmpty(paths, "No paths specified");
    this.paths = paths;
    this.wsHandler = webSocketHandler;
    this.sockJsTaskScheduler = sockJsTaskScheduler;
  }
 /**
  * Set the regular expressions defining methods to match for exclusion. Matching will be the union
  * of all these; if any match, the pointcut matches.
  */
 public void setExcludedPatterns(String[] excludedPatterns) {
   Assert.notEmpty(excludedPatterns, "'excludedPatterns' must not be empty");
   this.excludedPatterns = new String[excludedPatterns.length];
   for (int i = 0; i < excludedPatterns.length; i++) {
     this.excludedPatterns[i] = StringUtils.trimWhitespace(excludedPatterns[i]);
   }
   initExcludedPatternRepresentation(this.excludedPatterns);
 }
 /**
  * Provide the map of {@link HeaderValueMessageProcessor} to evaluate when enriching the target
  * MessageHeaders. The keys should simply be header names, and the values should be Expressions
  * that will evaluate against the reply Message as the root object.
  *
  * @param headerExpressions The header expressions.
  */
 public void setHeaderExpressions(Map<String, HeaderValueMessageProcessor<?>> headerExpressions) {
   Assert.notEmpty(headerExpressions, "headerExpressions must not be empty");
   Assert.noNullElements(
       headerExpressions.keySet().toArray(), "headerExpressions keys must not be empty");
   Assert.noNullElements(
       headerExpressions.values().toArray(), "headerExpressions values must not be empty");
   this.headerExpressions = new HashMap<String, HeaderValueMessageProcessor<?>>(headerExpressions);
 }
Beispiel #18
0
 /**
  * Create a custom AnnotationCacheOperationSource.
  *
  * @param annotationParsers the CacheAnnotationParser to use
  */
 public AnnotationCacheOperationSource(CacheAnnotationParser... annotationParsers) {
   this.publicMethodsOnly = true;
   Assert.notEmpty(annotationParsers, "At least one CacheAnnotationParser needs to be specified");
   Set<CacheAnnotationParser> parsers =
       new LinkedHashSet<CacheAnnotationParser>(annotationParsers.length);
   Collections.addAll(parsers, annotationParsers);
   this.annotationParsers = parsers;
 }
 /**
  * Set the regular expressions defining methods to match. Matching will be the union of all these;
  * if any match, the pointcut matches.
  */
 public void setPatterns(String[] patterns) {
   Assert.notEmpty(patterns, "'patterns' must not be empty");
   this.patterns = new String[patterns.length];
   for (int i = 0; i < patterns.length; i++) {
     this.patterns[i] = StringUtils.trimWhitespace(patterns[i]);
   }
   initPatternRepresentation(this.patterns);
 }
Beispiel #20
0
 @SuppressWarnings("unchecked")
 public void delete(PK[] ids) {
   Assert.notEmpty(ids, "ids must not be empty");
   for (PK id : ids) {
     T entity = (T) getSession().load(entityClass, id);
     getSession().delete(entity);
   }
 }
Beispiel #21
0
  @JsonIgnore
  public List<Item> getOnLoanItemsFilterByItemCategoriesAndSmds(
      List<ItemCategory> itemCategoryList, List<SMD> smdList) {
    logger.debug(
        "Entering getOnLoanItemsFilterByItemCategoriesAndSmds(itemCategoryList={}, smdList={})",
        new Object[] {itemCategoryList, smdList});
    Assert.notEmpty(itemCategoryList);
    Assert.notEmpty(smdList);

    List<Item> onLoanItems =
        itemRepo.findByPatronAndItemStatusAndItemCategoryAndSmd(
            this, getCirculatedItemStatusList(), itemCategoryList, smdList, null);

    logger.debug(
        "Leaving getOnLoanItemsFilterByItemCategoriesAndSmds(). onLoanItems={}", onLoanItems);
    return onLoanItems;
  }
 @Override
 public DefaultDataBuffer write(ByteBuffer... byteBuffers) {
   Assert.notEmpty(byteBuffers, "'byteBuffers' must not be empty");
   int extraCapacity = Arrays.stream(byteBuffers).mapToInt(ByteBuffer::remaining).sum();
   ensureExtraCapacity(extraCapacity);
   Arrays.stream(byteBuffers)
       .forEach(byteBuffer -> writeInternal(buffer -> buffer.put(byteBuffer)));
   return this;
 }
 /**
  * Create an instance with the given ContentNegotiationStrategy instances.
  *
  * <p>Each instance is checked to see if it is also an implementation of
  * MediaTypeFileExtensionResolver, and if so it is registered as such.
  *
  * @param strategies one more more ContentNegotiationStrategy instances
  */
 public ContentNegotiationManager(ContentNegotiationStrategy... strategies) {
   Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected");
   this.contentNegotiationStrategies.addAll(Arrays.asList(strategies));
   for (ContentNegotiationStrategy strategy : this.contentNegotiationStrategies) {
     if (strategy instanceof MediaTypeFileExtensionResolver) {
       this.fileExtensionResolvers.add((MediaTypeFileExtensionResolver) strategy);
     }
   }
 }
  /**
   * @throws Exception
   * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
   */
  public void afterPropertiesSet() throws Exception {
    Assert.notEmpty(
        getGroupList(),
        "The property groupList in class "
            + this.getClass().getSimpleName()
            + " must not be null and not empty.");

    this.setAsText(getGroupList());
  }
 @SuppressWarnings("unchecked")
 HttpMessageConverterExtractor(
     Type responseType, List<HttpMessageConverter<?>> messageConverters, Log logger) {
   Assert.notNull(responseType, "'responseType' must not be null");
   Assert.notEmpty(messageConverters, "'messageConverters' must not be empty");
   this.responseType = responseType;
   this.responseClass = (responseType instanceof Class) ? (Class<T>) responseType : null;
   this.messageConverters = messageConverters;
   this.logger = logger;
 }
 /**
  * Create a custom CustomAnnotationTransactionAttributeSource.
  *
  * @param annotationParsers the TransactionAnnotationParsers to use
  */
 public CustomAnnotationTransactionAttributeSource(
     TransactionAnnotationParser... annotationParsers) {
   this.publicMethodsOnly = true;
   Assert.notEmpty(
       annotationParsers, "At least one TransactionAnnotationParser needs to be specified");
   Set<TransactionAnnotationParser> parsers =
       new LinkedHashSet<TransactionAnnotationParser>(annotationParsers.length);
   Collections.addAll(parsers, annotationParsers);
   this.annotationParsers = parsers;
 }
  @Override
  protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Assert.notEmpty(basePackages, "At least one base package must be specified");
    Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
    for (String basePackage : basePackages) {
      Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
      for (BeanDefinition candidate : candidates) {
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
        candidate.setScope(scopeMetadata.getScopeName());
        String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
        if (candidate instanceof AbstractBeanDefinition) {
          postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
        }
        if (candidate instanceof AnnotatedBeanDefinition) {
          processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
        }

        ScannedGenericBeanDefinition bd = (ScannedGenericBeanDefinition) candidate; // 通用bean扫描
        bd.setBeanClassName(HessianServiceExporter.class.getName()); // 设置bean名称
        bd.setBeanClass(HessianServiceExporter.class); // 设置bean类
        bd.getPropertyValues().add("service", registry.getBeanDefinition(beanName)); // 设置属性 service
        String[] interfaces = bd.getMetadata().getInterfaceNames(); // 获得元数据、接口名称

        if (interfaces == null || interfaces.length == 0) continue;
        Class interf = null;
        try {
          interf = Class.forName(interfaces[0]); // 获得接口
        } catch (ClassNotFoundException e) {
          continue;
        }
        bd.getPropertyValues().add("serviceInterface", interf); // 设置属性 serviceInterface
        candidate = bd;
        BeanDefinitionHolder definitionHolder =
            new BeanDefinitionHolder(candidate, "/" + beanName); // 新bean定义持有
        definitionHolder =
            applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); // 应用范围代理模式
        beanDefinitions.add(definitionHolder); // 将bean定义持有放入bean定义持有set中
        registerBeanDefinition(definitionHolder, this.registry); // 注册bean定义
      }
    }

    if (beanDefinitions.isEmpty()) {
      System.out.println("not service be scaned");
    } else {
      for (BeanDefinitionHolder holder : beanDefinitions) {
        AnnotatedBeanDefinition definition =
            (AnnotatedBeanDefinition) holder.getBeanDefinition(); // 注释的bean定义
        System.out.println("service:" + holder.getBeanName()); // 注释的bean定义名称
        System.out.println(
            "service:" + definition.getMetadata().getAnnotationTypes()); // 注释的bean定义类型
      }
    }

    return beanDefinitions;
  }
 @Test
 public void testGetUserRoleList() {
   Assert.notNull(client);
   User u = new User();
   u.setId(1L);
   List<Role> list = client.getUserRoleList(u);
   Assert.notEmpty(list);
   for (Role r : list) {
     logger.info("role name: " + r.getName());
   }
 }
 // TODO: Extract this into some utility, as it comes in handy in several places
 private String join(String... strings) {
   Assert.notEmpty(strings);
   StringBuilder builder = new StringBuilder();
   builder.append(strings[0]);
   if (strings.length > 1) {
     for (int i = 1; i < strings.length; i++) {
       builder.append(",").append(strings[i]);
     }
   }
   return builder.toString();
 }
 public JythonScriptFactory(
     String scriptSourceLocator, Class[] scriptInterfaces, Object[] arguments) {
   Assert.hasText(scriptSourceLocator);
   Assert.notEmpty(scriptInterfaces);
   this.scriptSourceLocator = scriptSourceLocator;
   this.scriptInterfaces = scriptInterfaces;
   if (arguments == null || arguments.length == 0) {
     this.arguments = null;
   } else {
     this.arguments = arguments;
   }
 }