Java Code Examples for org.springframework.util.CollectionUtils

The following are top voted examples for showing how to use org.springframework.util.CollectionUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: otter-G   File: ProcessTimeoutRuleMonitor.java   Source Code and License 7 votes vote down vote up
@Override
public void explore(List<AlarmRule> rules) {
    if (CollectionUtils.isEmpty(rules)) {
        return;
    }
    Long pipelineId = rules.get(0).getPipelineId();

    List<ProcessStat> processStats = processStatService.listRealtimeProcessStat(pipelineId);
    if (CollectionUtils.isEmpty(processStats)) {
        return;
    }

    long now = System.currentTimeMillis();
    Map<Long, Long> processTime = new HashMap<Long, Long>();
    for (ProcessStat processStat : processStats) {
        Long timeout = 0L;
        if (!CollectionUtils.isEmpty(processStat.getStageStats())) {
            timeout = now - processStat.getStageStats().get(0).getStartTime();
        }
        processTime.put(processStat.getProcessId(), timeout);
    }

    String message = StringUtils.EMPTY;
    for (AlarmRule rule : rules) {
        if (message.isEmpty()) {
            message = checkTimeout(rule, processTime);
        } else {
            checkTimeout(rule, processTime);
        }
    }

    if (!message.isEmpty()) {
        logRecordAlarm(pipelineId, MonitorName.PROCESSTIMEOUT, message);
    }

}
 
Example 2
Project: gemini.blueprint   File: CommonsLogging104Test.java   Source Code and License 7 votes vote down vote up
protected String[] getTestFrameworkBundlesNames() {
	String[] bundles = super.getTestFrameworkBundlesNames();

	// remove slf4j
	Collection bnds = new ArrayList(bundles.length);
	CollectionUtils.mergeArrayIntoCollection(bundles, bnds);

	for (Iterator iterator = bnds.iterator(); iterator.hasNext();) {
		String object = (String) iterator.next();
		// remove slf4j
		if (object.startsWith("org.slf4j"))
			iterator.remove();
	}
	// add commons logging
	bnds.add("org.eclipse.bundles,commons-logging,20070611");

	return (String[]) bnds.toArray(new String[bnds.size()]);
}
 
Example 3
Project: spring-security-oauth2-boot   File: DefaultUserInfoRestTemplateFactory.java   Source Code and License 6 votes vote down vote up
@Override
public OAuth2RestTemplate getUserInfoRestTemplate() {
	if (this.oauth2RestTemplate == null) {
		this.oauth2RestTemplate = createOAuth2RestTemplate(
				this.details == null ? DEFAULT_RESOURCE_DETAILS : this.details);
		this.oauth2RestTemplate.getInterceptors()
				.add(new AcceptJsonRequestInterceptor());
		AuthorizationCodeAccessTokenProvider accessTokenProvider = new AuthorizationCodeAccessTokenProvider();
		accessTokenProvider.setTokenRequestEnhancer(new AcceptJsonRequestEnhancer());
		this.oauth2RestTemplate.setAccessTokenProvider(accessTokenProvider);
		if (!CollectionUtils.isEmpty(this.customizers)) {
			AnnotationAwareOrderComparator.sort(this.customizers);
			for (UserInfoRestTemplateCustomizer customizer : this.customizers) {
				customizer.customize(this.oauth2RestTemplate);
			}
		}
	}
	return this.oauth2RestTemplate;
}
 
Example 4
Project: summer-mqtt   File: TopicSubscriptionHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Finds the {@link TopicSubscription} object from the {@code topicSubscriptions} list that
 * matches the {@code topicFilter}.
 * <p>
 * The search on the {@code topicFilter} is case-sensitive. If a matching
 * {@link TopicSubscription} value could not be found, a null value will be returned.
 * 
 * @param topicFilter the Topic Filter to search for
 * @param topicSubscriptions a {@link List} of {@link TopicSubscription} objects for search
 * 
 * @return a {@link TopicSubscription} object, or null if not found
 */
public static TopicSubscription findByTopicFilter(final String topicFilter,
    List<TopicSubscription> topicSubscriptions)
{
    TopicSubscription record = null;
    if (StringUtils.hasText(topicFilter)
        && !CollectionUtils.isEmpty(topicSubscriptions))
    {
        for (TopicSubscription topicSubscription : topicSubscriptions)
        {
            if (topicSubscription.getTopicFilter().equals(topicFilter))
            {
                record = topicSubscription;
                break;
            }
        }
    }
    return record;
}
 
Example 5
Project: common-dao   File: SelectSupport.java   Source Code and License 6 votes vote down vote up
public <T> T selectByPrimaryKey(Object primaryKey, Class<T> entityClass) {
    Entity entity=getEntity(entityClass);
    Entity.Column primaryKeyColumn=entity.getPrimaryKey();
    if (primaryKey == null) {
        throw new RuntimeException("没有指定主键");
    }
    final StringBuilder sql = new StringBuilder();
    sql.append(SqlHelper.selectFromTable(entity.getTableName()));
    sql.append(SqlHelper.whereClause(Collections.singleton(primaryKeyColumn)));
    System.out.println(sql.toString());
    List<T> resultList=jdbcTemplate.query(sql.toString(), new MapSqlParameterSource(primaryKeyColumn.getName(), primaryKey), new BeanPropertyRowMapper<>(entityClass));
    if (!CollectionUtils.isEmpty(resultList)) {
        return resultList.get(0);
    }
    return null;
}
 
Example 6
Project: otter-G   File: TerminMonitor.java   Source Code and License 6 votes vote down vote up
private synchronized void initTermin(List<String> termins) {
    if (CollectionUtils.isEmpty(termins)) {
        return;
    }

    List<Long> processIds = new ArrayList<Long>(termins.size());
    for (String termin : termins) {
        processIds.add(StagePathUtils.getProcessId(termin));
    }
    // 排序一下
    Collections.sort(processIds);
    for (Long processId : processIds) {
        boolean successed = waitProcessIds.offer(processId);
        if (successed && logger.isDebugEnabled()) {
            logger.debug("## {} add termin id [{}]", getPipelineId(), processId);
        }
    }
}
 
