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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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: otter-G   File: DatabaseExtractor.java   View source code 5 votes vote down vote up
private List<String> select(DbDialect dbDialect, String schemaName, String tableName, TableData keyTableData,
                            TableData columnTableData) throws InterruptedException {
    String selectSql = dbDialect.getSqlTemplate().getSelectSql(schemaName,
        tableName,
        keyTableData.columnNames,
        columnTableData.columnNames);
    Exception exception = null;
    for (int i = 0; i < retryTimes; i++) {
        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedException(); // 退出
        }

        try {
            List<List<String>> result = dbDialect.getJdbcTemplate().query(selectSql,
                keyTableData.columnValues,
                keyTableData.columnTypes,
                new RowDataMapper(columnTableData.columnTypes));
            if (CollectionUtils.isEmpty(result)) {
                logger.warn("the mediaName = {}.{} not has rowdate in db \n {}", new Object[] { schemaName,
                        tableName, dumpEventData(eventData, selectSql) });
                return null;
            } else {
                return result.get(0);
            }

        } catch (Exception e) {
            exception = e;
            logger.warn("retry [" + (i + 1) + "] failed", e);
        }
    }

    throw new RuntimeException("db extract failed , data:\n " + dumpEventData(eventData, selectSql), exception);
}
 
Example 33
Project: bootstrap   File: RestRepositoryImpl.java   View source code 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 34
Project: lams   File: HierarchicalUriComponents.java   View source code 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 35
Project: apollo-custom   File: AdminServiceAPI.java   View source code 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 36
Project: xxpay-master   File: PayOrderService.java   View source code 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 37
Project: document-management-store-app   File: MultipartFileListWhiteListValidator.java   View source code 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 38
Project: xxpay-master   File: PayOrderService.java   View source code 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 39
Project: raven   File: JsonUtils.java   View source code 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 40
Project: MonitorPlatform   File: ResultMap.java   View source code 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.");
}