@Override public Page<T> findAll(final Set<T> groups, final String criteria, final Pageable pageable, final Map<String, Comparator<T>> customComparators) { // Create the set with the right comparator final List<Sort.Order> orders = IteratorUtils.toList(ObjectUtils.defaultIfNull(pageable.getSort(), new ArrayList<Sort.Order>()).iterator()); orders.add(DEFAULT_ORDER); final Sort.Order order = orders.get(0); Comparator<T> comparator = customComparators.get(order.getProperty()); if (order.getDirection() == Direction.DESC) { comparator = Collections.reverseOrder(comparator); } final Set<T> result = new TreeSet<>(comparator); // Filter the groups, filtering by the criteria addFilteredByPattern(groups, criteria, result); // Apply in-memory pagination return inMemoryPagination.newPage(result, pageable); }
/** * Complete the standard data with temporal data (not SLA), sub task, and components */ @Override protected void writeIssueData(final IssueDetails issue, final Writer writer, final Format df, final Format idf) throws IOException { // Write static data super.writeIssueData(issue, writer, df, idf); // Time spent writer.write(';'); writer.write(String.valueOf(ObjectUtils.defaultIfNull((Object) issue.getTimeSpent(), ""))); // Time estimate writer.write(';'); writer.write(String.valueOf(ObjectUtils.defaultIfNull((Object) issue.getTimeEstimate(), ""))); // Time initial estimate writer.write(';'); writer.write(String.valueOf(ObjectUtils.defaultIfNull((Object) issue.getTimeEstimateInit(), ""))); // Optional parent writer.write(';'); writer.write(String.valueOf(ObjectUtils.defaultIfNull(subTasks.get(issue.getId()), ""))); // Custom non fixed fields writeCustomData((IssueSla) issue, writer, df); }
@Override public void write(final Kryo kryo, final Output output, final RegisteredService service) { kryo.writeObject(output, service.getServiceId()); kryo.writeObject(output, StringUtils.defaultIfEmpty(service.getName(), "")); kryo.writeObject(output, StringUtils.defaultIfEmpty(service.getDescription(), "")); kryo.writeObject(output, service.getId()); kryo.writeObject(output, service.getEvaluationOrder()); kryo.writeObject(output, ObjectUtils.defaultIfNull(service.getLogo(), getEmptyUrl())); kryo.writeObject(output, service.getLogoutType()); kryo.writeObject(output, ObjectUtils.defaultIfNull(service.getLogoutUrl(), getEmptyUrl())); kryo.writeObject(output, ImmutableSet.copyOf(service.getRequiredHandlers())); kryo.writeObject(output, StringUtils.defaultIfEmpty(service.getTheme(), "")); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getPublicKey(), new RegisteredServicePublicKeyImpl())); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getProxyPolicy(), new RefuseRegisteredServiceProxyPolicy())); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getAttributeReleasePolicy(), new ReturnAllowedAttributeReleasePolicy())); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getUsernameAttributeProvider(), new DefaultRegisteredServiceUsernameProvider())); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getAccessStrategy(), new DefaultRegisteredServiceAccessStrategy())); }
private void save(final SlaEditionVo vo, final Sla entity) { DescribedBean.copy(vo, entity); entity.setStop(StringUtils.join(identifierHelper.normalize(vo.getStop()), ',')); entity.setStart(StringUtils.join(identifierHelper.normalize(vo.getStart()), ',')); entity.setThreshold(vo.getThreshold()); vo.setPause(ObjectUtils.defaultIfNull(vo.getPause(), new ArrayList<>())); vo.setPriorities(ObjectUtils.defaultIfNull(vo.getPriorities(), new ArrayList<>())); vo.setResolutions(ObjectUtils.defaultIfNull(vo.getResolutions(), new ArrayList<>())); vo.setTypes(ObjectUtils.defaultIfNull(vo.getTypes(), new ArrayList<>())); checkSlaBounds(vo); entity.setPause(StringUtils.join(identifierHelper.normalize(vo.getPause()), ',')); entity.setPriorities(StringUtils.join(vo.getPriorities(), ',')); entity.setResolutions(StringUtils.join(vo.getResolutions(), ',')); entity.setTypes(StringUtils.join(vo.getTypes(), ',')); slaRepository.saveAndFlush(entity); }
@Override public void write(final Kryo kryo, final Output output, final RegisteredService service) { kryo.writeObject(output, service.getServiceId()); kryo.writeObject(output, StringUtils.defaultIfEmpty(service.getName(), StringUtils.EMPTY)); kryo.writeObject(output, StringUtils.defaultIfEmpty(service.getDescription(), StringUtils.EMPTY)); kryo.writeObject(output, service.getId()); kryo.writeObject(output, service.getEvaluationOrder()); kryo.writeObject(output, ObjectUtils.defaultIfNull(service.getLogo(), getEmptyUrl())); kryo.writeObject(output, service.getLogoutType()); kryo.writeObject(output, ObjectUtils.defaultIfNull(service.getLogoutUrl(), getEmptyUrl())); kryo.writeObject(output, new HashSet<>(service.getRequiredHandlers())); kryo.writeObject(output, StringUtils.defaultIfEmpty(service.getTheme(), StringUtils.EMPTY)); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getPublicKey(), new RegisteredServicePublicKeyImpl())); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getProxyPolicy(), new RefuseRegisteredServiceProxyPolicy())); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getAttributeReleasePolicy(), new ReturnAllowedAttributeReleasePolicy())); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getUsernameAttributeProvider(), new DefaultRegisteredServiceUsernameProvider())); writeObjectByReflection(kryo, output, ObjectUtils.defaultIfNull(service.getAccessStrategy(), new DefaultRegisteredServiceAccessStrategy())); }
/** * Handle configuration modified event. * * @param event the event */ @EventListener public void handleConfigurationModifiedEvent(final CasConfigurationModifiedEvent event) { if (this.contextRefresher == null) { LOGGER.warn("Unable to refresh application context, since no refresher is available"); return; } if (event.isEligibleForContextRefresh()) { LOGGER.info("Received event [{}]. Refreshing CAS configuration...", event); Collection<String> keys = null; try { keys = this.contextRefresher.refresh(); LOGGER.debug("Refreshed the following settings: [{}].", keys); } catch (final Throwable e) { LOGGER.trace(e.getMessage(), e); } finally { rebind(); LOGGER.info("CAS finished rebinding configuration with new settings [{}]", ObjectUtils.defaultIfNull(keys, Collections.emptyList())); } } }
/** * Write issue data */ private void writeData(final JiraChangeItem change, final String key, final Writer writer, final Format df, final Format idf) throws IOException { // Write static data writer.write(change.getId().toString()); writer.write(';'); writer.write(key); writer.write(';'); writer.write(ObjectUtils.defaultIfNull(change.getAuthor(), change.getReporter())); writer.write(';'); writer.write(ObjectUtils.defaultIfNull(change.getFromStatus(), "").toString()); writer.write(';'); writer.write(String.valueOf(change.getToStatus())); writer.write(';'); writer.write(idf.format(ObjectUtils.defaultIfNull(statusText.get(change.getFromStatus()), ""))); writer.write(';'); writer.write(idf.format(statusText.get(change.getToStatus()))); writer.write(';'); writer.write(df.format(change.getCreated())); writer.write(';'); writer.write(String.valueOf(change.getCreated().getTime())); }
/** * 创建节点 * * @param path * @param data * @param mode * @return */ public boolean createNode(String path, String data, CreateMode mode) { if (!ObjectUtils.allNotNull(zkClient, path)) { return Boolean.FALSE; } try { Stat stat = exists(path); if (stat == null) { mode = mode == null ? CreateMode.PERSISTENT : mode; String opResult; if (ObjectUtils.allNotNull(data)) { opResult = zkClient.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path, data.getBytes(Charsets.UTF_8)); } else { opResult = zkClient.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path); } return Objects.equal(opResult, path); } return Boolean.TRUE; } catch (Exception e) { log.error("create node fail! path: {}, error: {}", path, e); } return Boolean.FALSE; }
/** * 删除节点 递归删除子节点 * * @param path * @param version * @return */ public boolean deleteNode(String path, Integer version) { if (!ObjectUtils.allNotNull(zkClient, path)) { return Boolean.FALSE; } try { Stat stat = exists(path); if (stat != null) { if (version == null) { zkClient.delete().deletingChildrenIfNeeded().forPath(path); } else { zkClient.delete().deletingChildrenIfNeeded().withVersion(version).forPath(path); } } return Boolean.TRUE; } catch (Exception e) { log.error("delete node fail! path: {}, error: {}", path, e); } return Boolean.FALSE; }
/** * 设置节点数据 * * @param path * @param data * @param version * @return */ public boolean setNodeData(String path, byte[] data, Integer version) { if (!ObjectUtils.allNotNull(zkClient, path)) { return Boolean.FALSE; } try { Stat stat = exists(path); if (stat != null) { if (version == null) { zkClient.setData().forPath(path, data); } else { zkClient.setData().withVersion(version).forPath(path, data); } return Boolean.TRUE; } } catch (Exception e) { log.error("set node data fail! path: {}, error: {}", path, e); } return Boolean.FALSE; }
/** * 设置子节点更改监听 * * @param path * @throws Exception */ public boolean listenerPathChildrenCache(String path, BiConsumer<CuratorFramework, PathChildrenCacheEvent> biConsumer) { if (!ObjectUtils.allNotNull(zkClient, path, biConsumer)) { return Boolean.FALSE; } try { Stat stat = exists(path); if (stat != null) { PathChildrenCache watcher = new PathChildrenCache(zkClient, path, true); watcher.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); //该模式下 watcher在重连的时候会自动 rebuild 否则需要重新rebuild watcher.getListenable().addListener(biConsumer::accept, pool); if (!pathChildrenCaches.contains(watcher)) { pathChildrenCaches.add(watcher); } // else{ // watcher.rebuild(); // } return Boolean.TRUE; } } catch (Exception e) { log.error("listen path children cache fail! path:{} , error:{}", path, e); } return Boolean.FALSE; }
/** * 读取指定节点的子菜单的值 * * @param path * @return */ public Map<String, String> readTargetChildsData(String path) { if (!ObjectUtils.allNotNull(zkClient, path)) { return null; } Map<String, String> map = null; try { Stat stat = exists(path); if (stat != null) { List<String> childrens = zkClient.getChildren().forPath(path); GetDataBuilder dataBuilder = zkClient.getData(); if (childrens != null) { map = childrens.stream().collect(Collectors.toMap(Function.identity(), (child) -> { try { return new String(dataBuilder.forPath(ZKPaths.makePath(path, child)), Charsets.UTF_8); } catch (Exception e1) { return null; } })); } } } catch (Exception e) { log.error("get target childs data fail!, path:{} , error:{}", path, e); } return map; }
/** * 创建响应URL * @param transOrder * @param backType 1:前台页面;2:后台接口 * @return */ public String createNotifyUrl(TransOrder transOrder, String backType) { String mchId = transOrder.getMchId(); MchInfo mchInfo = super.baseSelectMchInfo(mchId); String resKey = mchInfo.getResKey(); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("transOrderId", ObjectUtils.defaultIfNull(transOrder.getTransOrderId(), "")); // 转账订单号 paramMap.put("mchId", ObjectUtils.defaultIfNull(transOrder.getMchId(), "")); // 商户ID paramMap.put("mchOrderNo", ObjectUtils.defaultIfNull(transOrder.getMchTransNo(), "")); // 商户订单号 paramMap.put("channelId", ObjectUtils.defaultIfNull(transOrder.getChannelId(), "")); // 渠道ID paramMap.put("amount", ObjectUtils.defaultIfNull(transOrder.getAmount(), "")); // 支付金额 paramMap.put("currency", ObjectUtils.defaultIfNull(transOrder.getCurrency(), "")); // 货币类型 paramMap.put("status", ObjectUtils.defaultIfNull(transOrder.getStatus(), "")); // 转账状态 paramMap.put("result", ObjectUtils.defaultIfNull(transOrder.getResult(), "")); // 转账结果 paramMap.put("clientIp", ObjectUtils.defaultIfNull(transOrder.getClientIp(), "")); // 客户端IP paramMap.put("device", ObjectUtils.defaultIfNull(transOrder.getDevice(), "")); // 设备 paramMap.put("channelOrderNo", ObjectUtils.defaultIfNull(transOrder.getChannelOrderNo(), "")); // 渠道订单号 paramMap.put("param1", ObjectUtils.defaultIfNull(transOrder.getParam1(), "")); // 扩展参数1 paramMap.put("param2", ObjectUtils.defaultIfNull(transOrder.getParam2(), "")); // 扩展参数2 paramMap.put("transSuccTime", ObjectUtils.defaultIfNull(transOrder.getTransSuccTime(), "")); // 转账成功时间 paramMap.put("backType", backType==null ? "" : backType); // 先对原文签名 String reqSign = PayDigestUtil.getSign(paramMap, resKey); paramMap.put("sign", reqSign); // 签名 // 签名后再对有中文参数编码 try { paramMap.put("device", URLEncoder.encode(ObjectUtils.defaultIfNull(transOrder.getDevice(), ""), PayConstant.RESP_UTF8)); paramMap.put("param1", URLEncoder.encode(ObjectUtils.defaultIfNull(transOrder.getParam1(), ""), PayConstant.RESP_UTF8)); paramMap.put("param2", URLEncoder.encode(ObjectUtils.defaultIfNull(transOrder.getParam2(), ""), PayConstant.RESP_UTF8)); }catch (UnsupportedEncodingException e) { _log.error("URL Encode exception.", e); return null; } String param = XXPayUtil.genUrlParams(paramMap); StringBuffer sb = new StringBuffer(); sb.append(transOrder.getNotifyUrl()).append("?").append(param); return sb.toString(); }
/** * Upload a file of quote in add mode. * * @param subscription * The subscription identifier, will be used to filter the locations * from the associated provider. * @param uploadedFile * Instance entries files to import. Currently support only CSV * format. * @param columns * the CSV header names. * @param term * The default {@link ProvInstancePriceTerm} used when no one is * defined in the CSV line * @param ramMultiplier * The multiplier for imported RAM values. Default is 1. * @param encoding * CSV encoding. Default is UTF-8. * @throws IOException * When the CSV stream cannot be written. */ @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Path("{subscription:\\d+}/upload") public void upload(@PathParam("subscription") final int subscription, @Multipart(value = "csv-file") final InputStream uploadedFile, @Multipart(value = "columns", required = false) final String[] columns, @Multipart(value = "term", required = false) final String term, @Multipart(value = "memoryUnit", required = false) final Integer ramMultiplier, @Multipart(value = "encoding", required = false) final String encoding) throws IOException { subscriptionResource.checkVisibleSubscription(subscription).getNode().getId(); // Check column's name validity final String[] sanitizeColumns = ArrayUtils.isEmpty(columns) ? DEFAULT_COLUMNS : columns; checkHeaders(ACCEPTED_COLUMNS, sanitizeColumns); // Build CSV header from array final String csvHeaders = StringUtils.chop(ArrayUtils.toString(sanitizeColumns)).substring(1).replace(',', ';') + "\n"; // Build entries final String safeEncoding = ObjectUtils.defaultIfNull(encoding, StandardCharsets.UTF_8.name()); csvForBean .toBean(InstanceUpload.class, new InputStreamReader( new SequenceInputStream(new ByteArrayInputStream(csvHeaders.getBytes(safeEncoding)), uploadedFile), safeEncoding)) .stream().filter(Objects::nonNull).forEach(i -> persist(i, subscription, term, ramMultiplier)); }
protected void handleError(Throwable e) { if (engine != null) { if (engine.getInteractiveMode() != null) { engine.getInteractiveMode().getExceptionHandler().handleException(e, new GenericExceptionContext(engine, ObjectUtils.defaultIfNull(SpongeUtils.getSourceName(e), "interactive"))); } else { engine.handleError("standalone", e); } } else { if (e instanceof StandaloneInitializationException && !testMode) { System.out.println(e.getMessage()); System.out.println(""); builder.printHelp(); } else { logger.error("Error", e); } } if (testMode) { throw SpongeUtils.wrapException(e); } }
/** * Build a described {@link Vm} bean from a XML VMRecord entry. */ private VCloudVm toVm(final Element record) { final VCloudVm result = new VCloudVm(); result.setId(StringUtils.removeStart(record.getAttribute("id"), "urn:vcloud:vm:")); result.setName(record.getAttribute("name")); result.setOs(record.getAttribute("guestOs")); // Optional attributes result.setStorageProfileName(record.getAttribute("storageProfileName")); result.setStatus(EnumUtils.getEnum(VmStatus.class, record.getAttribute("status"))); result.setCpu(NumberUtils.toInt(StringUtils.trimToNull(record.getAttribute("numberOfCpus")))); result.setBusy(Boolean.parseBoolean(ObjectUtils.defaultIfNull(StringUtils.trimToNull(record.getAttribute("isBusy")), "false"))); result.setVApp(StringUtils.trimToNull(record.getAttribute("containerName"))); result.setVAppId(StringUtils.trimToNull(StringUtils.removeStart(record.getAttribute("container"), "urn:vcloud:vapp:"))); result.setRam(NumberUtils.toInt(StringUtils.trimToNull(record.getAttribute("memoryMB")))); result.setDeployed( Boolean.parseBoolean(ObjectUtils.defaultIfNull(StringUtils.trimToNull(record.getAttribute("isDeployed")), "false"))); return result; }
@Override public String getLastVersion() throws Exception { // Get the download json from the default repository final String portletVersions = new CurlProcessor().get( "https://my.vmware.com/web/vmware/downloads?p_p_id=ProductIndexPortlet_WAR_itdownloadsportlet&p_p_lifecycle=2&p_p_resource_id=allProducts"); // Extract the version from the rw String, because of the non stable // content format, but the links // Search for : "target": // "./info/slug/datacenter_cloud_infrastructure/vmware_vcloud_suite/6_0" final int linkIndex = Math.min( ObjectUtils.defaultIfNull(portletVersions, "").indexOf("vmware_vcloud_suite/") + "vmware_vcloud_suite/".length(), portletVersions.length()); return portletVersions.substring(linkIndex, Math.min(Math.max(portletVersions.indexOf('#', linkIndex), linkIndex), Math.max(portletVersions.indexOf('\"', linkIndex), linkIndex))); }
@SuppressWarnings("unchecked") @Override public String getVersion(final Map<String, String> parameters) throws Exception { final FortifyCurlProcessor processor = new FortifyCurlProcessor(); // Check the user can log-in to Fortify authenticate(parameters, processor); final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_URL), "/") + "api/v1/userSession/info"; final CurlRequest request = new CurlRequest("POST", url, null, "Accept: application/json"); request.setSaveResponse(true); processor.process(request); final String content = ObjectUtils.defaultIfNull(request.getResponse(), "{}"); final ObjectMapper mapper = new ObjectMapper(); final Map<String, ?> data = MapUtils .emptyIfNull((Map<String, ?>) mapper.readValue(content, Map.class).get("data")); final String version = (String) data.get("webappVersion"); processor.close(); return version; }
/** * Update internal user with the new user for following attributes : * department and local identifier. Note the security is not checked there. * * @param userOrg * The user to update. Note this must be the internal instance. * @param newUser * The new user data. Note this will not be the stored instance. */ public void mergeUser(final UserOrg userOrg, final UserOrg newUser) { boolean needUpdate = false; // Merge department if (ObjectUtils.notEqual(userOrg.getDepartment(), newUser.getDepartment())) { // Remove membership from the old department if exist Optional.ofNullable(toDepartmentGroup(userOrg.getDepartment())).ifPresent(g -> getGroup().removeUser(userOrg, g.getId())); // Add membership to the new department if exist Optional.ofNullable(toDepartmentGroup(newUser.getDepartment())).ifPresent(g -> getGroup().addUser(userOrg, g.getId())); userOrg.setDepartment(newUser.getDepartment()); needUpdate = true; } // Merge local identifier if (ObjectUtils.notEqual(userOrg.getLocalId(), newUser.getLocalId())) { userOrg.setLocalId(newUser.getLocalId()); } // Updated as needed if (needUpdate) { getUser().updateUser(userOrg); } }
private ImmutableList<Change> parseChanges(final ChangeType changeType, ImmutableList<FileObject> files, final DbChangeFileParser changeParser, final String schema) { return files.flatCollect(new Function<FileObject, ImmutableList<Change>>() { @Override public ImmutableList<Change> valueOf(FileObject file) { PackageMetadata packageMetadata = getPackageMetadata(file); String encoding = null; TextMarkupDocumentSection metadataSection = null; if (packageMetadata != null) { encoding = packageMetadata.getFileToEncodingMap().get(file.getName().getBaseName()); metadataSection = packageMetadata.getMetadataSection(); } CharsetStrategy charsetStrategy = CharsetStrategyFactory.getCharsetStrategy(ObjectUtils.defaultIfNull(encoding, env.getSourceEncoding())); final String objectName = file.getName().getBaseName().split("\\.")[0]; try { LOG.debug("Attempting to read file {}", file); return changeParser.value(changeType, file, file.getStringContent(charsetStrategy), objectName, schema, metadataSection); } catch (RuntimeException e) { throw new IllegalArgumentException("Error while parsing file " + file + " of change type " + changeType.getName() + "; please see the cause in the stack trace below: " + e.getMessage(), e); } } }); }
public void reveng(AquaRevengArgs args) { if (args.getInputPath() == null) { File file = printInstructions(System.out, args); System.out.println(""); System.out.println(""); if (file != null) { System.out.println("Interim reverse-engineering from the vendor tool is complete."); System.out.println("Content was written to: " + file); System.out.println("Proceeding with full reverse-engineering: " + file); System.out.println(""); System.out.println("*** In case the interim content had issues when reverse-engineering to the final output, you can update the interim files and restart from there (without going back to the DB) by specifying the following argument:"); System.out.println(" -inputPath " + ObjectUtils.defaultIfNull(args.getOutputPath(), "<outputFile>")); revengMain(file, args); } else { System.out.println("***********"); System.out.println(""); System.out.println("Once those steps are done, rerun the reverse-engineering command you just ran, but add the following argument based on the <outputDirectory> value passed in above the argument:"); System.out.println(" -inputPath " + ObjectUtils.defaultIfNull(args.getOutputPath(), "<outputFile>")); System.out.println(""); System.out.println("If you need more information on the vendor reverse engineer process, see the doc: https://goldmansachs.github.io/obevo/reverse-engineer-dbmstools.html"); } } else { revengMain(args.getInputPath(), args); } }
/** * Validate the space configuration and return the corresponding details. */ protected CurlRequest[] validateSpaceInternal(final Map<String, String> parameters, final String... partialRequests) { final String url = StringUtils.removeEnd(parameters.get(PARAMETER_URL), "/"); final String space = ObjectUtils.defaultIfNull(parameters.get(PARAMETER_SPACE), "0"); final CurlRequest[] result = new CurlRequest[partialRequests.length]; for (int i = 0; i < partialRequests.length; i++) { result[i] = new CurlRequest(HttpMethod.GET, url + partialRequests[i] + space, null); result[i].setSaveResponse(true); } // Prepare the sequence of HTTP requests to Confluence final ConfluenceCurlProcessor processor = new ConfluenceCurlProcessor(); authenticate(parameters, processor); // Execute the requests processor.process(result); // Get the space if it exists if (result[0].getResponse() == null) { // Invalid couple PKEY and id throw new ValidationJsonException(PARAMETER_SPACE, "confluence-space", parameters.get(PARAMETER_SPACE)); } return result; }
@Override public Page<UserOrg> findAll(final Collection<GroupOrg> requiredGroups, final Set<String> companies, final String criteria, final Pageable pageable) { // Create the set with the right comparator final List<Sort.Order> orders = IteratorUtils.toList(ObjectUtils.defaultIfNull(pageable.getSort(), new ArrayList<Sort.Order>()).iterator()); orders.add(DEFAULT_ORDER); final Sort.Order order = orders.get(0); Comparator<UserOrg> comparator = ObjectUtils.defaultIfNull(COMPARATORS.get(order.getProperty()), DEFAULT_COMPARATOR); if (order.getDirection() == Direction.DESC) { comparator = Collections.reverseOrder(comparator); } final Set<UserOrg> result = new TreeSet<>(comparator); // Filter the users traversing firstly the required groups and their members, the companies, then the criteria final Map<String, UserOrg> users = findAll(); if (requiredGroups == null) { // No constraint on group addFilteredByCompaniesAndPattern(users.keySet(), companies, criteria, result, users); } else { // User must be within one the given groups for (final GroupOrg requiredGroup : requiredGroups) { addFilteredByCompaniesAndPattern(requiredGroup.getMembers(), companies, criteria, result, users); } } // Apply in-memory pagination return inMemoryPagination.newPage(result, pageable); }
@Override public String getToken(final String login) { final AndFilter filter = new AndFilter(); filter.and(new EqualsFilter(OBJECT_CLASS, peopleClass)); filter.and(new EqualsFilter(uidAttribute, login)); return template.search(peopleBaseDn, filter.encode(), new AbstractContextMapper<String>() { @Override public String doMapFromContext(final DirContextOperations context) { // Get the password return new String(ObjectUtils.defaultIfNull((byte[]) context.getObjectAttribute(PASSWORD_ATTRIBUTE), new byte[0]), StandardCharsets.UTF_8); } }).stream().findFirst().orElse(null); }
/** * 处理支付结果后台服务器通知 */ public void doNotify(PayOrder payOrder, boolean isFirst) { _log.info(">>>>>> PAY开始回调通知业务系统 <<<<<<"); // 发起后台通知业务系统 JSONObject object = createNotifyInfo(payOrder, isFirst); try { mq4MchPayNotify.send(object.toJSONString()); } catch (Exception e) { _log.error(e, "payOrderId=%s,sendMessage error.", ObjectUtils.defaultIfNull(payOrder.getPayOrderId(), "")); } _log.info(">>>>>> PAY回调通知业务系统完成 <<<<<<"); }
/** * 创建响应URL * @param payOrder * @param backType 1:前台页面;2:后台接口 * @return */ public String createNotifyUrl(PayOrder payOrder, String backType) { String mchId = payOrder.getMchId(); MchInfo mchInfo = super.baseSelectMchInfo(mchId); String resKey = mchInfo.getResKey(); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("payOrderId", ObjectUtils.defaultIfNull(payOrder.getPayOrderId(), "")); // 支付订单号 paramMap.put("mchId", ObjectUtils.defaultIfNull(payOrder.getMchId(), "")); // 商户ID paramMap.put("mchOrderNo", ObjectUtils.defaultIfNull(payOrder.getMchOrderNo(), "")); // 商户订单号 paramMap.put("channelId", ObjectUtils.defaultIfNull(payOrder.getChannelId(), "")); // 渠道ID paramMap.put("amount", ObjectUtils.defaultIfNull(payOrder.getAmount(), "")); // 支付金额 paramMap.put("currency", ObjectUtils.defaultIfNull(payOrder.getCurrency(), "")); // 货币类型 paramMap.put("status", ObjectUtils.defaultIfNull(payOrder.getStatus(), "")); // 支付状态 paramMap.put("clientIp", ObjectUtils.defaultIfNull(payOrder.getClientIp(), "")); // 客户端IP paramMap.put("device", ObjectUtils.defaultIfNull(payOrder.getDevice(), "")); // 设备 paramMap.put("subject", ObjectUtils.defaultIfNull(payOrder.getSubject(), "")); // 商品标题 paramMap.put("channelOrderNo", ObjectUtils.defaultIfNull(payOrder.getChannelOrderNo(), "")); // 渠道订单号 paramMap.put("param1", ObjectUtils.defaultIfNull(payOrder.getParam1(), "")); // 扩展参数1 paramMap.put("param2", ObjectUtils.defaultIfNull(payOrder.getParam2(), "")); // 扩展参数2 paramMap.put("paySuccTime", ObjectUtils.defaultIfNull(payOrder.getPaySuccTime(), "")); // 支付成功时间 paramMap.put("backType", ObjectUtils.defaultIfNull(backType, "")); // 先对原文签名 String reqSign = PayDigestUtil.getSign(paramMap, resKey); paramMap.put("sign", reqSign); // 签名 // 签名后再对有中文参数编码 try { paramMap.put("device", URLEncoder.encode(ObjectUtils.defaultIfNull(payOrder.getDevice(), ""), PayConstant.RESP_UTF8)); paramMap.put("subject", URLEncoder.encode(ObjectUtils.defaultIfNull(payOrder.getSubject(), ""), PayConstant.RESP_UTF8)); paramMap.put("param1", URLEncoder.encode(ObjectUtils.defaultIfNull(payOrder.getParam1(), ""), PayConstant.RESP_UTF8)); paramMap.put("param2", URLEncoder.encode(ObjectUtils.defaultIfNull(payOrder.getParam2(), ""), PayConstant.RESP_UTF8)); }catch (UnsupportedEncodingException e) { _log.error("URL Encode exception.", e); return null; } String param = XXPayUtil.genUrlParams(paramMap); StringBuffer sb = new StringBuffer(); sb.append(payOrder.getNotifyUrl()).append("?").append(param); return sb.toString(); }
/** * For each change, increment the status counter. */ private Map<Integer, Integer> getStatusCounter(final IssueStatus issue) { final Map<Integer, Integer> satusCounter = new HashMap<>(); for (final StatusChange change : issue.getChanges()) { // Increment the counter for this status final int status = change.getStatus(); satusCounter.put(status, ObjectUtils.defaultIfNull(satusCounter.get(status), 0) + 1); } return satusCounter; }
public void sortObjectEntities() { objectEntityAdapters.sort((entity1, entity2) -> { return ObjectUtils.compare(entity1.nameProperty().get(), entity2.nameProperty().get()); }); }
/** * Gets headers. * * @return the headers */ public Map<String, String> getRequestHeaders(Object[] args) { if (CommonTools.isEmpty(headers)) { headers = new HashMap<>(); } if (!headers.containsKey(RestyConst.CONTENT_TYPE)) { headers.put(RestyConst.CONTENT_TYPE, RestyConst.APPLICATION_JSON); } if (args != null && args.length > 0 && !CommonTools.isEmpty(requestHeader)) { for (RequestHeaderData headerData : requestHeader) { headers.put(headerData.getName(), ObjectUtils.defaultIfNull(String.valueOf(args[headerData.getIndex()]), headerData.getDefaultValue())); } } return headers; }
/** * Gets request path. * * @param args the args * @return the request path */ public String getRequestPath(Object[] args) { if (this.pathVariables != null && this.pathVariables.size() > 0) { StringBuffer sb = new StringBuffer(64); Matcher matcher = pathVariableReg.matcher(this.path); while (matcher.find()) { String pathVariable = findPathVariable(matcher.group(), args); matcher.appendReplacement(sb, ObjectUtils.defaultIfNull(pathVariable, "")); } matcher.appendTail(sb); return sb.toString(); } else { return this.path; } }
private final void doCaculate(Map map, double least, String freeKey, String symbol) { List<List<String>> asks = (List<List<String>>) map.get("asks"); List<List<String>> bids = (List<List<String>>) map.get("bids"); List<String> firstBidPair = bids.get(0); List<String> firstAskPair = asks.get(asks.size() - 1); double firstBidPrice = Double.valueOf(firstBidPair.get(0)); double firstBidVolume = Double.valueOf(firstBidPair.get(1)); double firstAskPrice = Double.valueOf(firstAskPair.get(0)); double firstAskVolume = Double.valueOf(firstAskPair.get(1)); double bidPrice = firstBidPrice + 0.01f; //取最高买价 double askPrice = firstAskPrice - 0.01f; //取卖价卖价 if (hasProfit(bidPrice, askPrice)) { double cnyFree = free.getOrDefault("cny", 0.0d) - 500d; double ltcBalance = free.get(freeKey); if (ltcBalance < least && cnyFree >= askPrice * least) {//无币有钱,买币 sendOrder(bidPrice, cnyFree / bidPrice, bidType, symbol); } else if (ltcBalance >= least && cnyFree < askPrice * least) {//有币无钱,卖币 sendOrder(askPrice, ltcBalance, askType, symbol); } else if (ltcBalance >= least && cnyFree >= askPrice * least) {//有币有钱,卖币买币 double volume = ObjectUtils.min(cnyFree / bidPrice, ltcBalance); sendOrder(askPrice, volume, askType, symbol); sendOrder(bidPrice, volume, bidType, symbol); } else { LOGGER.error("no enough money and coins for {}", symbol); } } }
/** * 获取指定节点的值 * * @param path * @return */ public byte[] getNodeData(String path) { if (!ObjectUtils.allNotNull(zkClient, path)) { return null; } try { Stat stat = exists(path); if (stat != null) { return zkClient.getData().forPath(path); } } catch (Exception e) { log.error("get node data fail! path: {}, error: {}", path, e); } return null; }
/** * 检查节点是否存在 * * @param path * @return */ public Stat exists(String path) { if (!ObjectUtils.allNotNull(zkClient, path)) { return null; } try { return zkClient.checkExists().forPath(path); } catch (Exception e) { log.error("check node exists fail! path: {}, error: {}", path, e); } return null; }
public <T> void set(DataParameter<T> key, T value) { EntityDataManager.DataEntry<T> dataentry = this.<T>getEntry(key); if (ObjectUtils.notEqual(value, dataentry.getValue())) { dataentry.setValue(value); this.entity.notifyDataManagerChange(key); dataentry.setDirty(true); this.dirty = true; } }
public Baseline build() { if (!ObjectUtils.allNotNull(padding)) { throw new IllegalStateException("Missing required field."); } if (percent > 100) { throw new IllegalStateException("percent cannot be greater than 100."); } if (padding < 1) { throw new IllegalStateException("padding cannot be less than 1."); } return new Baseline(this); }
public <T> void updateObject(int id, T newData) { DataWatcher.WatchableObject datawatcher$watchableobject = this.getWatchedObject(id); if (ObjectUtils.notEqual(newData, datawatcher$watchableobject.getObject())) { datawatcher$watchableobject.setObject(newData); this.owner.onDataWatcherUpdate(id); datawatcher$watchableobject.setWatched(true); this.objectChanged = true; } }
private Entry(Object message, Profiler.Entry parentEntry, Profiler.Entry firstEntry) { this.subEntries = new ArrayList(4); this.message = message; this.startTime = System.currentTimeMillis(); this.parentEntry = parentEntry; this.firstEntry = (Profiler.Entry)ObjectUtils.defaultIfNull(firstEntry, this); this.baseTime = firstEntry == null ? 0L : firstEntry.startTime; }
/** * Add a cost to the quote related to given resource entity. The global cost is * not deeply computed, only delta is applied. * * @param entity * The configured entity, related to a quote. * @param costUpdater * The function used to compute the new cost. * @param <T> * The entity type holding the cost. * @return The new computed cost. */ default <T extends Costed> FloatingCost addCost(final T entity, final Function<T, FloatingCost> costUpdater) { // Save the previous costs final double oldCost = ObjectUtils.defaultIfNull(entity.getCost(), 0d); final double oldMaxCost = ObjectUtils.defaultIfNull(entity.getMaxCost(), 0d); // Process the update of this entity final FloatingCost newCost = costUpdater.apply(entity); // Report the delta to the quote final ProvQuote configuration = entity.getConfiguration(); configuration.setCost(round(configuration.getCost() + entity.getCost() - oldCost)); configuration.setMaxCost(round(configuration.getMaxCost() + entity.getMaxCost() - oldMaxCost)); return newCost; }
/** * Save or update the given entity from the {@link QuoteInstanceEditionVo}. The * computed cost are recursively updated from the instance to the quote total * cost. */ private UpdatedCost saveOrUpdate(final ProvQuoteInstance entity, final QuoteInstanceEditionVo vo) { // Compute the unbound cost delta final int deltaUnbound = BooleanUtils.toInteger(vo.getMaxQuantity() == null) - BooleanUtils.toInteger(entity.isUnboundCost()); // Check the associations and copy attributes to the entity final ProvQuote configuration = getQuoteFromSubscription(vo.getSubscription()); entity.setConfiguration(configuration); final Subscription subscription = configuration.getSubscription(); final String providerId = subscription.getNode().getRefined().getId(); DescribedBean.copy(vo, entity); entity.setPrice(ipRepository.findOneExpected(vo.getPrice())); entity.setLocation(resource.findLocation(subscription.getId(), vo.getLocation())); entity.setUsage(Optional.ofNullable(vo.getUsage()).map(u -> resource.findConfigured(usageRepository, u)).orElse(null)); entity.setOs(ObjectUtils.defaultIfNull(vo.getOs(), entity.getPrice().getOs())); entity.setRam(vo.getRam()); entity.setCpu(vo.getCpu()); entity.setConstant(vo.getConstant()); entity.setEphemeral(vo.isEphemeral()); entity.setInternet(vo.getInternet()); entity.setMaxVariableCost(vo.getMaxVariableCost()); entity.setMinQuantity(vo.getMinQuantity()); entity.setMaxQuantity(vo.getMaxQuantity()); resource.checkVisibility(entity.getPrice().getType(), providerId); checkConstraints(entity); checkOs(entity); // Update the unbound increment of the global quote configuration.setUnboundCostCounter(configuration.getUnboundCostCounter() + deltaUnbound); // Save and update the costs final UpdatedCost cost = newUpdateCost(entity); final Map<Integer, FloatingCost> storagesCosts = new HashMap<>(); CollectionUtils.emptyIfNull(entity.getStorages()) .forEach(s -> storagesCosts.put(s.getId(), addCost(s, storageResource::updateCost))); cost.setRelatedCosts(storagesCosts); cost.setTotalCost(toFloatingCost(entity.getConfiguration())); return cost; }