Example 7
Project: ukubuka-core   File: FileRecord.java   Source Code and License 6 votes vote down vote up
/********************************* Override(s) ********************************/
@Override
public boolean equals(Object object) {
    if (object == this)
        return true;
    if (!(object instanceof FileRecord)) {
        return false;
    }

    /* Cast FileRecord */
    FileRecord fileRecord = (FileRecord) object;

    /* Empty List */
    if (CollectionUtils.isEmpty(this.getData())
            || CollectionUtils.isEmpty(fileRecord.getData())) {
        return false;
    }

    /* Check Whether Equal */
    return fileRecord.getData().toString()
            .equals(this.getData().toString());
}
 
Example 8
Project: apollo-custom   File: FileTextResolver.java   Source Code and License 6 votes vote down vote up
@Override
public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) {
  ItemChangeSets changeSets = new ItemChangeSets();
  if (StringUtils.isEmpty(configText)) {
    return changeSets;
  }
  if (CollectionUtils.isEmpty(baseItems)) {
    changeSets.addCreateItem(createItem(namespaceId, 0, configText));
  } else {
    ItemDTO beforeItem = baseItems.get(0);
    if (!configText.equals(beforeItem.getValue())) {//update
      changeSets.addUpdateItem(createItem(namespaceId, beforeItem.getId(), configText));
    }
  }

  return changeSets;
}
 
Example 9
Project: apollo-custom   File: ReleaseMessageServiceWithCache.java   Source Code and License 6 votes vote down vote up
private void loadReleaseMessages(long startId) {
  boolean hasMore = true;
  while (hasMore && !Thread.currentThread().isInterrupted()) {
    //current batch is 500
    List<ReleaseMessage> releaseMessages = releaseMessageRepository
        .findFirst500ByIdGreaterThanOrderByIdAsc(startId);
    if (CollectionUtils.isEmpty(releaseMessages)) {
      break;
    }
    releaseMessages.forEach(this::mergeReleaseMessage);
    int scanned = releaseMessages.size();
    startId = releaseMessages.get(scanned - 1).getId();
    hasMore = scanned == 500;
    logger.info("Loaded {} release messages with startId {}", scanned, startId);
  }
}
 
Example 10
Project: SpringBoot_Wechat_Sell   File: OrderServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public OrderDTO findOne(String orderId) {

    OrderMaster orderMaster = orderMasterRepository.findOne(orderId);
    if (orderMaster == null) {
        throw new SellException(ResultEnum.ORDER_NOT_EX);
    }

    List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
    if (CollectionUtils.isEmpty(orderDetailList)) {
        throw new SellException(ResultEnum.ORDERDETAIL_NOT_EXIST);
    }

    OrderDTO orderDTO = new OrderDTO();
    BeanUtils.copyProperties(orderMaster, orderDTO);
    orderDTO.setOrderDetailList(orderDetailList);

    return orderDTO;
}
 
Example 11
Project: apollo-custom   File: PermissionController.java   Source Code and License 6 votes vote down vote up
@PreAuthorize(value = "@permissionValidator.hasAssignRolePermission(#appId)")
@RequestMapping(value = "/apps/{appId}/roles/{roleType}", method = RequestMethod.POST)
public ResponseEntity<Void> assignAppRoleToUser(@PathVariable String appId, @PathVariable String roleType,
                                                @RequestBody String user) {
  checkUserExists(user);
  RequestPrecondition.checkArgumentsNotEmpty(user);

  if (!RoleType.isValidRoleType(roleType)) {
    throw new BadRequestException("role type is illegal");
  }
  Set<String> assignedUsers = rolePermissionService.assignRoleToUsers(RoleUtils.buildAppRoleName(appId, roleType),
      Sets.newHashSet(user), userInfoHolder.getUser().getUserId());
  if (CollectionUtils.isEmpty(assignedUsers)) {
    throw new BadRequestException(user + "已授权");
  }

  return ResponseEntity.ok().build();
}
 
Example 12
Project: xxpay-master   File: RefundOrderController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("/list")
@ResponseBody
public String list(@ModelAttribute RefundOrder refundOrder, Integer pageIndex, Integer pageSize) {
    PageModel pageModel = new PageModel();
    int count = refundOrderService.count(refundOrder);
    if(count <= 0) return JSON.toJSONString(pageModel);
    List<RefundOrder> refundOrderList = refundOrderService.getRefundOrderList((pageIndex-1)*pageSize, pageSize, refundOrder);
    if(!CollectionUtils.isEmpty(refundOrderList)) {
        JSONArray array = new JSONArray();
        for(RefundOrder po : refundOrderList) {
            JSONObject object = (JSONObject) JSONObject.toJSON(po);
            if(po.getCreateTime() != null) object.put("createTime", DateUtil.date2Str(po.getCreateTime()));
            if(po.getRefundAmount() != null) object.put("amount", AmountUtil.convertCent2Dollar(po.getRefundAmount()+""));
            array.add(object);
        }
        pageModel.setList(array);
    }
    pageModel.setCount(count);
    pageModel.setMsg("ok");
    pageModel.setRel(true);
    return JSON.toJSONString(pageModel);
}
 
Example 13
Project: ukubuka-core   File: UkubukaBaseParser.java   Source Code and License 6 votes vote down vote up
/**
 * Get File Contents
 * 
 * @param fileContent
 * @return File Contents
 */
