List of usage examples for java.util Arrays stream
public static DoubleStream stream(double[] array)
From source file:io.mapzone.controller.vm.http.LoginProvision.java
@Override public Status execute() throws Exception { checked.set(this); // check authToken AuthTokenValidator atv = new AuthTokenValidator(() -> projectUow(), request.get()); if (atv.checkAuthToken()) { String clientHost = request.get().getRemoteHost(); log.info("AuthToken: valid, for client: " + clientHost); registerUser(clientHost, response.get()); // who we are? does arena need a user? return OK_STATUS; }/* ww w. j av a 2 s . c om*/ // cookie -> OK Optional<Cookie> cookie = Arrays.stream(request.get().getCookies()) .filter(c -> c.getName().equals(COOKIE_NAME)).findAny(); if (cookie.isPresent()) { String userId = loggedIn.get(cookie.get().getValue()); if (userId != null) { return OK_STATUS; } } // check /dashboard login Optional<LoginCookie> loginCookie = LoginCookie.access(request.get(), response.get()).findAndUpdate(); if (loginCookie.isPresent()) { registerUser((String) loginCookie.get().user.get().id(), response.get()); return OK_STATUS; } // no cookie -> /login String requestUrl = Joiner.on("").skipNulls().join(request.get().getServletPath(), request.get().getPathInfo(), "?", request.get().getQueryString()); String handlerId = LoginAppDesign.registerHandler(user -> { try { registerUser((String) user.id(), RWT.getResponse()); UIUtils.exec("window.location=\"", requestUrl, "\";"); } catch (Exception e) { throw new RuntimeException(e); } }); // http://stackoverflow.com/questions/30844807/can-a-redirect-to-relative-path-be-sent-from-java-servlet-api // response.get().sendRedirect( "../../../login?id=" + handlerId ); response.get().setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.get().setHeader("Location", "../../../login?id=" + handlerId); throw new ProvisionRuntimeException(); }
From source file:com.github.ljtfreitas.restify.http.client.message.converter.json.JacksonMessageConverter.java
@Override public void write(T body, HttpRequestMessage httpRequestMessage) throws RestifyHttpMessageWriteException { try {/* w ww.j ava2 s. c om*/ JsonEncoding encoding = Arrays.stream(JsonEncoding.values()) .filter(e -> e.getJavaName().equals(httpRequestMessage.charset())).findFirst() .orElse(JsonEncoding.UTF8); JsonGenerator generator = objectMapper.getFactory().createGenerator(httpRequestMessage.output(), encoding); objectMapper.writeValue(generator, body); generator.flush(); } catch (IOException e) { throw new RestifyHttpMessageWriteException(e); } }
From source file:com.uber.hoodie.common.table.timeline.HoodieActiveTimeline.java
protected HoodieActiveTimeline(FileSystem fs, String metaPath, String[] includedExtensions) { // Filter all the filter in the metapath and include only the extensions passed and // convert them into HoodieInstant try {/*w ww . j ava2 s. c o m*/ this.instants = Arrays.stream(HoodieTableMetaClient.scanFiles(fs, new Path(metaPath), path -> { // Include only the meta files with extensions that needs to be included String extension = FSUtils.getFileExtension(path.getName()); return Arrays.stream(includedExtensions).anyMatch(Predicate.isEqual(extension)); })).sorted(Comparator.comparing( // Sort the meta-data by the instant time (first part of the file name) fileStatus -> FSUtils.getInstantTime(fileStatus.getPath().getName()))) // create HoodieInstantMarkers from FileStatus, which extracts properties .map(HoodieInstant::new).collect(Collectors.toList()); log.info("Loaded instants " + instants); } catch (IOException e) { throw new HoodieIOException("Failed to scan metadata", e); } this.fs = fs; this.metaPath = metaPath; // multiple casts will make this lambda serializable - http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.16 this.details = (Function<HoodieInstant, Optional<byte[]>> & Serializable) this::getInstantDetails; }
From source file:com.github.mavogel.ilias.utils.ConfigurationsUtils.java
/** * Creates the login configuration and uses defaults if necessary. * * @param propertyFilename the name of the property file * @return the {@link LoginConfiguration} *//*from w w w .j a va2 s. co m*/ public static LoginConfiguration createLoginConfiguration(final String propertyFilename) { Parameters params = new Parameters(); FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>( PropertiesConfiguration.class).configure(params.properties().setFileName(propertyFilename)); LoginConfiguration.LOGIN_MODE loginMode = null; String endpoint, client, username, password, loginModeRaw = ""; int maxFolderDepth; Level logLevel; try { Configuration config = builder.getConfiguration(); loginModeRaw = config.getString("login.mode"); loginMode = LoginConfiguration.LOGIN_MODE.valueOf(loginModeRaw); endpoint = config.getString("endpoint"); client = config.getString("login.client"); username = config.getString("login.username"); password = config.getString("login.password"); maxFolderDepth = config.getString("maxFolderDepth", String.valueOf(Defaults.MAX_FOLDER_DEPTH)).isEmpty() ? Defaults.MAX_FOLDER_DEPTH : Integer .valueOf(config.getString("maxFolderDepth", String.valueOf(Defaults.MAX_FOLDER_DEPTH))); logLevel = Level.toLevel(config.getString("log.level", Defaults.LOG_LEVEL.toString()), Defaults.LOG_LEVEL); if (password == null || password.isEmpty()) { Console console = System.console(); if (console != null) { password = String.valueOf(console.readPassword("Enter your password: ")); } else { throw new Exception("Console is not available!"); } } } catch (IllegalArgumentException iae) { throw new RuntimeException(String.format("Login mode '%s' is unknown. Use one of %s", loginModeRaw, Arrays.stream(LoginConfiguration.LOGIN_MODE.values()).map(lm -> lm.name()) .collect(Collectors.joining(", ")))); } catch (ConversionException ce) { throw new RuntimeException("maxFolderDepth property is not an integer"); } catch (Exception ex) { throw new RuntimeException(ex); } // == 1: set log level Logger.getRootLogger().setLevel(logLevel); // == 2: create login configuration switch (loginMode) { case STD: return LoginConfiguration.asStandardLogin(endpoint, client, username, password, maxFolderDepth); case LDAP: return LoginConfiguration.asLDAPLogin(endpoint, client, username, password, maxFolderDepth); case CAS: return LoginConfiguration.asCASLogin(); default: // should not happen return null; } }
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 w w w . j av a2 s.c o 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:uk.dsxt.voting.client.datamodel.QuestionWeb.java
public QuestionWeb(Question q) { this.id = q.getId(); this.question = q.getQuestion(); this.answers = Arrays.stream(q.getAnswers()).map(AnswerWeb::new).collect(Collectors.toList()) .toArray(new AnswerWeb[q.getAnswers().length]); this.canSelectMultiple = q.isCanSelectMultiple(); this.multiplicator = q.getMultiplicator(); }
From source file:com.gazbert.bxbot.rest.api.AbstractConfigControllerTest.java
@Autowired void setConverters(HttpMessageConverter<?>[] converters) { this.mappingJackson2HttpMessageConverter = Arrays.stream(converters) .filter(converter -> converter instanceof MappingJackson2HttpMessageConverter).findAny().get(); Assert.assertNotNull("The JSON message converter must not be null", this.mappingJackson2HttpMessageConverter); }
From source file:Main.java
/** * Selects the list of array elements that satisfy the given filter. * If the filter is <code>null</code>, all the array elements are returned. * * @param array The array to be filtered * @param filter The filter to be applied * @param <T> The type of array elements * @return A list of elements satisfying the filter *//*w ww . ja v a2 s . c o m*/ public static <T> List<T> where(T[] array, Predicate<T> filter) { List<T> result = null; if (array != null) { if (filter != null) { result = where(Arrays.stream(array), filter); } else { result = Arrays.asList(array); } } return result; }
From source file:com.github.ljtfreitas.restify.spring.configure.RestifyConfigurationRegistrar.java
@SuppressWarnings("unchecked") private Set<TypeFilter> filters(RestifyExcludeFilter[] filters) { Set<TypeFilter> typeFilters = new LinkedHashSet<>(); Arrays.stream(filters).forEach(f -> { Arrays.stream(f.classes()).forEach(classType -> { switch (f.type()) { case ANNOTATION: { typeFilters.add(new AnnotationTypeFilter((Class<? extends Annotation>) classType)); break; }/* ww w. ja va2s .c o m*/ case ASSIGNABLE_TYPE: { typeFilters.add(new AssignableTypeFilter(classType)); break; } case CUSTOM: { typeFilters.add(Tryable.of(() -> (TypeFilter) classType.newInstance(), () -> new IllegalArgumentException( "Cannot construct your custom TypeFilter of type [" + classType + "]"))); } default: { throw new IllegalArgumentException("Illegal @Filter use. " + "Your configure [classes] attribute with filter type [" + f.type() + "]"); } } }); Arrays.stream(f.pattern()).forEach(pattern -> { switch (f.type()) { case REGEX: { typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(pattern))); } case ASPECTJ: { typeFilters.add(new AspectJTypeFilter(pattern, resourceLoader.getClassLoader())); } default: { throw new IllegalArgumentException("Illegal @Filter use. " + "Your configure [pattern] attribute with filter type [" + f.type() + "]"); } } }); }); return typeFilters; }
From source file:alfio.manager.system.MailjetMailer.java
@Override public void send(Event event, String to, List<String> cc, String subject, String text, Optional<String> html, Attachment... attachment) {//from w w w . j a va 2 s.c om String apiKeyPublic = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_APIKEY_PUBLIC)); String apiKeyPrivate = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_APIKEY_PRIVATE)); String fromEmail = configurationManager.getRequiredValue( Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAILJET_FROM)); //https://dev.mailjet.com/guides/?shell#sending-with-attached-files Map<String, Object> mailPayload = new HashMap<>(); List<Map<String, String>> recipients = new ArrayList<>(); recipients.add(Collections.singletonMap("Email", to)); if (cc != null && !cc.isEmpty()) { recipients.addAll(cc.stream().map(email -> Collections.singletonMap("Email", email)) .collect(Collectors.toList())); } mailPayload.put("FromEmail", fromEmail); mailPayload.put("FromName", event.getDisplayName()); mailPayload.put("Subject", subject); mailPayload.put("Text-part", text); html.ifPresent(h -> mailPayload.put("Html-part", h)); mailPayload.put("Recipients", recipients); String replyTo = configurationManager.getStringConfigValue( Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.MAIL_REPLY_TO), ""); if (StringUtils.isNotBlank(replyTo)) { mailPayload.put("Headers", Collections.singletonMap("Reply-To", replyTo)); } if (attachment != null && attachment.length > 0) { mailPayload.put("Attachments", Arrays.stream(attachment).map(MailjetMailer::fromAttachment).collect(Collectors.toList())); } RequestBody body = RequestBody.create(MediaType.parse("application/json"), Json.GSON.toJson(mailPayload)); Request request = new Request.Builder().url("https://api.mailjet.com/v3/send") .header("Authorization", Credentials.basic(apiKeyPublic, apiKeyPrivate)).post(body).build(); try (Response resp = client.newCall(request).execute()) { if (!resp.isSuccessful()) { log.warn("sending email was not successful:" + resp); } } catch (IOException e) { log.warn("error while sending email", e); } }