Example usage for java.util Arrays stream

List of usage examples for java.util Arrays stream

Introduction

In this page you can find the example usage for java.util Arrays stream.

Prototype

public static DoubleStream stream(double[] array) 

Source Link

Document

Returns a sequential DoubleStream with the specified array as its source.

Usage

From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java

/** Compiles a scala class
 * @param script// w  w  w.  j a v a2 s  . c  o  m
 * @param clazz_name
 * @return
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 */
public Tuple2<ClassLoader, Object> buildClass(final String script, final String clazz_name,
        final Optional<IBucketLogger> logger)
        throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    final String relative_dir = "./script_classpath/";
    new File(relative_dir).mkdirs();

    final File source_file = new File(relative_dir + clazz_name + ".scala");
    FileUtils.writeStringToFile(source_file, script);

    final String this_path = LiveInjector.findPathJar(this.getClass(), "./dummy.jar");
    final File f = new File(this_path);
    final File fp = new File(f.getParent());
    final String classpath = Arrays.stream(fp.listFiles()).map(ff -> ff.toString())
            .filter(ff -> ff.endsWith(".jar")).collect(Collectors.joining(":"));

    // Need this to make the URL classloader be used, not the system classloader (which doesn't know about Aleph2..)

    final Settings s = new Settings();
    s.classpath().value_$eq(System.getProperty("java.class.path") + classpath);
    s.usejavacp().scala$tools$nsc$settings$AbsSettings$AbsSetting$$internalSetting_$eq(true);
    final StoreReporter reporter = new StoreReporter();
    final Global g = new Global(s, reporter);
    final Run r = g.new Run();
    r.compile(JavaConverters.asScalaBufferConverter(Arrays.<String>asList(source_file.toString())).asScala()
            .toList());

    if (reporter.hasErrors() || reporter.hasWarnings()) {
        final String errors = "Compiler: Errors/warnings (**to get to user script line substract 22**): "
                + JavaConverters.asJavaSetConverter(reporter.infos()).asJava().stream()
                        .map(info -> info.toString()).collect(Collectors.joining(" ;; "));
        logger.ifPresent(l -> l.log(reporter.hasErrors() ? Level.ERROR : Level.DEBUG, false, () -> errors,
                () -> "SparkScalaInterpreterTopology", () -> "compile"));

        //ERROR:
        if (reporter.hasErrors()) {
            System.err.println(errors);
        }
    }
    // Move any class files (eg including sub-classes)
    Arrays.stream(fp.listFiles()).filter(ff -> ff.toString().endsWith(".class"))
            .forEach(Lambdas.wrap_consumer_u(ff -> {
                FileUtils.moveFile(ff, new File(relative_dir + ff.getName()));
            }));

    // Create a JAR file...

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    final JarOutputStream target = new JarOutputStream(new FileOutputStream("./script_classpath.jar"),
            manifest);
    Arrays.stream(new File(relative_dir).listFiles()).forEach(Lambdas.wrap_consumer_i(ff -> {
        JarEntry entry = new JarEntry(ff.getName());
        target.putNextEntry(entry);
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(ff))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }));
    target.close();

    final String created = "Created = " + new File("./script_classpath.jar").toURI().toURL() + " ... "
            + Arrays.stream(new File(relative_dir).listFiles()).map(ff -> ff.toString())
                    .collect(Collectors.joining(";"));
    logger.ifPresent(l -> l.log(Level.DEBUG, true, () -> created, () -> "SparkScalaInterpreterTopology",
            () -> "compile"));

    final Tuple2<ClassLoader, Object> o = Lambdas.get(Lambdas.wrap_u(() -> {
        _cl.set(new java.net.URLClassLoader(
                Arrays.asList(new File("./script_classpath.jar").toURI().toURL()).toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader()));
        Object o_ = _cl.get().loadClass("ScriptRunner").newInstance();
        return Tuples._2T(_cl.get(), o_);
    }));
    return o;
}

From source file:org.ligoj.app.http.security.RestAuthenticationProvider.java

/**
 * Return a new authentication with the the real use name.
 *///from w w w . j  a v a 2 s.  com