public FileContents getFileContents(final List<String> fileContent) {
    FileContents fileContents = new FileContents();

    /* Set Header */
    fileContents.setHeader(new ArrayList<>(Arrays.asList(fileContent
            .remove(0).split(Constants.DEFAULT_FILE_DELIMITER))));

    /* Set Data */
    List<FileRecord> fileData = new ArrayList<>();
    while (!CollectionUtils.isEmpty(fileContent)) {
        fileData.add(new FileRecord(
                new ArrayList<>(Arrays.asList(fileContent.remove(0)
                        .split(Constants.DEFAULT_FILE_DELIMITER)))));
    }
    fileContents.setData(fileData);

    /* Return File Contents */
    return fileContents;
}
 
Example 14
Project: apollo-custom   File: GrayReleaseRulesHolder.java   Source Code and License 6 votes vote down vote up
private void scanGrayReleaseRules() {
  long maxIdScanned = 0;
  boolean hasMore = true;

  while (hasMore && !Thread.currentThread().isInterrupted()) {
    List<GrayReleaseRule> grayReleaseRules = grayReleaseRuleRepository
        .findFirst500ByIdGreaterThanOrderByIdAsc(maxIdScanned);
    if (CollectionUtils.isEmpty(grayReleaseRules)) {
      break;
    }
    mergeGrayReleaseRules(grayReleaseRules);
    int rulesScanned = grayReleaseRules.size();
    maxIdScanned = grayReleaseRules.get(rulesScanned - 1).getId();
    //batch is 500
    hasMore = rulesScanned == 500;
  }
}
 
Example 15
Project: xxpay-master   File: TransOrderController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("/list")
@ResponseBody
public String list(@ModelAttribute TransOrder transOrder, Integer pageIndex, Integer pageSize) {
    PageModel pageModel = new PageModel();
    int count = transOrderService.count(transOrder);
    if(count <= 0) return JSON.toJSONString(pageModel);
    List<TransOrder> transOrderList = transOrderService.getTransOrderList((pageIndex-1)*pageSize, pageSize, transOrder);
    if(!CollectionUtils.isEmpty(transOrderList)) {
        JSONArray array = new JSONArray();
        for(TransOrder po : transOrderList) {
            JSONObject object = (JSONObject) JSONObject.toJSON(po);
            if(po.getCreateTime() != null) object.put("createTime", DateUtil.date2Str(po.getCreateTime()));
            if(po.getAmount() != null) object.put("amount", AmountUtil.convertCent2Dollar(po.getAmount()+""));
            array.add(object);
        }
        pageModel.setList(array);
    }
    pageModel.setCount(count);
    pageModel.setMsg("ok");
    pageModel.setRel(true);
    return JSON.toJSONString(pageModel);
}
 
Example 16
Project: jaffa-framework   File: PersistentConfig.java   Source Code and License 6 votes vote down vote up
/**
 * Add all LifecycleHandlers to the input handler.
 */
private void registerLifecycleHandlers(Persistent persistent) {

    // register all handlers to fire before the target handler
    List<ILifecycleHandler> prependHandlers = lifecycleHandlerFactory.getPrependedHandlers(persistent);
    if (!CollectionUtils.isEmpty(prependHandlers)) {
        persistent.prependLifecycleHandlers(prependHandlers);
    }

    // register the target handler - this must always happen, even if this build has no factory defined
    persistent.getLifecycleHandlers().add(persistent);

    // register all handlers to fire after the target handler
    List<ILifecycleHandler> appendHandlers = lifecycleHandlerFactory.getAppendedHandlers(persistent);
    if (!CollectionUtils.isEmpty(appendHandlers)) {
        persistent.appendLifecycleHandlers(appendHandlers);
    }
}
 
Example 17
Project: apollo-custom   File: RetryableRestTemplate.java   Source Code and License 6 votes vote down vote up
private List<ServiceDTO> getAdminServices(Env env, Transaction ct) {

    List<ServiceDTO> services = adminServiceAddressLocator.getServiceList(env);

    if (CollectionUtils.isEmpty(services)) {
      ServiceException e = new ServiceException(String.format("No available admin server."
                                                              + " Maybe because of meta server down or all admin server down. "
                                                              + "Meta server address: %s",
                                                              MetaDomainConsts.getDomain(env)));
      ct.setStatus(e);
      ct.complete();
      throw e;
    }

    return services;
  }
 
Example 18
Project: backbone   File: WebMvcApplicationConfig.java   Source Code and License 6 votes vote down vote up
protected Resource[] getPropsResources(ResourceLoader resourceLoader) {
    PropertySource sourceAnnotation = WebMvcApplicationConfig.class.getAnnotation(PropertySource.class);
    String[] props = sourceAnnotation.value();
    if (props.length > 0) {
        List<Resource> list = new ArrayList<Resource>(1);
        for (String prop : props) {
            Resource resource = resourceLoader.getResource(prop);
            if (resource.exists())
                list.add(resource);
        }
        if (!CollectionUtils.isEmpty(list)) {
            Resource[] resources = new Resource[list.size()];
            list.toArray(resources);
            //print log
            printLog(Global.BEAN_NAME_ROOT_PROPS, resources);

            return resources;
        }
   }
    return null;
}
 
Example 19
Project: jsf-core   File: ScanNodeStatusServiceImpl.java   Source Code and License 5 votes vote down vote up
/**
 * 逻辑删除死亡的client
 * @param ins
 * @throws Exception 
 */
private boolean tagClientToDel(InsVo ins) throws Exception {

	List<Client> clientList = ins.clientList;
	List<Client> deletaClientList = new ArrayList<Client>();
	if (!CollectionUtils.isEmpty(clientList)) {
		for (Client client : clientList) {
			//如果有反注册,就不逻辑删除了
			if (client.getStatus() == InstanceStatus.unreg.value().intValue()) {
				continue;
			}
			deletaClientList.add(client);
		}
	}
    scanClientManager.tagClientToDel(deletaClientList);
    logger.info("insKey: {}, tagClientToDel: {}", ins.ins.getInsKey(), getClientUniqKeyListString(deletaClientList));
    return true;
}
 
