List of usage examples for java.util Arrays stream
public static DoubleStream stream(double[] array)
From source file:com.uber.hoodie.common.table.view.HoodieTableFileSystemView.java
private Stream<HoodieDataFile> convertFileStatusesToDataFiles(FileStatus[] statuses) { Predicate<FileStatus> roFilePredicate = fileStatus -> fileStatus.getPath().getName() .contains(metaClient.getTableConfig().getROFileFormat().getFileExtension()); return Arrays.stream(statuses).filter(roFilePredicate).map(HoodieDataFile::new); }
From source file:com.simiacryptus.mindseye.lang.Layer.java
/** * Eval nn result./*from w w w .ja v a2 s .co m*/ * * @param array the array * @return the nn result */ @Nullable default Result eval(Result... array) { Arrays.stream(array).forEach(ReferenceCounting::addRef); Arrays.stream(array).map(Result::getData).forEach(ReferenceCounting::addRef); return evalAndFree(array); }
From source file:eu.itesla_project.modules.rules.CheckSecurityTool.java
@Override public void run(CommandLine line) throws Exception { OfflineConfig config = OfflineConfig.load(); Path caseFile = Paths.get(line.getOptionValue("case-file")); Objects.requireNonNull(caseFile); String rulesDbName = line.hasOption("rules-db-name") ? line.getOptionValue("rules-db-name") : OfflineConfig.DEFAULT_RULES_DB_NAME; RulesDbClientFactory rulesDbClientFactory = config.getRulesDbClientFactoryClass().newInstance(); String workflowId = line.getOptionValue("workflow"); RuleAttributeSet attributeSet = RuleAttributeSet.valueOf(line.getOptionValue("attribute-set")); double purityThreshold = line.hasOption("purity-threshold") ? Double.parseDouble(line.getOptionValue("purity-threshold")) : CheckSecurityCommand.DEFAULT_PURITY_THRESHOLD; Path outputCsvFile = null;//w w w.j ava2 s . c om if (line.hasOption("output-csv-file")) { outputCsvFile = Paths.get(line.getOptionValue("output-csv-file")); } Set<SecurityIndexType> securityIndexTypes = line.hasOption("security-index-types") ? Arrays.stream(line.getOptionValue("security-index-types").split(",")) .map(SecurityIndexType::valueOf).collect(Collectors.toSet()) : EnumSet.allOf(SecurityIndexType.class); final Set<String> contingencies = line.hasOption("contingencies") ? Arrays.stream(line.getOptionValue("contingencies").split(",")).collect(Collectors.toSet()) : null; try (RulesDbClient rulesDb = rulesDbClientFactory.create(rulesDbName)) { if (Files.isRegularFile(caseFile)) { System.out.println("loading case " + caseFile + "..."); // load the network Network network = Importers.loadNetwork(caseFile); if (network == null) { throw new RuntimeException("Case '" + caseFile + "' not found"); } network.getStateManager().allowStateMultiThreadAccess(true); System.out.println("checking rules..."); Map<String, Map<SecurityIndexType, SecurityRuleCheckStatus>> checkStatusPerContingency = SecurityRuleUtil .checkRules(network, rulesDb, workflowId, attributeSet, securityIndexTypes, contingencies, purityThreshold); if (outputCsvFile == null) { prettyPrint(checkStatusPerContingency, securityIndexTypes); } else { writeCsv(checkStatusPerContingency, securityIndexTypes, outputCsvFile); } } else if (Files.isDirectory(caseFile)) { if (outputCsvFile == null) { throw new RuntimeException( "In case of multiple impact security checks, only output to csv file is supported"); } Map<String, Map<SecurityIndexId, SecurityRuleCheckStatus>> checkStatusPerBaseCase = Collections .synchronizedMap(new LinkedHashMap<>()); Importers.loadNetworks(caseFile, true, network -> { try { Map<String, Map<SecurityIndexType, SecurityRuleCheckStatus>> checkStatusPerContingency = SecurityRuleUtil .checkRules(network, rulesDb, workflowId, attributeSet, securityIndexTypes, contingencies, purityThreshold); Map<SecurityIndexId, SecurityRuleCheckStatus> checkStatusMap = new HashMap<>(); for (Map.Entry<String, Map<SecurityIndexType, SecurityRuleCheckStatus>> entry : checkStatusPerContingency .entrySet()) { String contingencyId = entry.getKey(); for (Map.Entry<SecurityIndexType, SecurityRuleCheckStatus> entry1 : entry.getValue() .entrySet()) { SecurityIndexType type = entry1.getKey(); SecurityRuleCheckStatus status = entry1.getValue(); checkStatusMap.put(new SecurityIndexId(contingencyId, type), status); } } checkStatusPerBaseCase.put(network.getId(), checkStatusMap); } catch (Exception e) { LOGGER.error(e.toString(), e); } }, dataSource -> System.out.println("loading case " + dataSource.getBaseName() + "...")); writeCsv2(checkStatusPerBaseCase, outputCsvFile); } } }
From source file:alfio.config.MvcConfiguration.java
@Bean public HandlerInterceptor getEventLocaleSetterInterceptor() { return new HandlerInterceptorAdapter() { @Override/*from w w w . j a v a 2 s . c o m*/ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = ((HandlerMethod) handler); RequestMapping reqMapping = handlerMethod.getMethodAnnotation(RequestMapping.class); //check if the request mapping value has the form "/event/{something}" Pattern eventPattern = Pattern.compile("^/event/\\{(\\w+)}/{0,1}.*"); if (reqMapping != null && reqMapping.value().length == 1 && eventPattern.matcher(reqMapping.value()[0]).matches()) { Matcher m = eventPattern.matcher(reqMapping.value()[0]); m.matches(); String pathVariableName = m.group(1); //extract the parameter name Arrays.stream(handlerMethod.getMethodParameters()) .map(methodParameter -> methodParameter.getParameterAnnotation(PathVariable.class)) .filter(Objects::nonNull).map(PathVariable::value).filter(pathVariableName::equals) .findFirst().ifPresent((val) -> { //fetch the parameter value @SuppressWarnings("unchecked") String eventName = Optional.ofNullable(((Map<String, Object>) request .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE)) .get(val)) .orElse("").toString(); LocaleResolver resolver = RequestContextUtils.getLocaleResolver(request); Locale locale = resolver.resolveLocale(request); List<ContentLanguage> cl = i18nManager.getEventLanguages(eventName); request.setAttribute("ALFIO_EVENT_NAME", eventName); if (cl.stream().noneMatch( contentLanguage -> contentLanguage.getLanguage().equals(Optional .ofNullable(locale).orElse(Locale.ENGLISH).getLanguage()))) { //override the user locale if it's not in the one permitted by the event resolver.setLocale(request, response, cl.stream().findFirst() .map(ContentLanguage::getLocale).orElse(Locale.ENGLISH)); } else { resolver.setLocale(request, response, locale); } }); } } return true; } }; }
From source file:org.ow2.proactive.connector.iaas.cloud.provider.jclouds.JCloudsProvider.java
protected String buildScriptToExecuteString(InstanceScript instanceScript) { return Optional.ofNullable(instanceScript).map(scriptToRun -> { ScriptBuilder scriptBuilder = new ScriptBuilder(); Arrays.stream(scriptToRun.getScripts()) .forEachOrdered(script -> scriptBuilder.addStatement(exec(script))); return scriptBuilder.render(OsFamily.UNIX); }).orElse(""); }
From source file:com.epam.jdi.uitests.mobile.appium.elements.complex.table.EntityTable.java
private void setEntityField(E entity, Field[] fields, String fieldName, String value) { Optional<Field> opt = Arrays.stream(fields).filter(f -> f.getName().equalsIgnoreCase(fieldName)) .findFirst();//w ww. ja v a 2 s. c om if (!opt.isPresent()) { return; } Field field = opt.get(); try { FieldUtils.writeField(field, entity, ReflectionUtils.convertStringToType(value, field), true); } catch (IllegalAccessException e) { e.printStackTrace(); } }
From source file:org.bremersee.common.spring.autoconfigure.LdaptiveInMemoryDirectoryServerProperties.java
public String[] getSchemaLocationsAsArray() { if (StringUtils.hasText(schemaLocations)) { String[] values = schemaLocations.split(Pattern.quote(",")); return Arrays.stream(values).map(String::trim).toArray(size -> new String[size]); }// www . j av a 2s .c o m return new String[0]; }
From source file:com.hurence.logisland.documentation.DocGenerator.java
/** * Generates documentation into the work/docs dir specified from a specified set of class *///from w w w .j ava 2 s . co m public static void generate(final File docsDirectory, final String writerType) { Map<String, Class> extensionClasses = new TreeMap<>(); PluginLoader.getRegistry().forEach((className, classLoader) -> { try { extensionClasses.put(className, classLoader.loadClass(className)); } catch (Exception e) { logger.error("Unable to load class " + className, e); } }); ClassFinder.findClasses(clazz -> { if (!clazz.startsWith("BOOT-INF") && clazz.contains("logisland") && !clazz.contains("Mock") && !clazz.contains("shade")) { try { Class c = Class.forName(clazz); if (c.isAssignableFrom(ConfigurableComponent.class) && !Modifier.isAbstract(c.getModifiers())) { extensionClasses.put(c.getSimpleName(), c); } } catch (Throwable e) { logger.error("Unable to load class " + clazz + " : " + e.getMessage()); } } return true; // return false if you don't want to see any more classes }); docsDirectory.mkdirs(); // write headers for single rst file if (writerType.equals("rst")) { final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType); if (baseDocumenationFile.exists()) baseDocumenationFile.delete(); try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) { writer.println("Components"); writer.println("=========="); writer.println( "You'll find here the list of all usable Processors, Engines, Services and other components " + "that can be usable out of the box in your analytics streams"); writer.println(); } catch (FileNotFoundException e) { logger.warn(e.getMessage()); } } else if (writerType.equals("json")) { final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType); if (baseDocumenationFile.exists()) baseDocumenationFile.delete(); try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) { writer.println("["); } catch (FileNotFoundException e) { logger.warn(e.getMessage()); } } Class[] sortedExtensionsClasses = new Class[extensionClasses.size()]; extensionClasses.values(). toArray(sortedExtensionsClasses); Arrays.sort(sortedExtensionsClasses, new Comparator<Class>() { @Override public int compare(Class s1, Class s2) { // the +1 is to avoid including the '.' in the extension and to avoid exceptions // EDIT: // We first need to make sure that either both files or neither file // has an extension (otherwise we'll end up comparing the extension of one // to the start of the other, or else throwing an exception) final int s1Dot = s1.getName().lastIndexOf('.'); final int s2Dot = s2.getName().lastIndexOf('.'); if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither String s1Name = s1.getName().substring(s1Dot + 1); String s2Name = s2.getName().substring(s2Dot + 1); return s1Name.compareTo(s2Name); } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first return -1; } else { // only s1 has an extension, so s1 goes second return 1; } } }); logger.info("Generating " + writerType + " documentation for " + Arrays.stream(sortedExtensionsClasses). count() + " components in: " + docsDirectory); Arrays.stream(sortedExtensionsClasses). forEach(extensionClass -> { final Class componentClass = extensionClass.asSubclass(ConfigurableComponent.class); try { document(docsDirectory, componentClass, writerType); } catch (Exception e) { logger.error("Unexpected error for " + extensionClass, e); } }); if (writerType.equals("json")) { final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType); try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) { writer.println("]"); } catch (FileNotFoundException e) { logger.warn(e.getMessage()); } } }
From source file:org.leandreck.endpoints.processor.model.TypeNodeFactory.java
@SuppressWarnings("unchecked") private static boolean isLombokAnnotatedType(final TypeMirror typeMirror, final Types typeUtils) { return Arrays.stream(new String[] { "lombok.Data", "lombok.Value", "lombok.Getter" }) .anyMatch(annotationName -> { try { Class dataAnnotationClass = Class.forName(annotationName); Object dataAnnotation = TypeNodeUtils.getAnnotationForClass(typeMirror, dataAnnotationClass, typeUtils);/*from w w w.j ava2 s .c o m*/ return (dataAnnotation != null); } catch (Exception e) { //ignored } return false; }); }
From source file:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticle.java
private void deployOrientDBRepositoryVerticles() { if (ArrayUtils.isEmpty(orientDBRepositoryVerticleDeployments)) { return;/*w ww . j a v a 2 s.c o m*/ } final Set<RunRightFastVerticleDeployment> deployments = Arrays.stream(orientDBRepositoryVerticleDeployments) .map(deployment -> { return new RunRightFastVerticleDeployment(() -> { final OrientDBRepositoryVerticle repo = deployment.getOrientDBRepositoryVerticle().get(); repo.setOrientDBService(service); return repo; }, deployment.getOrientDBRepositoryVerticleClass(), deployment.getDeploymentOptions()); }).collect(Collectors.toSet()); deployVerticles(deployments); }