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.github.lynxdb.server.run.Run.java

@Override
public void run(String... args) throws Exception {

    mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

    if (Arrays.stream(args).anyMatch((String t) -> t.equals("--debug"))) {
        ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory
                .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.toLevel("debug"));
    }//from   w ww .  jav  a 2s  .c  om

    if (Arrays.stream(args).anyMatch((String t) -> t.equals("--trace"))) {
        ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory
                .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.toLevel("trace"));
    }

    LOGGER.info("Discovering bundles");
    context.getBeansOfType(Bundle.class).entrySet().stream()
            .filter((Map.Entry<String, Bundle> b) -> b.getValue().autostart() || Arrays.stream(args)
                    .anyMatch((String t) -> t.equals("--" + b.getKey().toLowerCase().trim())))
            .forEach((Map.Entry<String, Bundle> t) -> {
                LOGGER.info("Found bundle " + t.getValue().name() + " in " + t.getValue().getClass());
                bundles.add(t.getValue());
            });
    LOGGER.info("Bundles discovery complete");
    LOGGER.info("Starting bundles...");
    for (Bundle b : bundles) {
        LOGGER.info("Starting bundle " + b.name());
        b.start();
        LOGGER.info("Bundle " + b.name() + " started");
    }
    LOGGER.info("Bundles started");
}

From source file:de.sainth.recipe.backend.security.AuthFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    String header = request.getHeader("Authorization");
    Optional<Cookie> cookie;
    if (request.getCookies() != null) {
        cookie = Arrays.stream(request.getCookies()).filter(c -> COOKIE_NAME.equals(c.getName())).findFirst();
    } else {/*from   w  w  w . java  2s.c o  m*/
        cookie = Optional.empty();
    }
    if (!cookie.isPresent() && (header == null || header.length() == 0)) {
        throw new AccessDeniedException("No authentication information present");
    }
    RecipeManagerAuthenticationToken authentication;
    try {
        if (cookie.isPresent()) {
            authentication = parseToken(cookie.get().getValue());
        } else {
            Optional<RecipeManagerAuthenticationToken> maybeAuthentication;
            if (header.startsWith("Bearer ")) {
                maybeAuthentication = parseBearerToken(header);
            } else {
                maybeAuthentication = parseBasicAuth(header);
            }
            if (maybeAuthentication.isPresent()) {
                authentication = maybeAuthentication.get();
            } else {
                throw new AccessDeniedException("Bad credentials");
            }
        }
    } catch (ExpiredJwtException | SignatureException e) {
        throw new AccessDeniedException("Token not valid");
    }
    SecurityContextHolder.getContext().setAuthentication(authentication);
    response.addCookie(createCookie(authentication, request.isSecure()));

    chain.doFilter(request, response);
}

From source file:io.gravitee.management.security.config.basic.filter.AuthenticationSuccessFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    final HttpServletRequest req = (HttpServletRequest) servletRequest;

    final Optional<Cookie> optionalStringToken;

    if (req.getCookies() == null) {
        optionalStringToken = Optional.empty();
    } else {//from   w w  w.  j  a  v  a 2  s . c om
        optionalStringToken = Arrays.stream(req.getCookies())
                .filter(cookie -> HttpHeaders.AUTHORIZATION.equals(cookie.getName())).findAny();
    }

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && !optionalStringToken.isPresent()) {
        // JWT signer
        final Map<String, Object> claims = new HashMap<>();
        claims.put(JWTClaims.ISSUER, jwtIssuer);

        final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        claims.put(JWTClaims.PERMISSIONS, userDetails.getAuthorities());
        claims.put(JWTClaims.SUBJECT, userDetails.getUsername());
        claims.put(JWTClaims.EMAIL, userDetails.getEmail());
        claims.put(JWTClaims.FIRSTNAME, userDetails.getFirstname());
        claims.put(JWTClaims.LASTNAME, userDetails.getLastname());

        final JWTSigner.Options options = new JWTSigner.Options();
        options.setExpirySeconds(jwtExpireAfter);
        options.setIssuedAt(true);
        options.setJwtId(true);

        final Cookie bearerCookie = jwtCookieGenerator
                .generate("Bearer " + new JWTSigner(jwtSecret).sign(claims, options));
        ((HttpServletResponse) servletResponse).addCookie(bearerCookie);
    }
    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:com.hurence.logisland.classloading.PluginLoader.java

/**
 * Scan for plugins./*from   w ww.j a va  2s.c  om*/
 */