private Authentication newAuthentication(final String userName, final String userpassword,
        final Authentication authentication, final HttpResponse httpResponse) {
    final List<String> cookies = Arrays.stream(httpResponse.getAllHeaders())
            .filter(header -> "set-cookie".equals(header.getName())).map(Header::getValue)
            .collect(Collectors.toList());

    // Get the optional real user name if provided
    final String realUserName = Optional.ofNullable(httpResponse.getFirstHeader("X-Real-User"))
            .map(Header::getValue).orElse(userName);
    if (realUserName.equals(userName)) {
        log.info("Success authentication of {}[{}]", realUserName, userpassword.length(), realUserName);
    } else {
        log.info("Success authentication of {}[{}] using login {}", realUserName, userpassword.length(),
                userName);
    }

    // Return the authentication token
    return new CookieUsernamePasswordAuthenticationToken(realUserName, authentication.getCredentials(),
            authentication.getAuthorities(), cookies);

}

From source file:com.willwinder.universalgcodesender.connection.JSerialCommConnection.java

@Override
public List<String> getPortNames() {
    return Arrays.stream(SerialPort.getCommPorts()).map(SerialPort::getSystemPortName)
            .collect(Collectors.toList());
}

From source file:org.geosdi.geoplatform.experimental.openam.support.connector.request.BaseOpenAMRequest.java

/**
 * @param uriBuilder/*from  w w  w.  j a  va2  s. c om*/
 * @return {@link URIBuilder}
 * @throws Exception
 */
default URIBuilder addRequestParameter(URIBuilder uriBuilder, RequestParameter... value) throws Exception {
    Preconditions.checkNotNull(uriBuilder, "The Parameter URIBuilder must not be null.");
    Preconditions.checkArgument(((value != null) && (value.length > 0)),
            "The Parameter Value must not be null");
    Arrays.stream(value).forEach(p -> uriBuilder.addParameter(p.getkey(), p.getValue()));
    return uriBuilder;
}

From source file:eu.itesla_project.security.SecurityAnalysisTool.java

@Override
public void run(CommandLine line) throws Exception {
    Path caseFile = Paths.get(line.getOptionValue("case-file"));
    Set<LimitViolationType> limitViolationTypes = line.hasOption("limit-types")
            ? Arrays.stream(line.getOptionValue("limit-types").split(",")).map(LimitViolationType::valueOf)
                    .collect(Collectors.toSet())
            : EnumSet.allOf(LimitViolationType.class);
    Path csvFile = null;//from   w  w  w . j  a  v a  2s . co m
    if (line.hasOption("output-csv")) {
        csvFile = Paths.get(line.getOptionValue("output-csv"));
    }

    System.out.println("Loading network '" + caseFile + "'");

    // load network
    Network network = Importers.loadNetwork(caseFile);
    if (network == null) {
        throw new RuntimeException("Case '" + caseFile + "' not found");
    }
    network.getStateManager().allowStateMultiThreadAccess(true);

    ComponentDefaultConfig defaultConfig = new ComponentDefaultConfig();
    SecurityAnalysisFactory securityAnalysisFactory = defaultConfig
            .findFactoryImplClass(SecurityAnalysisFactory.class).newInstance();
    SecurityAnalysis securityAnalysis = securityAnalysisFactory.create(network,
            LocalComputationManager.getDefault(), 0);

    ContingenciesProviderFactory contingenciesProviderFactory = defaultConfig
            .findFactoryImplClass(ContingenciesProviderFactory.class).newInstance();
    ContingenciesProvider contingenciesProvider = contingenciesProviderFactory.create();

    // run security analysis on all N-1 lines
    SecurityAnalysisResult result = securityAnalysis.runAsync(contingenciesProvider).join();

    if (!result.getPreContingencyResult().isComputationOk()) {
        System.out.println("Pre-contingency state divergence");
    }
    LimitViolationFilter limitViolationFilter = new LimitViolationFilter(limitViolationTypes);
    if (csvFile != null) {
        System.out.println("Writing results to '" + csvFile + "'");
        CsvTableFormatterFactory csvTableFormatterFactory = new CsvTableFormatterFactory();
        Security.printPreContingencyViolations(result, Files.newBufferedWriter(csvFile, StandardCharsets.UTF_8),
                csvTableFormatterFactory, limitViolationFilter);
        Security.printPostContingencyViolations(result,
                Files.newBufferedWriter(csvFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND),
                csvTableFormatterFactory, limitViolationFilter);
    } else {
        SystemOutStreamWriter soutWriter = new SystemOutStreamWriter();
        AsciiTableFormatterFactory asciiTableFormatterFactory = new AsciiTableFormatterFactory();
        Security.printPreContingencyViolations(result, soutWriter, asciiTableFormatterFactory,
                limitViolationFilter);
        Security.printPostContingencyViolations(result, soutWriter, asciiTableFormatterFactory,
                limitViolationFilter);
    }
}