Example 20
Project: spring-boot-gae   File: SearchAutoConfiguration.java   Source Code and License 5 votes vote down vote up
/**
 * Gather all the {@link SearchConfigurer} beans registered with the container.
 * These will be used to configure the beans created here.
 *
 * @param configurers Registered {@link SearchConfigurer} list.
 */
@Autowired(required = false)
public void setConfigurers(List<SearchConfigurer> configurers) {
    if (!CollectionUtils.isEmpty(configurers)) {
        this.configurers = configurers;
    }
}
 
Example 21
Project: spring-webflux-microservices-boilerplate   File: LimitFilter.java   Source Code and License 5 votes vote down vote up
@Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
  ServerHttpRequest request = exchange.getRequest();
  final String LIMIT_KEY = "Limit-Key";
  List<String> limitKeyHeaders = request.getHeaders().get(LIMIT_KEY);
  if (!CollectionUtils.isEmpty(limitKeyHeaders) && StringUtils.isNotBlank(limitKeyHeaders.get(0))
      && !limit(new RequestLimit(RemoteAddressUtils.getRealIp(request),
      request.getURI().getPath(),
      limitKeyHeaders.get(0),
      requestBean.getRange(),
      requestBean.getCount()))) {
    exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
    return Mono.empty();
  }
  return chain.filter(exchange);
}
 
Example 22
Project: trioAop   File: Sl4jLoggerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void logger(RunTimeContext runTimeContext, LoggerConfig loggerConfig, String targetTime) {
	List<LoggerOne> list = loggerConfig.getLoggerList();
	if (!CollectionUtils.isEmpty(list)) {
		for (LoggerOne loggerOne : list) {
			logger(loggerOne.getLevel(), loggerOne.getName(), loggerOne.getInfo(), runTimeContext.getThrowable());
		}
	}
}
 
Example 23
Project: jsf-core   File: JsfRegAddrServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String getAllUrl() {
	Set<String> set = new HashSet<String>();
	List<JsfRegAddr> addrs = (List<JsfRegAddr>) this.listAll();
	if(!CollectionUtils.isEmpty(addrs)){
		for(JsfRegAddr addr : addrs){
			set.add(addr.getIp()+":"+addr.getPort());
		}
	}
	addrs = null;
	return Joiner.on(";").join(set);
}
 
Example 24
Project: spring-i18n-support   File: SimpleJdbcMessageSourceDao.java   Source Code and License 5 votes vote down vote up
@Override
public MessageResource findTopByCodeAndLang(String code, String lang) {
	List<MessageResource> byCodeAndLang = findByCodeAndLang(code, lang);
	if (CollectionUtils.isEmpty(byCodeAndLang)) {
		return null;
	}
	return byCodeAndLang.get(0);
}
 
Example 25
Project: jsf-core   File: SubscribeHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 从iface列表中获取ifaceAlias列表
 * @param list
 * @return
 */
public List<IfaceAliasVersion> getIfaceAliasList(List<InterfaceInfo> list) {
	List<IfaceAliasVersion> ifaceAliasList = new ArrayList<IfaceAliasVersion>();
	if (!CollectionUtils.isEmpty(list)) {
		for (InterfaceInfo iface : list) {
			if (!CollectionUtils.isEmpty(iface.getVersionList())) {
				ifaceAliasList.addAll(iface.getVersionList());
			}
		}
	}
	return ifaceAliasList;
}
 
Example 26
Project: otter-G   File: DbLoadDumper.java   Source Code and License 5 votes vote down vote up
public static String dumpEventDatas(List<EventData> eventDatas) {
    if (CollectionUtils.isEmpty(eventDatas)) {
        return StringUtils.EMPTY;
    }

    // 预先设定容量大小
    StringBuilder builder = new StringBuilder(event_default_capacity * eventDatas.size());
    for (EventData data : eventDatas) {
        builder.append(dumpEventData(data));
    }
    return builder.toString();
}
 
Example 27
Project: backbone   File: AnnotationBasedProcessorInterceptor.java   Source Code and License 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    List<? extends HandlerInterceptor> interceptors = getInterceptors(request, handler);
    if (!CollectionUtils.isEmpty(interceptors)) {
        for (HandlerInterceptor interceptor : interceptors) {
            boolean ret = interceptor.preHandle(request, response, handler);
            if (!ret) return false;
        }
    }
    return true;
}
 
Example 28
Project: lams   File: ServletConfigPropertySource.java   Source Code and License 5 votes vote down vote up
@Override
public String[] getPropertyNames() {
	return CollectionUtils.toArray(
			this.source.getInitParameterNames(), EMPTY_NAMES_ARRAY);
}
 
Example 29
Project: rocketmq-spring-boot-starter   File: MQConsumerAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@PostConstruct
public void init() throws Exception {
    Map<String, Object> beans = applicationContext.getBeansWithAnnotation(MQConsumer.class);
    if(!CollectionUtils.isEmpty(beans) && mqProperties.getTraceEnabled()) {
        initAsyncAppender();
    }
    for (Map.Entry<String, Object> entry : beans.entrySet()) {
        publishConsumer(entry.getKey(), entry.getValue());
    }
}
 