private static void scanAndRegisterPlugins() {
    Set<URL> urls = new HashSet<>();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    while (cl != null) {
        if (cl instanceof URLClassLoader) {
            urls.addAll(Arrays.asList(((URLClassLoader) cl).getURLs()));
            cl = cl.getParent();
        }
    }

    for (URL url : urls) {
        try {
            Archive archive = null;
            try {
                archive = new JarFileArchive(
                        new File(URLDecoder.decode(url.getFile(), Charset.defaultCharset().name())), url);
            } catch (Exception e) {
                //silently swallowing exception. just skip the archive since not an archive
            }
            if (archive == null) {
                continue;
            }
            Manifest manifest = archive.getManifest();
            if (manifest != null) {
                String exportedPlugins = manifest.getMainAttributes()
                        .getValue(ManifestAttributes.MODULE_EXPORTS);
                if (exportedPlugins != null) {
                    String version = StringUtils.defaultIfEmpty(
                            manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_VERSION),
                            "UNKNOWN");

                    logger.info("Loading components from module {}", archive.getUrl().toExternalForm());

                    final Archive arc = archive;

                    if (StringUtils.isNotBlank(exportedPlugins)) {
                        Arrays.stream(exportedPlugins.split(",")).map(String::trim).forEach(s -> {
                            if (registry.putIfAbsent(s, PluginClassloaderBuilder.build(arc)) == null) {
                                logger.info("Registered component '{}' version '{}'", s, version);
                            }

                        });
                    }
                }
            }

        } catch (Exception e) {
            logger.error("Unable to load components from " + url.toExternalForm(), e);
        }
    }
}

From source file:alfio.model.transaction.PaymentProxy.java

public static List<PaymentProxy> availableProxies() {
    return Arrays.stream(values()).filter(PaymentProxy::isVisible).collect(Collectors.toList());
}

From source file:it.polimi.diceH2020.launcher.controller.FilesController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String multipleSave(@RequestParam("file[]") MultipartFile[] files,
        @RequestParam("scenario") String useCase, Model model, RedirectAttributes redirectAttrs) {
    boolean singleInputData = false;
    Scenarios scenario = Scenarios.valueOf(useCase);
    ArrayList<String> tmpValues = new ArrayList<>();

    redirectAttrs.addAttribute("scenario", scenario);
    model.addAttribute("scenario", scenario);

    if (files == null || files.length == 0) {
        model.addAttribute("message", "Wrong files!");
        return "launchSimulation_FileUpload";
    }/*w w w .  j av  a 2  s .  com*/

    if (hasDuplicate(
            Arrays.stream(files).map(MultipartFile::getOriginalFilename).collect(Collectors.toList()))) {
        model.addAttribute("message", "Duplicated files!");
        return "launchSimulation_FileUpload";
    }

    for (int i = 0; i < files.length; i++) {
        String fileName = files[i].getOriginalFilename()
                .substring(files[i].getOriginalFilename().lastIndexOf("/") + 1);
        File f = saveFile(files[i], fileName);
        if (f == null)
            return "error";
        if (fileName.contains(".json")) {
            Optional<InstanceDataMultiProvider> idmp = validator.readInstanceDataMultiProvider(f.toPath());
            if (idmp.isPresent()) {
                if (idmp.get().validate()) {
                    redirectAttrs.addAttribute("instanceDataMultiProvider", f.toPath().toString());
                    continue;
                } else {
                    model.addAttribute("message", idmp.get().getValidationError());
                    return "launchSimulation_FileUpload";
                }
            }
            model.addAttribute("message", "You have submitted an invalid json!");
            return "launchSimulation_FileUpload";
        } else {
            if (fileName.contains(".txt")) {
                tmpValues.add(f.toPath().toString());
            }
        }
    }

    redirectAttrs.addAttribute("pathList", tmpValues);
    if (singleInputData)
        return "redirect:/launch/simulationSetupSingleInputData";
    return "redirect:/launch/simulationSetup";
}

