List of usage examples for java.util.stream Collectors joining
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter)
From source file:dk.dma.msiproxy.web.WmsProxyServlet.java
/** * Main GET method//from ww w . ja va 2 s.c om * @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 = (Map<String, String[]>) 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); }
From source file:com.thinkbiganalytics.metadata.jobrepo.nifi.provenance.NifiBulletinExceptionExtractor.java
/** * associates the error message from Nifi to the step given * * @param stepExecution The step execution object * @param flowFileId The UUID of the flow file to extract the error message from * @param componentId The ID of the component posting the bulletin * @return true if error messages were added to stepExecution, false otherwise * @throws NifiConnectionException if cannot query Nifi */// w ww . j a v a 2s . c o m public boolean addErrorMessagesToStep(BatchStepExecution stepExecution, String flowFileId, String componentId) throws NifiConnectionException { if (StringUtils.isNotBlank(flowFileId) && StringUtils.isNotBlank(componentId)) { List<BulletinDTO> bulletins = getProcessorBulletinsForComponentInFlowFile(flowFileId, componentId); if (bulletins != null) { String msg = bulletins.stream() .filter(bulletinDTO -> bulletinErrorLevels.contains(bulletinDTO.getLevel().toUpperCase())) .map(BulletinDTO::getMessage).collect(Collectors.joining(", ")); String exitMsg = StringUtils.isBlank(stepExecution.getExitMessage()) ? "" : stepExecution.getExitMessage() + "\n"; stepExecution.setExitMessage(exitMsg + msg); return true; } } return false; }
From source file:com.coveo.spillway.storage.RedisStorage.java
@Override public Map<LimitKey, Integer> addAndGet(Collection<AddAndGetRequest> requests) { Pipeline pipeline = jedis.pipelined(); Map<LimitKey, Response<Long>> responses = new LinkedHashMap<>(); for (AddAndGetRequest request : requests) { pipeline.multi();//from ww w .jav a2 s. c o m LimitKey limitKey = LimitKey.fromRequest(request); String redisKey = Stream .of(keyPrefix, limitKey.getResource(), limitKey.getLimitName(), limitKey.getProperty(), limitKey.getBucket().toString()) .map(RedisStorage::clean).collect(Collectors.joining(KEY_SEPARATOR)); responses.put(limitKey, pipeline.incrBy(redisKey, request.getCost())); // We set the expire to twice the expiration period. The expiration is there to ensure that we don't fill the Redis cluster with // useless keys. The actual expiration mechanism is handled by the bucketing mechanism. pipeline.expire(redisKey, (int) request.getExpiration().getSeconds() * 2); pipeline.exec(); } pipeline.sync(); return responses.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, kvp -> kvp.getValue().get().intValue())); }
From source file:org.elasticsearch.xpack.core.rollup.RollupRestTestStateCleaner.java
private static String responseEntityToString(Response response) throws Exception { try (BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) { return reader.lines().collect(Collectors.joining("\n")); }/* w w w . j a v a 2s . c o m*/ }
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} *//* w w w . ja va 2 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:org.opencb.commons.datastore.core.ObjectMap.java
public String getString(String field, String defaultValue) { if (field != null && objectMap.containsKey(field)) { Object o = objectMap.get(field); if (o != null) { if (o instanceof Collection) { //Join manually to avoid surrounding brackets return ((Collection<?>) o).stream().map(Objects::toString).collect(Collectors.joining(",")); } else { return o.toString(); }/*from w w w . j a va 2 s . c o m*/ } else { return defaultValue; } } return defaultValue; }
From source file:com.epam.ta.reportportal.database.LaunchesTableDocumentHandler.java
@Override public void processDocument(DBObject dbObject) throws MongoException, DataAccessException { if (contentFields == null) { return;//from w w w . j a va 2s . c o m } ChartObject chartObject = new ChartObject(); Map<String, String> values = new HashMap<>(); for (String contentField : contentFields) { String[] split = contentField.split("\\."); Object object; if (split.length == 1) { object = dbObject.get(contentField); } else { object = getValue(dbObject, split); } chartObject.setId(dbObject.get(ID).toString()); if (contentField.equalsIgnoreCase(NAME)) chartObject.setName(object.toString()); else if (contentField.equalsIgnoreCase(NUMBER)) chartObject.setNumber(object.toString()); else if (contentField.equalsIgnoreCase(START_TIME)) chartObject.setStartTime(valueOf(((Date) object).getTime())); else { if (object instanceof Date) { values.put(contentField, valueOf(((Date) object).getTime())); } else if (object instanceof List) { values.put(contentField, ((List<?>) object).stream().map(Object::toString).collect(Collectors.joining(","))); } else { values.put(contentField, null != object ? object.toString() : null); } } } chartObject.setValues(values); list.add(chartObject); }
From source file:fi.helsinki.opintoni.integration.coursepage.CoursePageRestClient.java
@Override public List<CoursePageNotification> getCoursePageNotifications(Set<String> courseImplementationIds, LocalDateTime from, Locale locale) { if (courseImplementationIds.isEmpty()) { return newArrayList(); }/*from ww w .ja v a2 s. c o m*/ ResponseEntity<List<CoursePageNotification>> responseEntity = restTemplate.exchange( "{baseUrl}/course_implementation_activity" + "?course_implementation_id={courseImplementationIds}×tamp={from}&langcode={locale}", HttpMethod.GET, null, new ParameterizedTypeReference<List<CoursePageNotification>>() { }, baseUrl, courseImplementationIds.stream().collect(Collectors.joining(",")), from.format(DateFormatter.COURSE_PAGE_DATE_TIME_FORMATTER), locale.getLanguage()); return Optional.ofNullable(responseEntity.getBody()).orElse(newArrayList()); }
From source file:com.evolveum.midpoint.prism.query.FullTextFilter.java
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("FULLTEXT: "); if (values != null) { sb.append(values.stream().collect(Collectors.joining("; "))); }// w ww . j a va 2 s. c om return sb.toString(); }
From source file:org.smigo.log.LogHandler.java
public String getRequestDump(HttpServletRequest request, HttpServletResponse response, String separator) { StringBuilder s = new StringBuilder("####REQUEST ").append(request.getMethod()).append(" ") .append(request.getRequestURL()).append(separator); s.append("Auth type:").append(request.getAuthType()).append(separator); s.append("Principal:").append(request.getUserPrincipal()).append(separator); s.append(Log.create(request, response).toString()).append(separator); s.append("Headers:").append(separator); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); s.append(headerName).append("=").append(request.getHeader(headerName)).append(separator); }/* www. java 2 s .co m*/ s.append(separator); s.append("####RESPONSE").append(separator); s.append("Status:").append(response.getStatus()).append(separator); s.append("Char encoding:").append(response.getCharacterEncoding()).append(separator); s.append("Locale:").append(response.getLocale()).append(separator); s.append("Content type:").append(response.getContentType()).append(separator); s.append("Headers:").append(separator); s.append(response.getHeaderNames().stream().map(rh -> rh + "=" + response.getHeader(rh)) .collect(Collectors.joining(separator))); final Long start = (Long) request.getAttribute(RequestLogFilter.REQUEST_TIMER); if (start != null) { final long elapsedTime = System.nanoTime() - start; s.append(separator).append("####Request time elapsed:").append(elapsedTime); s.append("ns which is ").append(elapsedTime / 1000000).append("ms").append(separator); } return s.toString(); }