Example 30
Project: otter-G   File: DelayStatRuleMonitor.java   Source Code and License 5 votes vote down vote up
@Override
public void explore(List<AlarmRule> rules) {
    if (CollectionUtils.isEmpty(rules)) {
        return;
    }

    // 进入到监控项级别的rule,pipelineId一定是相同的
    Long pipelineId = rules.get(0).getPipelineId();
    DelayStat delayStat = delayStatService.findRealtimeDelayStat(pipelineId);
    Long delayTime = 0L; // seconds
    Long delayUpdate = 0L;
    if (delayStat.getDelayTime() != null) {
        delayTime = delayStat.getDelayTime() / 1000;
    }
    if (delayStat.getGmtCreate() != null) {
        delayUpdate = (new Date().getTime() - delayStat.getGmtCreate().getTime()) / 1000;
    }

    boolean delayTimeFlag = false;
    boolean delayUpdateFlag = false;
    for (AlarmRule rule : rules) {
        if (rule.getMonitorName().isDelayTime()) {
            delayTimeFlag |= checkDelayTime(rule, delayTime);
            if (delayTimeFlag) { //如果出现超时,再check下是否因为最后更新时间过久了
                delayUpdateFlag |= checkDelayTime(rule, delayUpdate);//检查delay统计的最后更新时间,这也做为delay监控的一部分
            }
        }
    }

    if (delayTimeFlag && !delayUpdateFlag) {
        logRecordAlarm(pipelineId, MonitorName.DELAYTIME, String.format(DELAY_TIME_MESSAGE, pipelineId, delayTime));
    } else if (delayTimeFlag && delayUpdateFlag) {
        logRecordAlarm(pipelineId, MonitorName.DELAYTIME,
                       String.format(DELAY_TIME_UPDATE_MESSAGE, pipelineId, delayTime, delayUpdate));
    } else if (delayUpdateFlag) {
        logRecordAlarm(pipelineId, MonitorName.DELAYTIME,
                       String.format(DELAY_UPDATE_MESSAGE, pipelineId, delayUpdate));
    }
}
 
Example 31
Project: otter-G   File: DbLoadAction.java   Source Code and License 5 votes vote down vote up
private void doDryRun(DbLoadContext context, List<List<EventData>> totalRows, boolean canBatch) {
    for (List<EventData> rows : totalRows) {
        if (CollectionUtils.isEmpty(rows)) {
            continue; // 过滤空记录
        }

        for (EventData row : rows) {
            processStat(row, context);// 直接记录成功状态
        }

        context.getProcessedDatas().addAll(rows);
    }
}
 
Example 32
Project: bootstrap   File: RestRepositoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Transactional
public int deleteAll(final Collection<K> identifiers) {
	if (org.apache.commons.collections4.CollectionUtils.isEmpty(identifiers)) {
		return 0;
	}
	return em.createQuery(String.format(DELETE_ALL_IN, ei.getEntityName())).setParameter("ids", identifiers).executeUpdate();
}
 
Example 33
Project: lams   File: HierarchicalUriComponents.java   Source Code and License 5 votes vote down vote up
/**
 * Package-private constructor. All arguments are optional, and can be {@code null}.
 * @param scheme the scheme
 * @param userInfo the user info
 * @param host the host
 * @param port the port
 * @param path the path
 * @param queryParams the query parameters
 * @param fragment the fragment
 * @param encoded whether the components are already encoded
 * @param verify whether the components need to be checked for illegal characters
 */
HierarchicalUriComponents(String scheme, String userInfo, String host, int port, PathComponent path,
		MultiValueMap<String, String> queryParams, String fragment, boolean encoded, boolean verify) {

	super(scheme, fragment);
	this.userInfo = userInfo;
	this.host = host;
	this.port = port;
	this.path = path != null ? path : NULL_PATH_COMPONENT;
	this.queryParams = CollectionUtils.unmodifiableMultiValueMap(
			queryParams != null ? queryParams : new LinkedMultiValueMap<String, String>(0));
	this.encoded = encoded;
	if (verify) {
		verify();
	}
}
 
Example 34
Project: apollo-custom   File: AdminServiceAPI.java   Source Code and License 5 votes vote down vote up
public List<ReleaseDTO> findReleaseByIds(Env env, Set<Long> releaseIds) {
  if (CollectionUtils.isEmpty(releaseIds)) {
    return Collections.emptyList();
  }

  ReleaseDTO[]
      releases =
      restTemplate.get(env, "/releases?releaseIds={releaseIds}", ReleaseDTO[].class, JOINER.join(releaseIds));
  return Arrays.asList(releases);

}
 
Example 35
Project: xxpay-master   File: PayOrderService.java   Source Code and License 5 votes vote down vote up
public PayOrder selectPayOrderByMchIdAndMchOrderNo(String mchId, String mchOrderNo) {
    PayOrderExample example = new PayOrderExample();
    PayOrderExample.Criteria criteria = example.createCriteria();
    criteria.andMchIdEqualTo(mchId);
    criteria.andMchOrderNoEqualTo(mchOrderNo);
    List<PayOrder> payOrderList = payOrderMapper.selectByExample(example);
    return CollectionUtils.isEmpty(payOrderList) ? null : payOrderList.get(0);
}
 
Example 36
Project: document-management-store-app   File: MultipartFileListWhiteListValidator.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isValid(List<MultipartFile> multipartFiles, ConstraintValidatorContext context) {
    return  CollectionUtils.isEmpty(multipartFiles)
        || multipartFiles.stream()
            .map(MultipartFile::getContentType)
            .distinct()
            .allMatch(ft -> getMimeTypeList().contains(ft));
}
 
Example 37
Project: xxpay-master   File: PayOrderService.java   Source Code and License 5 votes vote down vote up
public PayOrder selectPayOrderByMchIdAndPayOrderId(String mchId, String payOrderId) {
    PayOrderExample example = new PayOrderExample();
    PayOrderExample.Criteria criteria = example.createCriteria();
    criteria.andMchIdEqualTo(mchId);
    criteria.andPayOrderIdEqualTo(payOrderId);
    List<PayOrder> payOrderList = payOrderMapper.selectByExample(example);
    return CollectionUtils.isEmpty(payOrderList) ? null : payOrderList.get(0);
}
 
Example 38
Project: raven   File: JsonUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * 将json串转为list对象<br>
 *
 * @param jsonStr
 * @param clazz
 * @return
 * List<T>
 * @Author fanyaowu
 * @data 2014年7月9日
 * @exception 
 * @version
 *
 */
