List of usage examples for java.util Arrays stream
public static DoubleStream stream(double[] array)
From source file:io.gravitee.reporter.elastic.engine.impl.AbstractElasticReportEngine.java
protected XContentBuilder getSource(Monitor monitor) throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder().startObject(); if (monitor.getOs() != null) { builder.startObject(Fields.OS);//from w w w. j a v a2 s.co m if (monitor.getOs().cpu != null) { builder.startObject(Fields.CPU); builder.field(Fields.PERCENT, monitor.getOs().cpu.getPercent()); if (monitor.getOs().cpu.getLoadAverage() != null && Arrays.stream(monitor.getOs().cpu.getLoadAverage()).anyMatch(load -> load != -1)) { builder.startObject(Fields.LOAD_AVERAGE); if (monitor.getOs().cpu.getLoadAverage()[0] != -1) { builder.field(Fields.LOAD_AVERAGE_1M, monitor.getOs().cpu.getLoadAverage()[0]); } if (monitor.getOs().cpu.getLoadAverage()[1] != -1) { builder.field(Fields.LOAD_AVERAGE_5M, monitor.getOs().cpu.getLoadAverage()[1]); } if (monitor.getOs().cpu.getLoadAverage()[2] != -1) { builder.field(Fields.LOAD_AVERAGE_15M, monitor.getOs().cpu.getLoadAverage()[2]); } builder.endObject(); } builder.endObject(); } if (monitor.getOs().mem != null) { builder.startObject(Fields.MEM); builder.byteSizeField(Fields.TOTAL_IN_BYTES, Fields.TOTAL, new ByteSizeValue(monitor.getOs().mem.getTotal())); builder.byteSizeField(Fields.FREE_IN_BYTES, Fields.FREE, new ByteSizeValue(monitor.getOs().mem.getFree())); builder.byteSizeField(Fields.USED_IN_BYTES, Fields.USED, new ByteSizeValue(monitor.getOs().mem.getUsed())); builder.field(Fields.FREE_PERCENT, monitor.getOs().mem.getFreePercent()); builder.field(Fields.USED_PERCENT, monitor.getOs().mem.getUsedPercent()); builder.endObject(); } builder.endObject(); } if (monitor.getProcess() != null) { builder.startObject(Fields.PROCESS); builder.field(Fields.TIMESTAMP, monitor.getProcess().timestamp); builder.field(Fields.OPEN_FILE_DESCRIPTORS, monitor.getProcess().openFileDescriptors); builder.field(Fields.MAX_FILE_DESCRIPTORS, monitor.getProcess().maxFileDescriptors); builder.endObject(); } if (monitor.getJvm() != null) { builder.startObject(Fields.JVM); builder.field(Fields.TIMESTAMP, monitor.getJvm().timestamp); builder.timeValueField(Fields.UPTIME_IN_MILLIS, Fields.UPTIME, monitor.getJvm().uptime); if (monitor.getJvm().mem != null) { builder.startObject(Fields.MEM); builder.byteSizeField(Fields.HEAP_USED_IN_BYTES, Fields.HEAP_USED, monitor.getJvm().mem.heapUsed); if (monitor.getJvm().mem.getHeapUsedPercent() >= 0) { builder.field(Fields.HEAP_USED_PERCENT, monitor.getJvm().mem.getHeapUsedPercent()); } builder.byteSizeField(Fields.HEAP_COMMITTED_IN_BYTES, Fields.HEAP_COMMITTED, monitor.getJvm().mem.heapCommitted); builder.byteSizeField(Fields.HEAP_MAX_IN_BYTES, Fields.HEAP_MAX, monitor.getJvm().mem.heapMax); builder.byteSizeField(Fields.NON_HEAP_USED_IN_BYTES, Fields.NON_HEAP_USED, monitor.getJvm().mem.nonHeapUsed); builder.byteSizeField(Fields.NON_HEAP_COMMITTED_IN_BYTES, Fields.NON_HEAP_COMMITTED, monitor.getJvm().mem.nonHeapCommitted); builder.startObject(Fields.POOLS); for (JvmInfo.MemoryPool pool : monitor.getJvm().mem.pools) { builder.startObject(pool.getName(), XContentBuilder.FieldCaseConversion.NONE); builder.byteSizeField(Fields.USED_IN_BYTES, Fields.USED, pool.used); builder.byteSizeField(Fields.MAX_IN_BYTES, Fields.MAX, pool.max); builder.byteSizeField(Fields.PEAK_USED_IN_BYTES, Fields.PEAK_USED, pool.peakUsed); builder.byteSizeField(Fields.PEAK_MAX_IN_BYTES, Fields.PEAK_MAX, pool.peakMax); builder.endObject(); } builder.endObject(); builder.endObject(); } if (monitor.getJvm().threads != null) { builder.startObject(Fields.THREADS); builder.field(Fields.COUNT, monitor.getJvm().threads.getCount()); builder.field(Fields.PEAK_COUNT, monitor.getJvm().threads.getPeakCount()); builder.endObject(); } if (monitor.getJvm().gc != null) { builder.startObject(Fields.GC); builder.startObject(Fields.COLLECTORS); for (JvmInfo.GarbageCollector collector : monitor.getJvm().gc.collectors) { builder.startObject(collector.getName(), XContentBuilder.FieldCaseConversion.NONE); builder.field(Fields.COLLECTION_COUNT, collector.getCollectionCount()); builder.timeValueField(Fields.COLLECTION_TIME_IN_MILLIS, Fields.COLLECTION_TIME, new TimeValue(collector.collectionTime, TimeUnit.MILLISECONDS)); builder.endObject(); } builder.endObject(); builder.endObject(); } builder.endObject(); } builder.field(Fields.GATEWAY, monitor.gateway()).field(Fields.HOSTNAME, hostname) .field(Fields.SPECIAL_TIMESTAMP, Date.from(monitor.timestamp()), dtf).endObject(); return builder; }
From source file:eu.itesla_project.online.tools.OnlineWorkflowTool.java
@Override public void run(CommandLine line) throws Exception { OnlineWorkflowStartParameters startconfig = OnlineWorkflowStartParameters.loadDefault(); String host = line.getOptionValue(OnlineWorkflowCommand.HOST); String port = line.getOptionValue(OnlineWorkflowCommand.PORT); String threads = line.getOptionValue(OnlineWorkflowCommand.THREADS); if (host != null) startconfig.setJmxHost(host);/* w w w.j a v a 2 s. co m*/ if (port != null) startconfig.setJmxPort(Integer.valueOf(port)); if (threads != null) startconfig.setThreads(Integer.valueOf(threads)); Set<DateTime> baseCasesSet = null; OnlineWorkflowParameters params = OnlineWorkflowParameters.loadDefault(); boolean atLeastOneBaseCaseLineParam = line.hasOption(OnlineWorkflowCommand.CASE_TYPE) || line.hasOption(OnlineWorkflowCommand.COUNTRIES) || line.hasOption(OnlineWorkflowCommand.BASE_CASE) || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL); boolean allNeededBaseCaseLineParams = line.hasOption(OnlineWorkflowCommand.CASE_TYPE) && line.hasOption(OnlineWorkflowCommand.COUNTRIES) && (line.hasOption(OnlineWorkflowCommand.BASE_CASE) || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL)); if (line.hasOption(OnlineWorkflowCommand.CASE_FILE)) { if (atLeastOneBaseCaseLineParam) { showHelp("parameter " + OnlineWorkflowCommand.CASE_FILE + " cannot be used together with parameters: " + OnlineWorkflowCommand.CASE_TYPE + ", " + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE + ", " + OnlineWorkflowCommand.BASECASES_INTERVAL); return; } params.setCaseFile(line.getOptionValue(OnlineWorkflowCommand.CASE_FILE)); } else { if (params.getCaseFile() != null) { if (atLeastOneBaseCaseLineParam) { if (!allNeededBaseCaseLineParams) { showHelp("to override default parameter " + OnlineWorkflowCommand.CASE_FILE + ", all these parameters must be specified: " + OnlineWorkflowCommand.CASE_TYPE + ", " + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE + " or " + OnlineWorkflowCommand.BASECASES_INTERVAL); return; } params.setCaseFile(null); } } if (line.hasOption(OnlineWorkflowCommand.CASE_TYPE)) params.setCaseType(CaseType.valueOf(line.getOptionValue(OnlineWorkflowCommand.CASE_TYPE))); if (line.hasOption(OnlineWorkflowCommand.COUNTRIES)) { params.setCountries(Arrays.stream(line.getOptionValue(OnlineWorkflowCommand.COUNTRIES).split(",")) .map(Country::valueOf).collect(Collectors.toSet())); } if (line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL)) { Interval basecasesInterval = Interval .parse(line.getOptionValue(OnlineWorkflowCommand.BASECASES_INTERVAL)); OnlineConfig oConfig = OnlineConfig.load(); CaseRepository caseRepo = oConfig.getCaseRepositoryFactoryClass().newInstance() .create(new LocalComputationManager()); baseCasesSet = caseRepo.dataAvailable(params.getCaseType(), params.getCountries(), basecasesInterval); System.out.println("Base cases available for interval " + basecasesInterval.toString()); baseCasesSet.forEach(x -> { System.out.println(" " + x); }); } if (baseCasesSet == null) { baseCasesSet = new HashSet<>(); String base = line.getOptionValue(OnlineWorkflowCommand.BASE_CASE); if (base != null) { baseCasesSet.add(DateTime.parse(base)); } else { baseCasesSet.add(params.getBaseCaseDate()); } } } String histo = line.getOptionValue(OnlineWorkflowCommand.HISTODB_INTERVAL); if (histo != null) params.setHistoInterval(Interval.parse(histo)); String states = line.getOptionValue(OnlineWorkflowCommand.STATES); if (states != null) params.setStates(Integer.parseInt(states)); String timeHorizon = line.getOptionValue(OnlineWorkflowCommand.TIME_HORIZON); if (timeHorizon != null) params.setTimeHorizon(TimeHorizon.fromName(timeHorizon)); String workflowid = line.getOptionValue(OnlineWorkflowCommand.WORKFLOW_ID); if (workflowid != null) params.setOfflineWorkflowId(workflowid); String feAnalysisId = line.getOptionValue(OnlineWorkflowCommand.FEANALYSIS_ID); if (feAnalysisId != null) params.setFeAnalysisId(feAnalysisId); String rulesPurity = line.getOptionValue(OnlineWorkflowCommand.RULES_PURITY); if (rulesPurity != null) params.setRulesPurityThreshold(Double.parseDouble(rulesPurity)); if (line.hasOption(OnlineWorkflowCommand.STORE_STATES)) params.setStoreStates(true); if (line.hasOption(OnlineWorkflowCommand.ANALYSE_BASECASE)) params.setAnalyseBasecase(true); if (line.hasOption(OnlineWorkflowCommand.VALIDATION)) { params.setValidation(true); params.setStoreStates(true); // if validation then store states params.setAnalyseBasecase(true); // if validation then analyze base case } Set<SecurityIndexType> securityIndexes = null; if (line.hasOption(OnlineWorkflowCommand.SECURITY_INDEXES)) { if (!"ALL".equals(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES))) securityIndexes = Arrays .stream(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES).split(",")) .map(SecurityIndexType::valueOf).collect(Collectors.toSet()); params.setSecurityIndexes(securityIndexes); } if (line.hasOption(OnlineWorkflowCommand.MERGE_OPTIMIZED)) params.setMergeOptimized(true); String limitReduction = line.getOptionValue(OnlineWorkflowCommand.LIMIT_REDUCTION); if (limitReduction != null) params.setLimitReduction(Float.parseFloat(limitReduction)); if (line.hasOption(OnlineWorkflowCommand.HANDLE_VIOLATION_IN_N)) { params.setHandleViolationsInN(true); params.setAnalyseBasecase(true); // if I need to handle violations in N, I need to analyze base case } String constraintMargin = line.getOptionValue(OnlineWorkflowCommand.CONSTRAINT_MARGIN); if (constraintMargin != null) params.setConstraintMargin(Float.parseFloat(constraintMargin)); String urlString = "service:jmx:rmi:///jndi/rmi://" + startconfig.getJmxHost() + ":" + startconfig.getJmxPort() + "/jmxrmi"; JMXServiceURL serviceURL = new JMXServiceURL(urlString); Map<String, String> jmxEnv = new HashMap<>(); JMXConnector connector = JMXConnectorFactory.connect(serviceURL, jmxEnv); MBeanServerConnection mbsc = connector.getMBeanServerConnection(); ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME); LocalOnlineApplicationMBean application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name, LocalOnlineApplicationMBean.class, false); if (line.hasOption(OnlineWorkflowCommand.START_CMD)) { if (params.getCaseFile() != null) { System.out.println("starting Online Workflow, caseFile " + params.getCaseFile()); String workflowId = application.startWorkflow(startconfig, params); System.out.println("workflowId=" + workflowId); } else { for (DateTime basecase : baseCasesSet) { params.setBaseCaseDate(basecase); System.out.println("starting Online Workflow, basecase " + basecase.toString()); String workflowId = application.startWorkflow(startconfig, params); System.out.println("workflowId=" + workflowId); } } } else if (line.hasOption(OnlineWorkflowCommand.SHUTDOWN_CMD)) { application.shutdown(); } else { showHelp(""); } }
From source file:com.qq.tars.web.controller.server.ServerController.java
@RequestMapping(value = "server/api/send_command", produces = { "application/json" }) @ResponseBody/*ww w . j a v a 2s . c om*/ public List<CommandResult> sendCommand(@RequestParam("server_ids") String serverIds, @RequestParam String command) throws Exception { log.info("servers={}, command={}", serverIds, command); List<Long> ids = Arrays.stream(serverIds.split(";")).filter(StringUtils::isNotBlank).map(Long::parseLong) .collect(Collectors.toList()); List<CommandTarget> targets = serverService.loadServerConfs(ids).stream() .map(configFile -> mapper.map(configFile, CommandTarget.class)).collect(Collectors.toList()); return adminService.doCommand(targets, command); }
From source file:org.openlmis.fulfillment.service.FulfillmentNotificationService.java
private String getContent(Object object, String messageKey, Map<String, String> messageParams) { String content = messageService.localize(new Message(messageKey)).getMessage(); try {// w w w . j a va 2 s. c o m List<PropertyDescriptor> descriptors = Arrays.stream(getPropertyDescriptors(object.getClass())) .filter(d -> null != d.getReadMethod()).collect(Collectors.toList()); for (PropertyDescriptor descriptor : descriptors) { String target = "{" + descriptor.getName() + "}"; String replacement = String.valueOf(descriptor.getReadMethod().invoke(object)); content = content.replace(target, replacement); } for (Map.Entry<String, String> entry : messageParams.entrySet()) { String target = "{" + entry.getKey() + "}"; String replacement = entry.getValue(); content = content.replace(target, replacement); } } catch (IllegalAccessException | InvocationTargetException exp) { throw new IllegalStateException("Can't get access to getter method", exp); } return content; }
From source file:uk.dsxt.voting.client.ClientManager.java
public RequestResult vote(String votingId, String clientId, String votingChoice) { try {/*from w w w. j a va 2s .co m*/ final Voting voting = assetsHolder.getVoting(votingId); if (voting == null) { log.error("vote method failed. Couldn't find voting with id [{}]", votingId); return new RequestResult<>(APIException.VOTING_NOT_FOUND); } BigDecimal packetSize = assetsHolder.getClientPacketSize(votingId, clientId); if (packetSize == null) { log.error("vote method failed. Client not found or can not vote. votingId [{}] clientId [{}]", votingId, clientId); return new RequestResult<>(APIException.CLIENT_NOT_FOUND); } VotingChoice choice = mapper.readValue(votingChoice, VotingChoice.class); log.debug("Vote for voting [{}] from client [{}] received.", votingId, clientId); VoteResult result = new VoteResult(votingId, clientId, packetSize); for (Map.Entry<String, QuestionChoice> entry : choice.getQuestionChoices().entrySet()) { Optional<Question> question = Arrays.stream(voting.getQuestions()) .filter(q -> q.getId().equals(entry.getKey())).findAny(); if (!question.isPresent()) { log.error("vote method failed. Couldn't find question with id={} in votingId={}.", entry.getKey(), votingId); return new RequestResult<>(APIException.UNKNOWN_EXCEPTION); } for (Map.Entry<String, BigDecimal> answer : entry.getValue().getAnswerChoices().entrySet()) { if (answer.getValue().signum() == 0) continue; result.setAnswer(question.get().getId(), answer.getKey(), answer.getValue()); } } //generate xml body and get vote results VotingInfoWeb infoWeb = getVotingResults(result, voting, null, null); //serializing whole xml and put signature near xml (not using Sgnt field) String xmlBody = serializer.serialize(result, voting); signInfoByKey.put(generateKeyForDocument(clientId, votingId), new SignatureInfo(result, xmlBody)); infoWeb.setXmlBody(xmlBody); return new RequestResult<>(infoWeb, null); } catch (JsonMappingException je) { log.error("vote method failed. Couldn't parse votingChoice JSON. votingId: {}, votingChoice: {}", votingId, votingChoice, je.getMessage()); return new RequestResult<>(APIException.UNKNOWN_EXCEPTION); } catch (Exception e) { log.error(String.format( "vote method failed. Couldn't process votingChoice. votingId: %s, votingChoice: %s", votingId, votingChoice), e); return new RequestResult<>(APIException.UNKNOWN_EXCEPTION); } }
From source file:com.ejisto.modules.controller.wizard.installer.workers.LoadClassAction.java
private List<MockedField> getMockedFields(CtClass clazz, WebApplicationDescriptor descriptor) { List<MockedField> results; try {/* www .j a va 2s.c om*/ results = Arrays.stream(clazz.getDeclaredFields()).map(declaredField -> { final MockedField existing = mockedFieldsRepository .loadOptional(descriptor.getContextPath(), clazz.getName(), declaredField.getName()) .orElse(new MockedFieldDecorator()); MockedField mockedField = MockedFieldDecorator.copyOf(existing); mockedField.setContextPath(descriptor.getKey()); mockedField.setClassName(clazz.getName()); mockedField.setFieldName(declaredField.getName()); mockedField.setFieldType(getFieldTypeAsString(declaredField)); parseGenerics(declaredField, mockedField); return mockedField; }).collect(Collectors.toList()); CtClass zuperclazz = clazz.getSuperclass(); if (!zuperclazz.getName().startsWith("java")) { results.addAll(getMockedFields(zuperclazz, descriptor)); } } catch (Exception e) { listener.errorOccurred(buildErrorDescriptor(e)); results = Collections.emptyList(); } return results; }
From source file:com.yahoo.pulsar.common.naming.NamespaceBundleFactory.java
public static BundlesData getBundlesData(NamespaceBundles bundles) throws Exception { if (bundles == null) { return new BundlesData(); } else {/*from ww w .j a v a 2 s .c o m*/ List<String> boundaries = Arrays.stream(bundles.partitions).boxed().map(p -> format("0x%08x", p)) .collect(Collectors.toList()); return new BundlesData(boundaries); } }
From source file:cc.altruix.javaprologinterop.PlUtilsLogic.java
protected String composeVarNameTxt(String[] varNames) { final StringJoiner stringJoiner = new StringJoiner(","); Arrays.stream(varNames).forEach(x -> stringJoiner.add(x)); return stringJoiner.toString(); }
From source file:eu.itesla_project.online.tools.RunWcaOnStateTool.java
@Override public void run(CommandLine line) throws Exception { String workflowId = line.getOptionValue("workflow"); Integer stateId = Integer.valueOf(line.getOptionValue("state")); System.out.println("loading state " + stateId + " of workflow " + workflowId + " from the online db ..."); OnlineConfig config = OnlineConfig.load(); OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create(); // load the network Network network = onlinedb.getState(workflowId, stateId); if (network != null) { OnlineWorkflowParameters parameters = onlinedb.getWorkflowParameters(workflowId); String offlineWorkflowId = parameters.getOfflineWorkflowId(); if (line.hasOption("offline-workflow")) offlineWorkflowId = line.getOptionValue("offline-workflow"); Interval histoInterval = parameters.getHistoInterval(); if (line.hasOption("history-interval")) histoInterval = Interval.parse(line.getOptionValue("history-interval")); double purityThreshold = parameters.getRulesPurityThreshold(); if (line.hasOption("purity-threshold")) purityThreshold = Double.parseDouble(line.getOptionValue("purity-threshold")); Set<SecurityIndexType> securityIndexTypes = parameters.getSecurityIndexes(); if (line.hasOption("security-index-types")) { securityIndexTypes = Arrays.stream(line.getOptionValue("security-index-types").split(",")) .map(SecurityIndexType::valueOf).collect(Collectors.toSet()); }// ww w. jav a 2 s . c o m boolean stopWcaOnViolations = DEFAULT_STOP_WCA_ON_VIOLATIONS; if (line.hasOption("stop-on-violations")) { stopWcaOnViolations = Boolean.parseBoolean(line.getOptionValue("stop-on-violations")); } ComputationManager computationManager = new LocalComputationManager(); network.getStateManager().allowStateMultiThreadAccess(true); WCAParameters wcaParameters = new WCAParameters(histoInterval, offlineWorkflowId, securityIndexTypes, purityThreshold, stopWcaOnViolations); ContingenciesAndActionsDatabaseClient contingenciesDb = config.getContingencyDbClientFactoryClass() .newInstance().create(); LoadFlowFactory loadFlowFactory = config.getLoadFlowFactoryClass().newInstance(); try (HistoDbClient histoDbClient = config.getHistoDbClientFactoryClass().newInstance().create(); RulesDbClient rulesDbClient = config.getRulesDbClientFactoryClass().newInstance() .create("rulesdb")) { UncertaintiesAnalyserFactory uncertaintiesAnalyserFactory = config .getUncertaintiesAnalyserFactoryClass().newInstance(); WCA wca = config.getWcaFactoryClass().newInstance().create(network, computationManager, histoDbClient, rulesDbClient, uncertaintiesAnalyserFactory, contingenciesDb, loadFlowFactory); WCAResult result = wca.run(wcaParameters); Table table = new Table(7, BorderStyle.CLASSIC_WIDE); table.addCell("Contingency", new CellStyle(CellStyle.HorizontalAlign.center)); table.addCell("Cluster 1", new CellStyle(CellStyle.HorizontalAlign.center)); table.addCell("Cluster 2", new CellStyle(CellStyle.HorizontalAlign.center)); table.addCell("Cluster 3", new CellStyle(CellStyle.HorizontalAlign.center)); table.addCell("Cluster 4", new CellStyle(CellStyle.HorizontalAlign.center)); table.addCell("Undefined", new CellStyle(CellStyle.HorizontalAlign.center)); table.addCell("Cause", new CellStyle(CellStyle.HorizontalAlign.center)); for (WCACluster cluster : result.getClusters()) { table.addCell(cluster.getContingency().getId()); int[] clusterIndexes = new int[] { 1, 2, 3, 4, -1 }; for (int k = 0; k < clusterIndexes.length; k++) { if (clusterIndexes[k] == cluster.getNum().toIntValue()) { table.addCell("X", new CellStyle(CellStyle.HorizontalAlign.center)); } else { table.addCell("-", new CellStyle(CellStyle.HorizontalAlign.center)); } } table.addCell(Objects.toString(cluster.getCauses(), ""), new CellStyle(CellStyle.HorizontalAlign.center)); } System.out.println(table.render()); } } }
From source file:com.netflix.spinnaker.halyard.config.model.v1.node.Node.java
public List<Field> localFiles() { Class<?> clazz = getClass(); List<Field> res = new ArrayList<>(); while (clazz != null) { res.addAll(Arrays.stream(clazz.getDeclaredFields()) .filter(f -> f.getDeclaredAnnotation(LocalFile.class) != null).collect(Collectors.toList())); clazz = clazz.getSuperclass();//from www .j ava 2s .co m } return res; }