From source file:de.thingweb.servient.MultiThingTests.java

@Test
public void multiThingServient() throws Exception {
    int nthings = 10;
    Thing[] things = new Thing[nthings];

    Action testAction = Action.getBuilder("testAction").build();
    Property testProp = Property.getBuilder("testProp").setWriteable(true).setValueType("xsd:string").build();

    for (int i = 0; i < nthings; i++) {
        things[i] = new Thing("thing" + i);
        things[i].addAction(testAction);
        things[i].addProperty(testProp);
        server.addThing(things[i]);/*from  w ww .  ja  v a2 s  .  c om*/
    }

    ServientBuilder.start();

    JsonNode jsonNode = jsonMapper.readTree(new URL("http://localhost:8080/things/"));
    assertThat("should be an object", jsonNode.isObject(), is(true));

    final ObjectNode repo = (ObjectNode) jsonNode;

    assertThat("expected at least the same number of links under /things as things", repo.size(),
            greaterThanOrEqualTo(nthings));

    Arrays.stream(things).forEach(thing -> assertThat("should contain all things, misses " + thing.getName(),
            repo.get(thing.getName()), notNullValue()));

    //further checks
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.KubernetesV2SearchProvider.java

@Autowired
public KubernetesV2SearchProvider(KubernetesCacheUtils cacheUtils, KubernetesSpinnakerKindMap kindMap,
        ObjectMapper objectMapper, KubernetesResourcePropertyRegistry registry) {
    this.cacheUtils = cacheUtils;
    this.mapper = objectMapper;
    this.kindMap = kindMap;
    this.registry = registry;

    this.defaultTypes = kindMap.allKubernetesKinds().stream().map(KubernetesKind::toString)
            .collect(Collectors.toList());
    this.logicalTypes = Arrays.stream(LogicalKind.values()).map(LogicalKind::toString)
            .collect(Collectors.toSet());

    this.allCaches = new HashSet<>(defaultTypes);
    this.allCaches.addAll(logicalTypes);
}

From source file:com.haulmont.cuba.core.sys.singleapp.SingleAppCoreServletListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {//  www . j  a v a  2  s . c  o  m
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        //need to put the following class to WebAppClassLoader, to share it between for web and core
        contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory");

        ServletContext servletContext = sce.getServletContext();
        String dependenciesFile;
        try {
            dependenciesFile = IOUtils
                    .toString(servletContext.getResourceAsStream("/WEB-INF/core.dependencies"), "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException("An error occurred while loading dependencies file", e);
        }

        String[] dependenciesNames = dependenciesFile.split("\\n");
        URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> {
            try {
                return servletContext.getResource("/WEB-INF/lib/" + name);
            } catch (MalformedURLException e) {
                throw new RuntimeException("An error occurred while loading dependency " + name, e);
            }
        }).toArray(URL[]::new);
        URLClassLoader coreClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader);

        Thread.currentThread().setContextClassLoader(coreClassLoader);
        Class<?> appContextLoaderClass = coreClassLoader.loadClass(getAppContextLoaderClassName());
        appContextLoader = appContextLoaderClass.newInstance();

        Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames",
                String.class);
        ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile);

        Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass,
                "contextInitialized", ServletContextEvent.class);
        ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce);

        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException("An error occurred while starting single WAR application", e);
    }
}

From source file:com.intellij.plugins.haxe.model.HaxeFileModel.java

@Nullable
public HaxeClassModel getClassModel(String name) {
    HaxeClass haxeClass = (HaxeClass) Arrays.stream(file.getChildren()).filter(
            element -> element instanceof HaxeClass && Objects.equals(name, ((HaxeClass) element).getName()))
            .findFirst().orElse(null);/*from w  w w  . j  a v  a2s.  c o  m*/

    return haxeClass != null ? haxeClass.getModel() : null;
}