public static <T> List<T> json2list(String jsonStr, Class<T> clazz)
{

	// 入參校驗
	if (StringUtils.isEmpty(jsonStr))
	{
		return null;
	}

	List<Map<String, Object>> list = null;
	try
	{
		list = objectMapper.readValue(jsonStr,
				new TypeReference<List<T>>()
				{
				});
	}
	catch (IOException e)
	{

	}

	// 非空校验
	if (CollectionUtils.isEmpty(list))
	{
		return null;
	}

	List<T> result = new ArrayList<T>();
	for (Map<String, Object> map : list)
	{
		result.add(map2pojo(map, clazz));
	}
	return result;
}
 
Example 39
Project: MonitorPlatform   File: ResultMap.java   Source Code and License 5 votes vote down vote up
public static ResultMap create(Map<String, Object> map) {
    if(!CollectionUtils.isEmpty(map)) {
        final String info = (String) map.get(INFO);
        final int status = (int) map.get(STATUS);
        final String message = (String) map.get(MESSAGE);
        return create(status, message, info);
    }
    
    throw new IllegalArgumentException("The parameter 'map' must be not empty.");
}
 
Example 40
Project: wisp   File: UnitTestDependencyInjectionTestExecutionListener.java   Source Code and License 5 votes vote down vote up
@Override
protected void injectDependencies(TestContext testContext) throws Exception {
    super.injectDependencies(testContext);
    /**
     * 获取测试类 & fields
     */
    Object bean = testContext.getTestInstance();
    List<Field> fields = getDeclaredFields(bean);
    if (CollectionUtils.isEmpty(fields)) {
        return;
    }
    /**
     * 如果测试类中, 被测试对象含有mockito的@InjectMocks注解,且 被测试对象被事务拦截器拦截 则 用原始对象代替
     */
    for (Field field : fields) {
        InjectMocks injectMocks = field.getAnnotation(InjectMocks.class);
        if (injectMocks == null) {
            continue;
        }
        field.setAccessible(true);
        Object proxy = field.get(bean);
        if (AopUtils.isAopProxy(proxy)) {
            // 替换对象
            Object target = ((Advised) proxy).getTargetSource().getTarget();
            field.set(bean, target);
        }
    }
}
 
Example 41
Project: MonitorPlatform   File: JobConfigController.java   Source Code and License 5 votes vote down vote up
@RequestMapping("/list")
public ResultMap jobList(Model model) {
    List<ScheduleJob> list = JobConfigService.getAllTask();
    //        model.addAttribute("taskList", list);
    if (CollectionUtils.isEmpty(list)) {
        return ResultMap.create(null, HttpStatus.OK);
    } else {
        return ResultMap.create(JSON.toJSONString(list), HttpStatus.OK);
    }
}
 
Example 42
Project: xxpay-master   File: BaseService4TransOrder.java   Source Code and License 5 votes vote down vote up
public int baseUpdateStatus4Complete(String transOrderId) {
    TransOrder transOrder = new TransOrder();
    transOrder.setTransOrderId(transOrderId);
    transOrder.setStatus(PayConstant.TRANS_STATUS_COMPLETE);
    TransOrderExample example = new TransOrderExample();
    TransOrderExample.Criteria criteria = example.createCriteria();
    criteria.andTransOrderIdEqualTo(transOrderId);
    List values = CollectionUtils.arrayToList(new Byte[] {
            PayConstant.TRANS_STATUS_SUCCESS, PayConstant.TRANS_STATUS_FAIL
    });
    criteria.andStatusIn(values);
    return transOrderMapper.updateByExampleSelective(transOrder, example);
}
 
Example 43
Project: xproject   File: AbstractXTreeBuilder.java   Source Code and License 5 votes vote down vote up
public <R> List<R> buildObjectTree(I rootTreeNodeId, List<T> allTreeNodeList, TreeNodeConverter<T, R> treeNodeConverter) {
	List<T> rootLevelTreeNodeList = buildObjectTree(rootTreeNodeId, allTreeNodeList);
	List<R> resultTreeNodeList = new ArrayList<R>();
	if(!CollectionUtils.isEmpty(rootLevelTreeNodeList)){
		for(T rootLevelTreeNode : rootLevelTreeNodeList){
			R resultTreeNode = treeNodeConverter.convertTreeNode(rootLevelTreeNode);
			resultTreeNodeList.add(resultTreeNode);
			recurisiveConvertTreeNode(rootLevelTreeNode, resultTreeNode, treeNodeConverter);
		}
	}
	return resultTreeNodeList;
}
 
Example 44
Project: apollo-custom   File: NamespaceService.java   Source Code and License 5 votes vote down vote up
private List<Namespace> filterChildNamespace(List<Namespace> namespaces) {
  List<Namespace> result = new LinkedList<>();

  if (CollectionUtils.isEmpty(namespaces)) {
    return result;
  }

  for (Namespace namespace : namespaces) {
    if (!isChildNamespace(namespace)) {
      result.add(namespace);
    }
  }

  return result;
}
 
Example 45
Project: apollo-custom   File: ConsumerRolePermissionService.java   Source Code and License 5 votes vote down vote up
/**
 * Check whether user has the permission
 */
public boolean consumerHasPermission(long consumerId, String permissionType, String targetId) {
  Permission permission =
      permissionRepository.findTopByPermissionTypeAndTargetId(permissionType, targetId);
  if (permission == null) {
    return false;
  }

  List<ConsumerRole> consumerRoles = consumerRoleRepository.findByConsumerId(consumerId);
  if (CollectionUtils.isEmpty(consumerRoles)) {
    return false;
  }

  Set<Long> roleIds =
      FluentIterable.from(consumerRoles).transform(consumerRole -> consumerRole.getRoleId())
          .toSet();
  List<RolePermission> rolePermissions = rolePermissionRepository.findByRoleIdIn(roleIds);
  if (CollectionUtils.isEmpty(rolePermissions)) {
    return false;
  }

  for (RolePermission rolePermission : rolePermissions) {
    if (rolePermission.getPermissionId() == permission.getId()) {
      return true;
    }
  }

  return false;
}
 
Example 46
Project: xproject   File: AbstractXTreeBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * 根据treeNodeId获取TreeNode对象
 * @param treeNodeId
 * @param allTreeNodeList
 * @return
 */