From source file:org.codice.ddf.security.servlet.logout.LocalLogoutServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("text/html");

    URIBuilder redirectUrlBuilder = null;
    List<NameValuePair> params = new ArrayList<>();

    try {/*from   w  ww. j av a  2  s  .  co  m*/
        redirectUrlBuilder = new URIBuilder("/logout/logout-response.html");

        HttpSession session = request.getSession();
        if (session != null) {
            SecurityTokenHolder savedToken = (SecurityTokenHolder) session
                    .getAttribute(SecurityConstants.SAML_ASSERTION);
            if (savedToken != null) {
                Subject subject = ThreadContext.getSubject();
                boolean hasSecurityAuditRole = Arrays
                        .stream(System.getProperty("security.audit.roles").split(","))
                        .anyMatch(subject::hasRole);
                if (hasSecurityAuditRole) {
                    SecurityLogger.audit("Subject with admin privileges has logged out", subject);
                }

                savedToken.removeAll();
            }
            session.invalidate();
            deleteJSessionId(response);
        }

        //Check for pki
        if (request.getAttribute("javax.servlet.request.X509Certificate") != null
                && ((X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate")).length > 0) {
            params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
        }

        //Check for basic
        Enumeration authHeaders = request.getHeaders(javax.ws.rs.core.HttpHeaders.AUTHORIZATION);
        while (authHeaders.hasMoreElements()) {
            if (((String) authHeaders.nextElement()).contains("Basic")) {
                params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
                break;
            }
        }
        redirectUrlBuilder.addParameters(params);
        response.sendRedirect(redirectUrlBuilder.build().toString());
    } catch (URISyntaxException e) {
        LOGGER.debug("Invalid URI", e);
    }
}

From source file:demir.terrier.matching.daat.FeaturedCandidateResult.java

private double[] GetMaxMin(double[] array) {
    DoubleSummaryStatistics stat = Arrays.stream(array).summaryStatistics();
    double[] MinMax = new double[2];
    MinMax[0] = stat.getMin();//from  w ww . j ava 2 s  . com
    MinMax[1] = stat.getMax();

    return MinMax;
    /* ---------2----------------------------
     List b = Arrays.asList(ArrayUtils.toObject(array));
     System.out.println(Collections.min(b));
     System.out.println(Collections.max(b));
     */
}

From source file:co.runrightfast.vertx.core.eventbus.EventBusAddress.java

/**
 * Address format follows a URI path convention. The address path is prefixe with the verticle id's group and name
 *
 * e.g., eventBusAddress(verticleId,"path1","path2","path3") returns "/runrightfast/verticle-manager/path1/path2/path3"
 *
 * where the verticle id group is "runrightfast" and the verticle id name is "verticle-manager"
 *
 *
 * @param verticleId REQUIRED verticleId
 * @param path REQUIRED//from   w  w w .  ja  v a  2  s.com
 * @param paths OPTIONAL
 * @return eventbus address
 */
public static String eventBusAddress(@NonNull final RunRightFastVerticleId verticleId, final String path,
        final String... paths) {
    checkArgument(isNotBlank(path));
    final StringBuilder sb = new StringBuilder(128).append('/').append(verticleId.getGroup()).append('/')
            .append(verticleId.getName()).append('/').append(path);
    if (ArrayUtils.isNotEmpty(paths)) {
        checkArgument(!Arrays.stream(paths).filter(StringUtils::isBlank).findFirst().isPresent());
        sb.append('/').append(String.join("/", paths));
    }
    return sb.toString();
}

From source file:pl.edu.icm.comac.vis.server.service.AtomicGraphServiceImpl.java

@Override
public Graph constructGraphs(String[] ids) throws OpenRDFException {
    List<NodeCacheEntry> favCacheNodes = fetchNodes(ids);
    //build link map
    Map<String, Set<String>> links = favCacheNodes.parallelStream().filter(x -> !x.isOverflow())
            .map(x -> x.getRelations()).flatMap(x -> x.stream())
            .flatMap(x -> Arrays.stream(
                    new String[][] { { x.getSubject(), x.getObject() }, { x.getObject(), x.getSubject() } }))
            .collect(Collectors.groupingBy(x -> x[0], Collectors.mapping(x -> x[1], Collectors.toSet())));
    Set<String> large = favCacheNodes.stream().filter(x -> x.isOverflow()).map(x -> x.getId())
            .collect(Collectors.toSet());
    Set<String> normal = favCacheNodes.stream().filter(x -> !x.isOverflow()).map(x -> x.getId())
            .collect(Collectors.toSet());
    Set<String> unfav = graphToolkit.calculateAdditions(normal, large, links, MAX_RETURNED_RELATIONS);
    //now fetch the unfavs:
    List<NodeCacheEntry> unfavCacheNodes = fetchNodes(unfav.toArray(new String[unfav.size()]));
    List<NodeCacheEntry> allNodes = new ArrayList<NodeCacheEntry>();
    allNodes.addAll(favCacheNodes);/*from  w w w  .j a  va 2  s .  c  o  m*/
    allNodes.addAll(unfavCacheNodes);
    List<NodeCacheEntry> largeNodes = allNodes.stream().filter(x -> x.isOverflow())
            .collect(Collectors.toList());
    List<RelationCacheEntry> largeRelations = calculateRelations(largeNodes);
    //now build the graph:

    List<Node> nodes = new ArrayList<>();

    List<Node> fnodes = favCacheNodes.stream().map(cached -> {
        Node res = new Node(cached.getId(), cached.getType(), cached.getName(), 1.0);
        res.setFavourite(true);
        return res;
    }).collect(Collectors.toList());
    nodes.addAll(fnodes);
    List<Node> ufnodes = unfavCacheNodes.stream().map(cached -> {
        Node res = new Node(cached.getId(), cached.getType(), cached.getName(), 1.0);
        res.setFavourite(false);
        return res;
    }).collect(Collectors.toList());
    nodes.addAll(ufnodes);
    Set<String> nodeIdSet = nodes.stream().map(x -> x.getId()).collect(Collectors.toSet());

    Set<Link> graphRelations = allNodes.parallelStream().filter(x -> !x.isOverflow())
            .flatMap(x -> x.getRelations().stream())
            .filter(x -> nodeIdSet.contains(x.subject) && nodeIdSet.contains(x.object))
            .map(x -> new Link(x.getPredicate(), x.getSubject(), x.getObject())).collect(Collectors.toSet());
    Graph res = new Graph();

    res.setNodes(nodes);
    res.setLinks(new ArrayList<Link>(graphRelations));
    return res;
}