List of usage examples for java.util.stream Collectors joining
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter)
From source file:httpasync.AsyncClientPipelinedStreaming.java
public static void a() { long start = System.currentTimeMillis(); CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining(); try {/*from w w w. j av a 2 s . c om*/ httpclient.start(); HttpHost targetHost = new HttpHost("globalquotes.xignite.com", 80); // HttpGet[] resquests = { // new HttpGet("/docs/index.html"), // new HttpGet("/docs/introduction.html"), // new HttpGet("/docs/setup.html"), // new HttpGet("/docs/config/index.html") // }; List<MyRequestProducer> requestProducers = new ArrayList<MyRequestProducer>(); List<MyResponseConsumer> responseConsumers = new ArrayList<MyResponseConsumer>(); String[] codes = StockParser.stockCodeList.split(","); // 500 * 17 ~~~~~~~~~~~~~~~ Shutting down : 12660 // avg=17348.1 // 400 * 21 ~~~~~~~~~~~~~~~ Shutting down : 27476 // avg=18923.8 int take = 400; for (int i = 0; i < codes.length / take; i++) { String code = Arrays.asList(codes).stream().skip(i * take).limit(take) .collect(Collectors.joining(",")); HttpGet request = new HttpGet(StockParser.uri + URLEncoder.encode(code.trim())); requestProducers.add(new MyRequestProducer(targetHost, request)); responseConsumers.add(new MyResponseConsumer(request)); } // System.out.println("? = "+ responseConsumers.size()); // for (HttpGet request: resquests) { // requestProducers.add(new MyRequestProducer(targetHost, request)); // responseConsumers.add(new MyResponseConsumer(request)); // } Future<List<Boolean>> future = httpclient.execute(targetHost, requestProducers, responseConsumers, new FutureCallback<List<Boolean>>() { @Override public void completed(List<Boolean> result) { } @Override public void failed(Exception ex) { ex.printStackTrace(); } @Override public void cancelled() { } }); future.get(); System.out.println(take + " * " + responseConsumers.size() + " ~~~~~~~~~~~~~~~ Shutting down : " + (System.currentTimeMillis() - start)); } catch (Exception e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } // System.out.println("Done"); }
From source file:com.rln.acme.security.MongoDBAuthenticationProvider.java
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { final String password = (String) authentication.getCredentials(); if (!StringUtils.isNotBlank(password)) { logger.warn("User {}: no password provided", username); throw new BadCredentialsException("Please enter password"); }/*w ww. ja v a 2s . c o m*/ final UserAccount user = userService.findByUsername(username); if (user == null) { logger.warn("Username {}, password {}: username and password not found", username, password); throw new BadCredentialsException("Invalid Username/Password"); } final List<GrantedAuthority> auths; if (CollectionUtils.isNotEmpty(user.getRoles())) { auths = AuthorityUtils.commaSeparatedStringToAuthorityList( user.getRoles().stream().map(r -> r.getId()).collect(Collectors.joining(","))); } else { auths = AuthorityUtils.NO_AUTHORITIES; } return new User(username, password, user.getEnabled(), // enabled true, // account not expired true, // credentials not expired true, // account not locked auths); }
From source file:eu.crydee.stanfordcorenlp.Tokenizer.java
/** * Tokenize and sentence split.//from w ww. j ava 2s.c om * * @param input the String to tokenize and sentence split. * @return a String of the tokenized text, one sentence per line, with space * separated words. */ public String tokenizeAndSentenceSplit(String input) { Annotation annotation = new Annotation(input); pipelineWithSS.annotate(annotation); return annotation .get(SentencesAnnotation.class).stream().map(s -> s.get(TokensAnnotation.class).stream() .map(t -> t.get(TextAnnotation.class)).collect(Collectors.joining(" "))) .collect(Collectors.joining("\n")); }
From source file:eu.crydee.alignment.aligner.cr.VideoLecturesCR.java
@Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); String[] dfxps = new File(dfxpDirpath).list(), teis = new File(teiDirpath).list(); List<String> errs = new ArrayList<>(); if (teis == null) { errs.add("The TEI directory path doesn't resolve to a directory."); } else if (dfxps == null) { errs.add("The DFXP directory path doesn't resolve to a directory."); }//from ww w . java 2 s.co m if (!errs.isEmpty()) { logger.error(errs.stream().collect(Collectors.joining("\n"))); throw new ResourceInitializationException(); } Set<String> dfxpsSet = Sets.newHashSet(dfxps); ids = Arrays.stream(teis).map(s -> s.replace(".tei.xml", "")).filter(s -> dfxpsSet.contains(s + ".dfxp")) .iterator(); currentIndex = 0; }
From source file:com.github.horrorho.inflatabledonkey.args.ArgsManager.java
String parse(Option option, UnaryOperator<String> parser) { if (option.hasArgs()) { return option.getValuesList().stream().map(u -> parse(option.getLongOpt(), u, parser)) .collect(Collectors.joining(" ")); }/*from w w w . j a v a 2 s.c om*/ if (option.hasArg()) { return parse(option.getLongOpt(), option.getValue(), parser); } return Boolean.TRUE.toString(); }
From source file:com.formkiq.core.domain.type.FolderDTO.java
/** * @return {@link String}//from ww w. j av a2s . c o m */ @JsonIgnore public String getPermissionsasstring() { return this.permissions.stream().collect(Collectors.joining(",")); }
From source file:com.epam.ta.reportportal.core.widget.content.UniqueBugFilterStrategy.java
@Override public Map<String, List<ChartObject>> buildFilterAndLoadContent(UserFilter userFilter, ContentOptions contentOptions, String projectName) { Filter filter = userFilter.getFilter(); if (filter.getTarget().equals(Launch.class)) { filter.addCondition(new FilterCondition(Condition.EQUALS, false, projectName, Launch.PROJECT)); filter.addCondition(FilterConditionUtils.LAUNCH_IN_DEFAULT_MODE()); filter.addCondition(FilterConditionUtils.LAUNCH_NOT_IN_PROGRESS()); int limit = contentOptions.getItemsCount(); CriteriaMap<?> criteriaMap = criteriaMapFactory.getCriteriaMap(filter.getTarget()); List<Launch> launches = launchRepository.findIdsByFilter(filter, new Sort(userFilter.getSelectionOptions().isAsc() ? Sort.Direction.ASC : Sort.Direction.DESC, criteriaMap.getCriteriaHolder(userFilter.getSelectionOptions().getSortingColumnName()) .getQueryCriteria()), limit);//from w w w. j a v a2s.c o m final String value = launches.stream().map(Launch::getId).collect(Collectors.joining(SEPARATOR)); filter = new Filter(TestItem.class, Sets.newHashSet(new FilterCondition(Condition.IN, false, value, TestItem.LAUNCH_CRITERIA))); } filter.addCondition(new FilterCondition(Condition.EXISTS, false, "true", TestItem.EXTERNAL_SYSTEM_ISSUES)); return widgetContentProvider.getChartContent(filter, userFilter.getSelectionOptions(), contentOptions); }
From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java
/** Compiles a scala class * @param script// w w w. ja v a 2 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.ng200.openolympus.resourceResolvers.OpenOlympusMessageSource.java
private void reportMissingLocalisationKey(final String code) { try {/*from w w w . ja v a 2s. c om*/ if (code.isEmpty() || Character.isUpperCase(code.charAt(0))) { return; } final Path file = FileSystems.getDefault().getPath(this.storagePath, "missingLocalisation.txt"); if (!FileAccess.exists(file)) { FileAccess.createDirectories(file.getParent()); FileAccess.createFile(file); } final Set<String> s = new TreeSet<>(Arrays.asList(FileAccess.readUTF8String(file).split("\n"))); s.add(code); FileAccess.writeUTF8StringToFile(file, s.stream().collect(Collectors.joining("\n"))); } catch (final IOException e) { OpenOlympusMessageSource.logger.error("Couldn't add to missing key repo: {}", e); } }
From source file:dk.dma.msinm.web.wms.WmsProxyServlet.java
/** * Main GET method//from w w w . ja va 2 s. c o m * @param request servlet request * @param response servlet response */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // Cache for a day WebUtils.cache(response, CACHE_TIMEOUT); // Check that the WMS provider has been defined using system properties if (StringUtils.isBlank(wmsServiceName) || StringUtils.isBlank(wmsProvider) || StringUtils.isBlank(wmsLogin) || StringUtils.isBlank(wmsPassword)) { response.sendRedirect(BLANK_IMAGE); return; } @SuppressWarnings("unchecked") Map<String, String[]> paramMap = request.getParameterMap(); String params = paramMap.entrySet().stream().map(p -> String.format("%s=%s", p.getKey(), p.getValue()[0])) .collect(Collectors.joining("&")); params += String.format("&SERVICENAME=%s&LOGIN=%s&PASSWORD=%s", wmsServiceName, wmsLogin, wmsPassword); String url = wmsProvider + "?" + params; log.trace("Loading image " + url); try { BufferedImage image = ImageIO.read(new URL(url)); if (image != null) { image = transformWhiteToTransparent(image); OutputStream out = response.getOutputStream(); ImageIO.write(image, "png", out); image.flush(); out.close(); return; } } catch (Exception e) { log.trace("Failed loading WMS image for URL " + url); } // Fall back to return a blank image response.sendRedirect(BLANK_IMAGE); }