protected T getTreeNodeById(I treeNodeId, List<T> allTreeNodeList) {
	if(CollectionUtils.isEmpty(allTreeNodeList) || ObjectUtils.isEmpty(treeNodeId)){
		return null;
	}
	for(T treeNode : allTreeNodeList){
		if(treeNode != null && treeNodeId.equals(getTreeNodeId(treeNode))){
			return treeNode;
		}
	}
	return null;
}
 
Example 47
Project: otter-G   File: PipelineTimeoutRuleMonitor.java   Source Code and License 5 votes vote down vote up
@Override
public void explore(List<AlarmRule> rules) {
    if (CollectionUtils.isEmpty(rules)) {
        return;
    }
    Long pipelineId = rules.get(0).getPipelineId();

    ThroughputCondition condition = new ThroughputCondition();
    condition.setPipelineId(pipelineId);
    condition.setType(ThroughputType.ROW);
    ThroughputStat stat = throughputStatService.findThroughputStatByPipelineId(condition);

    long latestSyncTime = 0L;
    if (stat != null && stat.getGmtModified() != null) {
        Date modifiedDate = stat.getGmtModified();
        latestSyncTime = modifiedDate.getTime();
    }
    long now = System.currentTimeMillis();
    long elapsed = now - latestSyncTime;
    boolean flag = false;
    for (AlarmRule rule : rules) {
        flag |= checkTimeout(rule, elapsed);
    }

    if (flag) {
        logRecordAlarm(pipelineId, MonitorName.PIPELINETIMEOUT,
                       String.format(TIME_OUT_MESSAGE, pipelineId, (elapsed / 1000)));
    }
}
 
Example 48
Project: lams   File: CacheAspectSupport.java   Source Code and License 5 votes vote down vote up
protected Object execute(Invoker invoker, Object target, Method method, Object[] args) {
	// check whether aspect is enabled
	// to cope with cases where the AJ is pulled in automatically
	if (this.initialized) {
		Class<?> targetClass = getTargetClass(target);
		Collection<CacheOperation> operations = getCacheOperationSource().getCacheOperations(method, targetClass);
		if (!CollectionUtils.isEmpty(operations)) {
			return execute(invoker, new CacheOperationContexts(operations, method, args, target, targetClass));
		}
	}

	return invoker.invoke();
}
 
Example 49
Project: jsf-core   File: SubscribeHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 转为map,key:interfaceId,value:alias
 * @param list
 * @return
 */
public Map<Integer, Set<String>> getIfaceAliasMap(List<IfaceAliasVersion> list) {
	Map<Integer, Set<String>> result = new HashMap<Integer, Set<String>>();
	if (!CollectionUtils.isEmpty(list)) {
		for (IfaceAliasVersion iface : list) {
			if (result.get(iface.getInterfaceId()) == null) {
				result.put(iface.getInterfaceId(), new HashSet<String>());
			}
			result.get(iface.getInterfaceId()).add(iface.getAlias());
		}
	}
	return result;
}
 
Example 50
Project: linq   File: JpaUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 更具查询条件查询记录
 * @param cq 条件
 * @param <T> 领域类(实体类)范型
 * @return 结果集合
 */
public static <T> List<T> findAll(CriteriaQuery<T> cq) {
	Class<T> domainClass = cq.getResultType();
	if (CollectionUtils.isEmpty(cq.getRoots())) {
		cq.from(domainClass);
	}
	EntityManager em = getEntityManager(domainClass);
	return em.createQuery(cq).getResultList();
}
 
Example 51
Project: apollo-custom   File: NotificationControllerV2.java   Source Code and License 5 votes vote down vote up
private List<ApolloConfigNotification> getApolloConfigNotifications(Set<String> namespaces,
                                                                    Map<String, Long> clientSideNotifications,
                                                                    Multimap<String, String> watchedKeysMap,
                                                                    List<ReleaseMessage> latestReleaseMessages) {
  List<ApolloConfigNotification> newNotifications = Lists.newArrayList();
  if (!CollectionUtils.isEmpty(latestReleaseMessages)) {
    Map<String, Long> latestNotifications = Maps.newHashMap();
    for (ReleaseMessage releaseMessage : latestReleaseMessages) {
      latestNotifications.put(releaseMessage.getMessage(), releaseMessage.getId());
    }

    for (String namespace : namespaces) {
      long clientSideId = clientSideNotifications.get(namespace);
      long latestId = ConfigConsts.NOTIFICATION_ID_PLACEHOLDER;
      Collection<String> namespaceWatchedKeys = watchedKeysMap.get(namespace);
      for (String namespaceWatchedKey : namespaceWatchedKeys) {
        long namespaceNotificationId =
            latestNotifications.getOrDefault(namespaceWatchedKey, ConfigConsts.NOTIFICATION_ID_PLACEHOLDER);
        if (namespaceNotificationId > latestId) {
          latestId = namespaceNotificationId;
        }
      }
      if (latestId > clientSideId) {
        ApolloConfigNotification notification = new ApolloConfigNotification(namespace, latestId);
        namespaceWatchedKeys.stream().filter(latestNotifications::containsKey).forEach(namespaceWatchedKey ->
            notification.addMessage(namespaceWatchedKey, latestNotifications.get(namespaceWatchedKey)));
        newNotifications.add(notification);
      }
    }
  }
  return newNotifications;
}
 
Example 52
Project: ukubuka-core   File: UkubukaTransformer.java   Source Code and License 5 votes vote down vote up
/**
 * Perform Type Operations
 * 
 * @param fileContents
 * @param transformOperations
 * @throws TransformException
 */
private void performTypeOperations(FileContents fileContents,
        final List<TransformOperations> transformOperations)
        throws TransformException {
    if (!CollectionUtils.isEmpty(transformOperations)) {
        LOGGER.info("Transform Count: #{}", transformOperations.size());
        performTransformOperations(fileContents, transformOperations);
    }
}
 
