@Test public void testGetTopLevelKeys() { List<String> expected = Lists.newArrayList("value1", "value2"); IData idata = IDataFactory.create(); IDataCursor cursor = idata.getCursor(); IDataUtil.put(cursor, "value1", "something"); IDataUtil.put(cursor, "value2", "another one"); cursor.destroy(); Document document = docFactory.wrap(idata); CollectionUtils.isEqualCollection(expected, document.getKeys()); }
@RequestMapping("/delete") @ResponseBody public ReturnT<String> delete(int id) { // 存在Test记录,拒绝删除 List<XxlApiTestHistory> historyList = xxlApiTestHistoryDao.loadByDocumentId(id); if (CollectionUtils.isNotEmpty(historyList)) { return new ReturnT<String>(ReturnT.FAIL_CODE, "拒绝删除,该接口下存在Test记录,不允许删除"); } // 存在Mock记录,拒绝删除 List<XxlApiMock> mockList = xxlApiMockDao.loadAll(id); if (CollectionUtils.isNotEmpty(mockList)) { return new ReturnT<String>(ReturnT.FAIL_CODE, "拒绝删除,该接口下存在Mock记录,不允许删除"); } int ret = xxlApiDocumentDao.delete(id); return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL; }
/** * 批量删除补偿事务信息 * * @param ids ids 事务id集合 * @param applicationName 应用名称 * @return true 成功 */ @Override public Boolean batchRemove(List<String> ids, String applicationName) { if (CollectionUtils.isEmpty(ids) || StringUtils.isBlank(applicationName)) { return Boolean.FALSE; } final String rootPath = RepositoryPathUtils.buildZookeeperPath(applicationName); ids.stream().map(id -> { try { final String path = buildRootPath(rootPath, id); byte[] content = zooKeeper.getData(path, false, new Stat()); final TransactionRecoverAdapter adapter = objectSerializer.deSerialize(content, TransactionRecoverAdapter.class); zooKeeper.delete(path, adapter.getVersion()); return 1; } catch (Exception e) { e.printStackTrace(); return -1; } }).count(); return Boolean.TRUE; }
public List<MigrationTask> getRollbackCandidates(List<MigrationTask> allMigrationTasks, int[] rollbackLevels, PatchInfoStore currentPatchInfoStore) throws MigrationException { validateRollbackLevel(rollbackLevels); int rollbackLevel = rollbackLevels[0]; int currentPatchLevel = currentPatchInfoStore.getPatchLevel(); if (currentPatchLevel < rollbackLevel) { throw new MigrationException( "The rollback patch level cannot be greater than the current patch level"); } PatchRollbackPredicate rollbackPredicate = new PatchRollbackPredicate(currentPatchLevel, rollbackLevel); List<MigrationTask> migrationCandidates = new ArrayList<MigrationTask>(); migrationCandidates.addAll(allMigrationTasks); CollectionUtils.filter(migrationCandidates, rollbackPredicate); Collections.sort(migrationCandidates); // need to reverse the list do we apply the rollbacks in descending // order Collections.reverse(migrationCandidates); return migrationCandidates; }
/** * 调用所有的{@link ConfigItemPostProcessor}进行配置项预处理 * * @param versionPropertySource */ private void invokeConfigItemPostProcessors(VersionPropertySource<ConfigItemList> versionPropertySource) { if (versionPropertySource == null) { return; } List<ConfigItemPostProcessor> configItemPostProcessors = this.configItemPostProcessors; if (CollectionUtils.isEmpty(configItemPostProcessors)) { return; } long version = versionPropertySource.getVersion(); EnumerablePropertySource<?> propertySource = versionPropertySource.getSource(); if (propertySource == null) { return; } if (!(propertySource instanceof ConfigPropertySource)) { return; } ConfigPropertySource configPropertySource = (ConfigPropertySource) propertySource; for (ConfigItemPostProcessor postProcessor : configItemPostProcessors) { postProcessor.postProcessConfigItems(version, configPropertySource); } }
/** * 获取当前登录者所能看见的菜单集合 * @param request * @param response * @return */ @ResponseBody @RequestMapping(value="/login/user/menus", method=GET, produces=APPLICATION_JSON) public Object getLoginUserMenuList(HttpServletRequest request, HttpServletResponse response) { List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>(); try { List<AdminResource> userMenuResources = new ArrayList<AdminResource>(); AdminUserRealm realm = ShiroUtils.getRealm(AdminUserRealm.class); AuthorizationInfo authInfo = realm.getAuthorizationInfo(SecurityUtils.getSubject().getPrincipals()); if(authInfo instanceof CustomAuthorizationInfo){ CustomAuthorizationInfo<AdminResource> authorizationInfo = (CustomAuthorizationInfo<AdminResource>) authInfo; Set<AdminResource> userResources = authorizationInfo.getResources(); if(!CollectionUtils.isEmpty(userResources)){ for(AdminResource resource : userResources){ if(AdminResourceActionTypeEnum.ADMIN_RESOURCE_ACTION_TYPE_MENU.getTypeCode().equals(resource.getActionType())){ userMenuResources.add(resource); } } dataList = resourceTreeBuilder.buildObjectTree(GlobalConstants.DEFAULT_ADMIN_ROOT_RESOURCE_ID, userMenuResources, resourceNavMenuNodeConverter); } } } catch (Exception e) { logger.error(e.getMessage(), e); } return dataList; }
@Test @SuppressWarnings("unchecked") public void testSelects() { Record r = new Record(); r.setUserIdentityARN("arn:sample"); List<Record> records = Arrays.asList(r, new Record()); Collection<Record> sample = CollectionUtils.select(records, new Predicate() { @Override public boolean evaluate(Object o) { return o instanceof Record && ((Record) o).getUserIdentityARN() != null && ((Record) o).getUserIdentityARN().contains("sample"); } }); Assertions.assertThat(sample).hasSize(1); }
@Override public void onEvent(RequestDtoEvent event, long sequence, boolean endOfBatch) throws Exception { if (event.hasErrorOrException()) { return; } List<Command> commandList = event.getCommandCollector().getCommandList(); if (CollectionUtils.isEmpty(commandList)) { return; } for (Command command : commandList) { commandDispatcher.dispatch(command); } }
/** * 判断对象是不是定义了 <br> * List的话,不为NULL和空<br> * 字符串的的话,不为NULL或空<br> * Integer的话,不为NULL或0<br> * * @param obj * 要判断的对象 * @return 是否定义了 */ public static boolean isDefined(Object obj) { if (obj instanceof Collection) { return CollectionUtils.isNotEmpty((Collection<?>) obj); } if (obj instanceof Map) { return MapUtils.isNotEmpty((Map<?, ?>) obj); } if (obj instanceof String) { return StringUtils.isNotEmpty((String) obj); } if (obj instanceof Integer) { return obj != null && (Integer) obj != 0; } return obj != null; }
/** * 获取延迟多长时间后的事务信息,只要为了防止并发的时候,刚新增的数据被执行 * * @param date 延迟后的时间 * @return List<TransactionRecover> */ @Override public List<TransactionRecover> listAllByDelay(Date date) { String sb = "select * from " + tableName + " where last_time <?"; List<Map<String, Object>> list = executeQuery(sb, date); if (CollectionUtils.isNotEmpty(list)) { return list.stream().filter(Objects::nonNull) .map(this::buildByMap).collect(Collectors.toList()); } return null; }
private synchronized void updateTxManagerServices() { String url = assembleUrl(); int maxRetries = 2; for (int i = 0; i < maxRetries; i++) { try { final List<TxManagerServiceDTO> serviceDTOList = OkHttpTools.getInstance().get(url, mResponsetype); if (CollectionUtils.isEmpty(serviceDTOList)) { LogUtil.error(LOGGER, "Empty response! 请求url为:{}", () -> url); continue; } mConfigservices.set(serviceDTOList); return; } catch (Throwable ex) { ex.printStackTrace(); LogUtil.error(LOGGER, "updateTxManagerServices fail exception:{}", ex::getMessage); /* throw new TransactionRuntimeException( String.format("Get config services failed from %s", url), ex);*/ } } }
public static Set<String> getAllNamespaceLists(Collection<HasChildren> rules) { Set<String> namespaceList = new HashSet<>(); for (HasChildren rule : rules) { Collection<Expressions> rulesExpressions = rule.getItems(); if (CollectionUtils.isNotEmpty(rulesExpressions)) { for (Expressions subRule : rulesExpressions) { if (subRule instanceof HasChildren) { namespaceList.addAll(getAllNamespaceLists(Arrays.asList((HasChildren)subRule))); } else if (subRule instanceof ContainsBase && ((ContainsBase)subRule).getType().equals("namespacedList")) { for (Value namespace : ((ContainsBase)subRule).getNamespacedLists()) { namespaceList.add(namespace.getValue()); } } } } else if(rule instanceof IfExpression) { log.warn("Rule {} has empty expressions", ((IfExpression)rule).getId()); } } return namespaceList; }
@Override public List<String> readPieceMd5(String taskId, String fileMd5) { List<String> pieceMd5s = null; String lockName = lockService.getLockName(LockConstants.FILE_MD5_DATA_LOCK, taskId); lockService.lock(lockName); try { Path path = PathUtil.getMd5DataPath(taskId); if (Files.exists(path)) { pieceMd5s = Files.readAllLines(path, StandardCharsets.UTF_8); } } catch (Exception e) { logger.error("read piece md5 error for taskId:{}", taskId, e); } finally { lockService.unlock(lockName); } if (CollectionUtils.isNotEmpty(pieceMd5s)) { String sha1Value = pieceMd5s.remove(pieceMd5s.size() - 1); if (StringUtils.equalsIgnoreCase(sha1Value, DigestUtil.sha1(pieceMd5s)) && !pieceMd5s.isEmpty()) { String realFileMd5 = pieceMd5s.remove(pieceMd5s.size() - 1); if (StringUtils.equalsIgnoreCase(realFileMd5, fileMd5)) { return pieceMd5s; } } } return null; }
@RequestMapping @PermessionLimit(superUser = true) public String index(Model model, HttpServletRequest request) { // permission XxlApiUser loginUser = (request.getAttribute(LOGIN_IDENTITY_KEY)!=null)? (XxlApiUser) request.getAttribute(LOGIN_IDENTITY_KEY) :null; if (loginUser.getType()!=1) { throw new RuntimeException("权限拦截."); } List<XxlApiUser> userList = xxlApiUserDao.loadAll(); if (CollectionUtils.isEmpty(userList)) { userList = new ArrayList<>(); } else { for (XxlApiUser user: userList) { user.setPassword("***"); } } model.addAttribute("userList", JacksonUtil.writeValueAsString(userList)); return "user/user.list"; }
@Override public HttpProxy getProxy(List<HttpProxy> httpProxies) { if (CollectionUtils.isNotEmpty(httpProxies)) { return httpProxies.get(new Random().nextInt(httpProxies.size()-1)); } return null; }
public void createService(CloudFoundryOperations client, CloudServiceExtended service, String spaceId) { if (CollectionUtils.isEmpty(service.getServiceAlternatives())) { createServiceInternal(client, service, spaceId); return; } LOGGER.debug(format("Service \"{0}\" has defined service offering alternatives \"{1}\" for default service offering \"{2}\"", service.getName(), service.getServiceAlternatives(), service.getLabel())); List<String> possibleServiceOfferings = computePossibleServiceOfferings(service); Map<String, List<CloudServicePlan>> existingServiceOfferings = client.getServiceOfferings().stream().collect( Collectors.toMap(CloudServiceOffering::getName, CloudServiceOffering::getCloudServicePlans)); List<String> validServiceOfferings = computeValidServiceOfferings(client, possibleServiceOfferings, service.getPlan(), existingServiceOfferings); if (CollectionUtils.isEmpty(validServiceOfferings)) { LOGGER.error(format( "Service \"{0}\" could not be created because none of the service offering(s) \"{1}\" match with existing service offerings \"{2}\" or provide service plan \"{3}\"", service.getName(), possibleServiceOfferings, existingServiceOfferings.keySet(), service.getPlan())); throw new CloudFoundryException(HttpStatus.BAD_REQUEST, format(Messages.CANT_CREATE_SERVICE_NOT_MATCHING_OFFERINGS_OR_PLAN, service.getName(), possibleServiceOfferings, service.getPlan())); } attemptToFindServiceOfferingAndCreateService(client, service, spaceId, validServiceOfferings); }
/** * Add all TransformationHandlers to the input handler. */ private void registerTransformationHandlers(TransformationHandler handler) { // register all handlers to fire before the target handler List<ITransformationHandler> prependHandlers = transformationHandlerFactory.getPrependedHandlers(handler); if (!CollectionUtils.isEmpty(prependHandlers)) { handler.prependTransformationHandlers(prependHandlers); } // register the target handler - this must always happen, even if this build has no factory defined handler.getTransformationHandlers().add(handler); // register all handlers to fire after the target handler List<ITransformationHandler> appendHandlers = transformationHandlerFactory.getAppendedHandlers(handler); if (!CollectionUtils.isEmpty(appendHandlers)) { handler.appendTransformationHandlers(appendHandlers); } }
@Override public void process(WatchedEvent event) throws Exception { String topicParentPath = zkConf.getZKBasePath() + "/topics"; LOG.info("get zookeeper notification for path={}", topicParentPath); if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) { List<String> newTopics = zkClient.getChildren().forPath(topicParentPath); List<String> oldTopics = metadata.getAllTopics(); Collection<String> addedTopics = CollectionUtils.subtract(newTopics, oldTopics); Collection<String> deletedTopics = CollectionUtils.subtract(oldTopics, newTopics); for (String topic : addedTopics) { String topicPath = topicParentPath + "/" + topic; zkClient.getChildren() .usingWatcher(new TopicWatcher(topic)) .forPath(topicPath); Map<Integer, Integer> queueMap = readTopicInfo(topic); metadata.updateTopicMap(topic, queueMap); } metadata.removeTopics(deletedTopics); } zkClient.getChildren() .usingWatcher(new TopicsWather()) .forPath(topicParentPath); }
private void confirm(TccTransaction tccTransaction) { final List<Participant> participants = tccTransaction.getParticipants(); List<Participant> failList = Lists.newArrayListWithCapacity(participants.size()); boolean success = true; if (CollectionUtils.isNotEmpty(participants)) { for (Participant participant : participants) { try { TccTransactionContext context = new TccTransactionContext(); context.setAction(TccActionEnum.CONFIRMING.getCode()); context.setTransId(tccTransaction.getTransId()); TransactionContextLocal.getInstance().set(context); executeCoordinator(participant.getConfirmTccInvocation()); } catch (Exception e) { LogUtil.error(LOGGER, "执行confirm方法异常:{}", () -> e); success = false; failList.add(participant); } } executeHandler(success, tccTransaction, failList); } }
/** * 解析数据源中单个数据项的扩展参数 * @param absEle * @param node */ private void parseDataParamList(AbstractElement absEle, Element node, Map<String, Object> tmpMap) { @SuppressWarnings("unchecked") List<Element> paramEleList = node.elements("param"); if(CollectionUtils.isEmpty(paramEleList)) { return; } for(Element element : paramEleList) { String key = element.attributeValue("name"); String value = element.attributeValue("value"); absEle.putData(key, value); tmpMap.put(key, value); } }
private List<String> getFullPieceMd5s(Task task, FileMetaData metaData) { List<String> pieceMd5s = taskService.getFullPieceMd5sByTask(task); if (CollectionUtils.isEmpty(pieceMd5s)) { pieceMd5s = fileMetaDataService.readPieceMd5(task.getTaskId(), metaData.getRealMd5()); } return pieceMd5s; }
public ProcessingLifecycleStatus determineLifecycleStatus(RawLines rawLines) { ProcessingLifecycleStatus status = ProcessingLifecycleStatus.UNKNOWN; List<List<RawWord>> lines = rawLines.getRawLines(); if(CollectionUtils.isEmpty(lines)) { return status; } for(List<RawWord> line : lines) { if(status != ProcessingLifecycleStatus.UNKNOWN) { break; } for(RawWord word : line) { if(word.getWord().contains("Forgot") || word.getWord().contains("Password")) { status = ProcessingLifecycleStatus.LOGIN_READY; break; } else if(word.getWord().contains("Welcome")) { status = ProcessingLifecycleStatus.APPLICATION_READY; break; } else if(word.getWord().contains("Trade")) { status = ProcessingLifecycleStatus.TRADE_PARTNER; } else if(word.getWord().contains("SOFTWARE")) { status = ProcessingLifecycleStatus.ACCEPT_TOS_EULA_READY; } } } return status; }
private String getExecutable() { File supposedExecutable = new File(executableDir + executableName); if(supposedExecutable.exists()) { return supposedExecutable.getAbsolutePath(); } else { Collection<File> theExecutable = FileUtils.listFiles(new File(executableDir), new WildcardFileFilter(executableName), TrueFileFilter.INSTANCE); if(theExecutable != null || theExecutable.size() > 1 || theExecutable.isEmpty()) { File newestExecutable = theExecutable.stream().reduce(new File(""), (aFile, newestFile) -> { if(aFile.lastModified() > newestFile.lastModified()) { return aFile; } return newestFile; }); return newestExecutable.getAbsolutePath(); } else if(theExecutable.size() == 1) { return ((File)CollectionUtils.get(theExecutable, 0)).getAbsolutePath(); } else { throw new RuntimeException("Could not determine executable path"); } } }
@Override public PendingChangesBatchOperationResult approve(String appName, ApplicationStatusMode mode) { OperationContextHolder.OperationContext currentContext = OperationContextHolder.getCurrentContext(); WhitelistedStackUpdates whitelistedStackUpdates = currentContext.getWhitelistedStackUpdates(); ServicePaths servicePaths = currentContext.getServicePaths(); PendingChangesStatus pendingChangesStatus = currentContext.getPendingChangesStatus(); PendingChangesBatchOperationResult batchResult = super.approve(appName, ApplicationStatusMode.OFFLINE); if (CollectionUtils.isNotEmpty(batchResult.getWhitelist().getEntitiesToSave())) { Whitelisted approvedWhitelist = (Whitelisted) batchResult.getWhitelist().getEntitiesToSave().get(0); ServicePaths updatedServicePaths = stacksService.updateStacksForService(appName, servicePaths, approvedWhitelist); batchResult.addEntityToUpdate(updatedServicePaths); batchResult.addEntityToUpdate(getWhiteListStackUpdateService().getNewWhitelistedStatuses(whitelistedStackUpdates, pendingChangesStatus, appName)); } return batchResult; }
@Override public <X> List<X> findByNative(String sql, List<?> params, Pageable pageable, Class<X> clazz) { Assert.hasText(sql, "native sql can not been null or blank"); Query query = entityManager.createNativeQuery(sql); if (query != null) { query.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(clazz)); query.setFirstResult(pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); if (CollectionUtils.isNotEmpty(params)) { for (int i = 0; i < params.size(); i++) { query.setParameter(i + 1, params.get(i)); } } return query.getResultList(); } return Lists.newArrayList(); }
@Override public int updateOrInsertServiceMethedRule(ServiceMethedRule serviceMethedRule) { if (serviceMethedRule == null) { return 0; } serviceMethedRule.setUpdateTime(new Date()); int count = serviceMethedRuleMapper.updateByPrimaryKey(serviceMethedRule); if (count <= 0) { ServiceMethedRuleExample example = new ServiceMethedRuleExample(); ReflectUtil.invokeSelectParams(example, serviceMethedRule); count = serviceMethedRuleMapper.insert(serviceMethedRule); List<ServiceMethedRule> services = selectServiceMethedRule(serviceMethedRule); int id = 0; if (CollectionUtils.isNotEmpty(services)) { for (ServiceMethedRule service : services) { if (service.getId() > id) { id = service.getId(); } } } serviceMethedRule.setId(id); } return count; }
public void setCaches(Collection<Cache> caches) { if (CollectionUtils.isNotEmpty(caches)) { for (Cache cache : caches) { this.caches.put(cache.getName(), cache); } } }
/** * 获取延迟多长时间后的事务信息,只要为了防止并发的时候,刚新增的数据被执行 * * @param date 延迟后的时间 * @return List<MythTransaction> */ @Override public List<MythTransaction> listAllByDelay(Date date) { String sb = "select * from " + tableName + " where last_time <? and status = 2"; List<Map<String, Object>> list = executeQuery(sb, date); if (CollectionUtils.isNotEmpty(list)) { return list.stream().filter(Objects::nonNull) .map(this::buildByResultMap).collect(Collectors.toList()); } return null; }
private void assertExistTenants(Set<TenantState> tenantKeys) { if (CollectionUtils.isEmpty(tenantKeys)) { final String error = "Tenant list for " + applicationName + " empty. Check tenants-list.json."; log.error(error); throw new IllegalStateException(error); } }
@Override public int updateOrInsertRegistryConfig(RegistryConfig registryConfig) { if (registryConfig == null) { return 0; } registryConfig.setUpdateTime(new Date()); int count = registryConfigMapper.updateByPrimaryKeySelective(registryConfig); if (count <= 0) { RegistryConfigExample example = new RegistryConfigExample(); ReflectUtil.invokeSelectParams(example, registryConfig); count = registryConfigMapper.insert(registryConfig); List<RegistryConfig> services = selectRegistryConfig(registryConfig); int id = 0; if (CollectionUtils.isNotEmpty(services)) { for (RegistryConfig service : services) { if (service.getId() > id) { id = service.getId(); } } } registryConfig.setId(id); } return count; }
@Override public boolean gc(GcMeta gcMeta) { boolean result = false; if (gcMeta != null) { List<String> cids = gcMeta.getCids(); String taskId = gcMeta.getTaskId(); if (CollectionUtils.isNotEmpty(cids) && taskId != null) { for (String cid : cids) { peerTaskRepo.remove(taskId, cid); } } result = true; } return result; }
@Override public OperationResult deleteTemplateRule(String appName, String ruleId) { final OperationContextHolder.OperationContext currentContext = OperationContextHolder.getCurrentContext(); final PendingChangesStatus pendingChangesStatus = currentContext.getPendingChangesStatus(); SelectServer templates = currentContext.getTemplatePathRules(); Collection<IfExpression> flavorRules = currentContext.getFlavorRules().getItems(); boolean containsTemplates = (templates != null && CollectionUtils.isNotEmpty(templates.getItems())); IfExpression current = containsTemplates ? templates.getRule(ruleId) : null; flavorRules.addAll(PendingChangeStatusHelper.getPendingFlavorRules(pendingChangesStatus)); return deleteRule(appName, ruleId, current, flavorRules, ApplicationStatusMode.OFFLINE); }
@Override public Collection<EmployeeDTO> convertToDTO(Collection<Employee> employees) { if (CollectionUtils.isEmpty(employees)) { return null; } return employees.stream(). filter(Objects::nonNull).map(employee -> convertToDTO(employee)) .collect(Collectors.toList()); }
/** * 获取延迟多长时间后的事务信息,只要为了防止并发的时候,刚新增的数据被执行 * * @param date 延迟后的时间 * @return List<TccTransaction> */ @Override @SuppressWarnings("unchecked") public List<TccTransaction> listAllByDelay(Date date) { String sb = "select * from " + tableName + " where last_time <?"; List<Map<String, Object>> list = executeQuery(sb, date); if (CollectionUtils.isNotEmpty(list)) { return list.stream().filter(Objects::nonNull) .map(this::buildByResultMap).collect(Collectors.toList()); } return null; }
@Override public void call(ChannelHandlerContext ctx, MessageToMultiDeviceReq message) { //找寻到对应设备的channel 将消息全部推送给这个设备 if (message != null) { if (CollectionUtils.isNotEmpty(message.getDevices())) { List<String> devcies = message.getDevices(); devcies.stream().forEach((e) -> { List<String> msgList = new ArrayList<>(); PushReq pushReq = PushReq.builder().msgs(msgList).build(); pushSender.send(e, pushReq); }); Channel channel = ctx.channel(); channel.writeAndFlush(MessageToMultiDeviceResp.builder().result(NodeMessageEnum.OK.getCode()).build().encode()); } } }
private Boolean checkChannel(List<TxTransactionItem> txTransactionItems) { if (CollectionUtils.isNotEmpty(txTransactionItems)) { final List<TxTransactionItem> collect = txTransactionItems.stream().filter(item -> { Channel channel = SocketManager.getInstance().getChannelByModelName(item.getModelName()); return Objects.nonNull(channel) && (channel.isActive() || item.getStatus() != TransactionStatusEnum.ROLLBACK.getCode()); }).collect(Collectors.toList()); return txTransactionItems.size() == collect.size(); } return true; }
public static Set<String> getFieldnames(FieldDescriptor descriptor, String context) { Set<String> fieldsnames = new HashSet<>(); for(UseCase useCase : UseCase.values()) { CollectionUtils.addIgnoreNull(fieldsnames, getFieldname(descriptor, useCase, context)); } return fieldsnames; }
public void setSelectAll(boolean selectAll) { this.selectAll = selectAll; if (this.triggerProcessList != null) { final boolean isSelectAll = this.isSelectAll(); CollectionUtils.forAllDo(this.triggerProcessList, new Closure() { @Override public void execute(Object tp) { ((TriggerProcess) tp).setSelected(isSelectAll); } }); } }
/** * 业务端获取TxManager信息 * * @return TxManagerServer */ @Override public TxManagerServer findTxManagerServer() { final List<String> eurekaService = findEurekaService(); if (CollectionUtils.isNotEmpty(eurekaService)) { final List<TxManagerInfo> txManagerInfos = eurekaService.stream().map(url -> restTemplate.getForObject(url + "/tx/manager/findTxManagerInfo", TxManagerInfo.class)) .collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(txManagerInfos)) { //获取连接数最多的服务 想要把所有的业务长连接,连接到同一个tm,但是又不能超过最大的连接 final Optional<TxManagerInfo> txManagerInfoOptional = txManagerInfos.stream().filter(Objects::nonNull) .filter(info -> info.getNowConnection() < info.getMaxConnection()) .sorted(Comparator.comparingInt(TxManagerInfo::getNowConnection).reversed()) .findFirst(); if (txManagerInfoOptional.isPresent()) { final TxManagerInfo txManagerInfo = txManagerInfoOptional.get(); TxManagerServer txManagerServer = new TxManagerServer(); txManagerServer.setHost(txManagerInfo.getIp()); txManagerServer.setPort(txManagerInfo.getPort()); return txManagerServer; } } } return null; }
/** * 获取需要提交的事务 * * @return List<TransactionRecover> */ @Override public List<TransactionRecover> listAll() { String selectSql = "select * from " + tableName; List<Map<String, Object>> list = executeQuery(selectSql); if (CollectionUtils.isNotEmpty(list)) { return list.stream().filter(Objects::nonNull) .map(this::buildByMap).collect(Collectors.toList()); } return null; }