Example 53
Project: bootstrap   File: RestRepositoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Transactional
public int deleteAllExpected(final Collection<K> identifiers) {
	final int deleted = deleteAll(identifiers);
	if (deleted != org.apache.commons.collections4.CollectionUtils.size(identifiers)) {
		// At least one row has not been deleted
		throw new EntityNotFoundException(identifiers.toString());
	}
	return deleted;
}
 
Example 54
Project: embedded-database-spring-test   File: OptimizedFlywayTestExecutionListener.java   Source Code and License 5 votes vote down vote up
private static MigrationVersion findLastVersion(Flyway flyway, String... locations) {
    CompositeMigrationResolver resolver = createMigrationResolver(flyway, locations);
    List<ResolvedMigration> migrations = resolver.resolveMigrations();

    if (CollectionUtils.isEmpty(migrations)) {
        return MigrationVersion.EMPTY;
    } else {
        return Iterables.getLast(migrations).getVersion();
    }
}
 
Example 55
Project: OutsourcedProject   File: JsonUtil.java   Source Code and License 5 votes vote down vote up
/***
 * 获取json键的值
 * @param jsonStr
 * @param k
 * @return
 */
public static <K, V> V getJsonValue(String jsonStr, K k) {
    V bean = null;
    Map<K, V> resultMap = jsonToMap(jsonStr);
    if (CollectionUtils.isEmpty(resultMap)) {
        bean = resultMap.get(k);
    }
    return bean;
}
 
Example 56
Project: jsf-core   File: ClientManagerImpl.java   Source Code and License 5 votes vote down vote up
/**
* 计算
* @return
* @throws Exception
   */
  private int getId() throws Exception {
  	int result = 0;
  	int start = 0;
  	int end;
if (subscribeHelper.genClientIdSwitch()) {
	try {
		if (auto_id == 0) {
			auto_id = clientDao.getAutoIncrement() - range * 2;
		}
		if (auto_id < CLIENTID_LIMIT) {    //auto_id小于CLIENTID_LIMIT时,就直接用自增就行
			return result;
		}
		while (true) {
			if (clientIdQueue.isEmpty()) {   //先从队列里取,如果没有了,再从db里取一批
				start = rand.nextInt(auto_id);
				end = start + range;
				List<Integer> resultIds = clientDao.getIdList(start, end);
				for (int i = start; i <= end; i++) {
					if (CollectionUtils.isEmpty(resultIds) || !resultIds.contains(i)) {
						clientIdQueue.put(i);
					}
				}
			}
			Integer tmp = clientIdQueue.poll(100, TimeUnit.MICROSECONDS);
			if (tmp != null) {
				result = tmp.intValue();
				break;
			}
		}
	} catch (Exception e) {
		logger.error(e.getMessage() + ", start:" + start, e);
	}
}
  	return result;
  }
 
Example 57
Project: spring-boot-starter-disruptor   File: DisruptorAutoConfiguration.java   Source Code and License 5 votes vote down vote up
protected Map<String, String> parseHandlerChainDefinitions(String definitions) {
	Ini ini = new Ini();
	ini.load(definitions);
	Ini.Section section = ini.getSection("urls");
	if (CollectionUtils.isEmpty(section)) {
		section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
	}
	return section;
}
 
Example 58
Project: lams   File: ContentNegotiationManagerFactoryBean.java   Source Code and License 5 votes vote down vote up
/**
 * Add mappings from file extensions to media types represented as strings.
 * <p>When this mapping is not set or when an extension is not found, the Java
 * Action Framework, if available, may be used if enabled via
 * {@link #setFavorPathExtension(boolean)}.
 * @see #addMediaType(String, MediaType)
 * @see #addMediaTypes(Map)
 */
public void setMediaTypes(Properties mediaTypes) {
	if (!CollectionUtils.isEmpty(mediaTypes)) {
		for (Entry<Object, Object> entry : mediaTypes.entrySet()) {
			String extension = ((String)entry.getKey()).toLowerCase(Locale.ENGLISH);
			this.mediaTypes.put(extension, MediaType.valueOf((String) entry.getValue()));
		}
	}
}
 
Example 59
Project: linq   File: JpaUtil.java   Source Code and License 5 votes vote down vote up
/**
 * source转Map,Key为source元素的propertyName属性值,Value为该元素
 * @param source 源集合
 * @param propertyName 属性名
 * @param <K> propertyName对应的属性的类型
 * @param <V> source集合元素类型
 * @return 索引Map
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <K, V> Map<K, V> index(Collection<V> source, String propertyName) {
	if (CollectionUtils.isEmpty(source)) {
		return Collections.EMPTY_MAP;
	}
	Map result = new HashMap();

	for (Object obj : source) {
		Object value = getValue(propertyName, obj);

		result.put(value, obj);
	}
	return result;
}
 
Example 60
Project: apollo-custom   File: DefaultRolePermissionService.java   Source Code and License 5 votes vote down vote up
/**
 * Check whether user has the permission
 */
public boolean userHasPermission(String userId, String permissionType, String targetId) {
    Permission permission =
            permissionRepository.findTopByPermissionTypeAndTargetId(permissionType, targetId);
    if (permission == null) {
        return false;
    }

    if (isSuperAdmin(userId)) {
        return true;
    }

    List<UserRole> userRoles = userRoleRepository.findByUserId(userId);
    if (CollectionUtils.isEmpty(userRoles)) {
        return false;
    }

    Set<Long> roleIds =
            FluentIterable.from(userRoles).transform(userRole -> userRole.getRoleId()).toSet();
    List<RolePermission> rolePermissions = rolePermissionRepository.findByRoleIdIn(roleIds);
    if (CollectionUtils.isEmpty(rolePermissions)) {
        return false;
    }

    for (RolePermission rolePermission : rolePermissions) {
        if (rolePermission.getPermissionId() == permission.getId()) {
            return true;
        }
    }

    return false;
}