List of usage examples for com.google.common.collect Maps transformEntries
@GwtIncompatible("NavigableMap") public static <K, V1, V2> NavigableMap<K, V2> transformEntries(NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer)
From source file:org.jahia.services.render.webflow.WebflowDispatcherScript.java
/** * Execute the script and return the result as a string * * @param resource resource to display//from w ww . j a v a2 s. com * @param context * @return the rendered resource * @throws org.jahia.services.render.RenderException * */ public String execute(Resource resource, RenderContext context) throws RenderException { final View view = getView(); if (view == null) { throw new RenderException("View not found for : " + resource); } else { if (logger.isDebugEnabled()) { logger.debug("View '" + view + "' resolved for resource: " + resource); } } String identifier; try { identifier = resource.getNode().getIdentifier(); } catch (RepositoryException e) { throw new RenderException(e); } String identifierNoDashes = StringUtils.replace(identifier, "-", "_"); if (!view.getKey().equals("default")) { identifierNoDashes += "__" + view.getKey(); } HttpServletRequest request; HttpServletResponse response = context.getResponse(); @SuppressWarnings("unchecked") final Map<String, List<String>> parameters = (Map<String, List<String>>) context.getRequest() .getAttribute("actionParameters"); if (xssFilteringEnabled && parameters != null) { final Map<String, String[]> m = Maps.transformEntries(parameters, new Maps.EntryTransformer<String, List<String>, String[]>() { @Override public String[] transformEntry(@Nullable String key, @Nullable List<String> value) { return value != null ? value.toArray(new String[value.size()]) : null; } }); request = new WebflowHttpServletRequestWrapper(context.getRequest(), m, identifierNoDashes); } else { request = new WebflowHttpServletRequestWrapper(context.getRequest(), new HashMap<>(context.getRequest().getParameterMap()), identifierNoDashes); } String s = (String) request.getSession().getAttribute("webflowResponse" + identifierNoDashes); if (s != null) { request.getSession().removeAttribute("webflowResponse" + identifierNoDashes); return s; } // skip aggregation for potentials fragments under the webflow boolean aggregationSkippedForWebflow = false; if (!AggregateFilter.skipAggregation(context.getRequest())) { aggregationSkippedForWebflow = true; context.getRequest().setAttribute(AggregateFilter.SKIP_AGGREGATION, true); } flowPath = MODULE_PREFIX_PATTERN.matcher(view.getPath()).replaceFirst(""); RequestDispatcher rd = request.getRequestDispatcher("/flow/" + flowPath); Object oldModule = request.getAttribute("currentModule"); request.setAttribute("currentModule", view.getModule()); if (logger.isDebugEnabled()) { dumpRequestAttributes(request); } StringResponseWrapper responseWrapper = new StringResponseWrapper(response); try { FlowDefinitionRegistry reg = ((FlowDefinitionRegistry) view.getModule().getContext() .getBean("jahiaFlowRegistry")); final GenericApplicationContext applicationContext = (GenericApplicationContext) reg .getFlowDefinition(flowPath).getApplicationContext(); applicationContext.setClassLoader(view.getModule().getClassLoader()); applicationContext.setResourceLoader(new ResourceLoader() { @Override public org.springframework.core.io.Resource getResource(String location) { return applicationContext.getParent().getResource("/" + flowPath + "/" + location); } @Override public ClassLoader getClassLoader() { return view.getModule().getClassLoader(); } }); rd.include(request, responseWrapper); String redirect = responseWrapper.getRedirect(); if (redirect != null && context.getRedirect() == null) { // if we have an absolute redirect, set it and move on if (redirect.startsWith("http:/") || redirect.startsWith("https://")) { context.setRedirect(responseWrapper.getRedirect()); } else { while (redirect != null) { final String qs = StringUtils.substringAfter(responseWrapper.getRedirect(), "?"); final Map<String, String[]> params = new HashMap<String, String[]>(); if (!StringUtils.isEmpty(qs)) { params.put("webflowexecution" + identifierNoDashes, new String[] { StringUtils .substringAfterLast(qs, "webflowexecution" + identifierNoDashes + "=") }); } HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request) { @Override public String getMethod() { return "GET"; } @SuppressWarnings("rawtypes") @Override public Map getParameterMap() { return params; } @Override public String getParameter(String name) { return params.containsKey(name) ? params.get(name)[0] : null; } @Override public Enumeration getParameterNames() { return new Vector(params.keySet()).elements(); } @Override public String[] getParameterValues(String name) { return params.get(name); } @Override public Object getAttribute(String name) { if (WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE.equals(name)) { return qs; } return super.getAttribute(name); } @Override public String getQueryString() { return qs; } }; rd = requestWrapper.getRequestDispatcher("/flow/" + flowPath + "?" + qs); responseWrapper = new StringResponseWrapper(response); rd.include(requestWrapper, responseWrapper); String oldRedirect = redirect; redirect = responseWrapper.getRedirect(); if (redirect != null) { // if we have an absolute redirect, exit the loop if (redirect.startsWith("http://") || redirect.startsWith("https://")) { context.setRedirect(redirect); break; } } else if (request.getMethod().equals("POST")) { // set the redirect to the last non-null one request.getSession().setAttribute("webflowResponse" + identifierNoDashes, responseWrapper.getString()); context.setRedirect(oldRedirect); } } } } } catch (ServletException e) { throw new RenderException(e.getRootCause() != null ? e.getRootCause() : e); } catch (IOException e) { throw new RenderException(e); } finally { request.setAttribute("currentModule", oldModule); } try { if (aggregationSkippedForWebflow) { request.removeAttribute(AggregateFilter.SKIP_AGGREGATION); } return responseWrapper.getString(); } catch (IOException e) { throw new RenderException(e); } }
From source file:com.android.build.gradle.internal.incremental.fixture.ClassEnhancement.java
private static Map<String, List<String>> findEnhancedClasses(final Map<String, File> compileOutputFolders) { final Context context = InstrumentationRegistry.getContext(); return Maps.transformEntries(compileOutputFolders, new Maps.EntryTransformer<String, File, List<String>>() { @Override/*from w w w . j a v a2 s. c om*/ public List<String> transformEntry(@Nullable String patch, @Nullable File outputFolder) { try { InputStream classesIS = context.getAssets().open(outputFolder.getPath() + "/classes.txt"); try { Iterable<String> classPaths = Splitter.on('\n').omitEmptyStrings() .split(CharStreams.toString(new InputStreamReader(classesIS, Charsets.UTF_8))); return Lists.newArrayList(Iterables.transform(classPaths, new Function<String, String>() { @Override public String apply(@Nullable String relativePath) { return relativePath.substring(0, relativePath.length() - 6 /*.class */).replace('/', '.'); } })); } finally { classesIS.close(); } } catch (IOException e) { throw new IllegalArgumentException("Could not open patch classes.dex", e); } } }); }
From source file:com.viadeo.kasper.core.component.event.eventbus.EventMessageHandler.java
@Override public void onMessage(Message message, Channel channel) throws Exception { final long deliveryTag = message.getMessageProperties().getDeliveryTag(); final EventMessage eventMessage; try {/*from ww w . j a v a 2 s . co m*/ eventMessage = (EventMessage) converter.fromMessage(message); } catch (Throwable e) { messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(), e)); channel.basicNack(deliveryTag, false, false); return; } metricRegistry.counter(HANDLE_MESSAGE_COUNT_METRIC).inc(); metricRegistry.histogram(HANDLE_MESSAGE_TIME_METRIC).update(timeTaken(eventMessage)); MDC.setContextMap(Maps.transformEntries(eventMessage.getMetaData(), new Maps.EntryTransformer<String, Object, String>() { @Override public String transformEntry(String key, Object value) { return String.valueOf(value); } })); EventResponse response = null; try { response = eventListener .handle(new com.viadeo.kasper.core.component.event.listener.EventMessage(eventMessage)); } catch (Exception e) { logger.error("Can't process event", e); response = EventResponse.failure(new KasperReason(CoreReasonCode.INTERNAL_COMPONENT_ERROR, e)); } final KasperReason reason = response.getReason(); switch (response.getStatus()) { case SUCCESS: case OK: logger.debug("Successfully handled the event message ({}) by '{}'", eventMessage.getIdentifier(), eventListener.getName()); channel.basicAck(deliveryTag, false); break; case ERROR: if (reason.getException().isPresent()) { logger.warn("Failed to handle the event message ({}) by '{}' : {}", eventMessage.getIdentifier(), eventListener.getName(), reason.getMessages(), reason.getException().get()); } else { logger.warn("Failed to handle the event message ({}) by '{}' : {}", eventMessage.getIdentifier(), eventListener.getName(), reason.getMessages()); } channel.basicAck(deliveryTag, false); break; case FAILURE: metricRegistry.counter(HANDLE_MESSAGE_ERROR_METRIC).inc(); final Integer nbAttempt = getIncrementedNbAttempt(message); final DateTime time = new DateTime(message.getMessageProperties().getTimestamp()); LOGGER.debug("Failed to attempt to handle the event message ({}) : {} time(s) by '{}'", eventMessage.getIdentifier(), nbAttempt, eventListener.getName()); if (response.isTemporary()) { if (nbAttempt >= maxAttempts) { if (DateTime.now().minusHours(requeueThresholdInHours).isBefore(time)) { LOGGER.info("Requeue the event message ({}) in the related queue of '{}'", eventMessage.getIdentifier(), eventListener.getClass().getSimpleName()); channel.basicNack(deliveryTag, false, true); return; } else { messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(), reason.getException().or(new RuntimeException("Failed to handle event message")))); channel.basicNack(deliveryTag, false, false); return; } } } else if (nbAttempt >= maxAttempts) { messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(), reason.getException().or(new RuntimeException("Failed to handle event message")))); channel.basicNack(deliveryTag, false, false); break; } throw new MessageHandlerException(eventListener.getClass(), reason.getException().or(new KasperEventException(response.getReason().toString()))); default: messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(), reason.getException().or( new RuntimeException(String.format("Status not managed '%s'", response.getStatus()))))); channel.basicNack(deliveryTag, false, false); break; } }
From source file:org.apache.beam.runners.spark.metrics.WithMetricsSupport.java
private Function<Map.Entry<String, Metric>, Map<String, Gauge>> beamMetricToGauges() { return new Function<Map.Entry<String, Metric>, Map<String, Gauge>>() { @Override/*from ww w. j a va2 s. co m*/ public Map<String, Gauge> apply(final Map.Entry<String, Metric> entry) { final Map<String, ?> metrics = ((SparkBeamMetric) entry.getValue()).renderAll(); final String parentName = entry.getKey(); final Map<String, Gauge> gaugeMap = Maps.transformEntries(metrics, toGauge()); final Map<String, Gauge> fullNameGaugeMap = Maps.newLinkedHashMap(); for (Map.Entry<String, Gauge> gaugeEntry : gaugeMap.entrySet()) { fullNameGaugeMap.put(parentName + "." + gaugeEntry.getKey(), gaugeEntry.getValue()); } return Maps.filterValues(fullNameGaugeMap, Predicates.notNull()); } }; }
From source file:org.openengsb.core.services.internal.security.EntryUtils.java
private static Map<String, Object> convertEntryMapToAttributeMap(Map<String, EntryValue> entryMap) { return Maps.transformEntries(entryMap, new EntryValueToObjectTransformer()); }
From source file:ai.grakn.test.engine.tasks.manager.singlequeue.MockGraknConsumer.java
@Override public synchronized ConsumerRecords<K, V> poll(long timeout) { ensureNotClosed();//from w ww .j a v a 2s.co m // Synchronize around the entire execution so new tasks to be triggered on subsequent poll calls can be added in // the callback synchronized (pollTasks) { Runnable task = pollTasks.poll(); if (task != null) task.run(); } if (wakeup.get()) { wakeup.set(false); throw new WakeupException(); } if (exception != null) { RuntimeException exception = this.exception; this.exception = null; throw exception; } // Handle seeks that need to wait for a poll() call to be processed for (TopicPartition tp : subscriptions.missingFetchPositions()) updateFetchPosition(tp); // CHANGED: Do not update the consumed offset automatically // CHANGED: Retrieve partition only beyond the current offset Map<TopicPartition, List<ConsumerRecord<K, V>>> recordOffset = Maps.transformEntries(records, (partition, recordList) -> { assert recordList != null; long offset = subscriptions.position(partition); return recordList.subList((int) offset, recordList.size()); }); ConsumerRecords<K, V> copy = new ConsumerRecords<K, V>(recordOffset); if (copy.count() == 0 && emptyPollTask != null) emptyPollTask.run(); return copy; }
From source file:controllers.SearchController.java
protected Result renderSearch(String q, String rangeType, int relative, String from, String to, String keyword, String interval, int page, String savedSearchId, String fields, int displayWidth, SearchSort sort, Stream stream, String filter) { UniversalSearch search;//from w ww. jav a 2 s . c o m try { search = getSearch(q, filter, rangeType, relative, from, to, keyword, page, sort); } catch (InvalidRangeParametersException e2) { return status(400, views.html.errors.error.render("Invalid range parameters provided.", e2, request())); } catch (IllegalArgumentException e1) { return status(400, views.html.errors.error.render("Invalid range type provided.", e1, request())); } SearchResult searchResult; DateHistogramResult histogramResult; SavedSearch savedSearch = null; Set<String> selectedFields = getSelectedFields(fields); String formattedHistogramResults; Set<StreamDescription> streams; Set<InputDescription> inputs = Sets.newHashSet(); Map<String, NodeDescription> nodes = Maps.newHashMap(); nodes.putAll(Maps.transformEntries(serverNodes.asMap(), new Maps.EntryTransformer<String, Node, NodeDescription>() { @Override public NodeDescription transformEntry(@Nullable String key, @Nullable Node value) { return new NodeDescription(value); } })); try { if (savedSearchId != null && !savedSearchId.isEmpty()) { savedSearch = savedSearchService.get(savedSearchId); } searchResult = search.search(); // TODO create a bulk call to get stream and input details (and restrict the fields that come back) final Set<String> streamIds = Sets.newHashSet(); final HashMultimap<String, String> usedInputIds = HashMultimap.create(); final HashMultimap<String, String> usedRadioIds = HashMultimap.create(); for (MessageResult messageResult : searchResult.getMessages()) { streamIds.addAll(messageResult.getStreamIds()); usedInputIds.put(messageResult.getSourceNodeId(), messageResult.getSourceInputId()); if (messageResult.getSourceRadioId() != null) { usedRadioIds.put(messageResult.getSourceRadioId(), messageResult.getSourceRadioInputId()); } } // resolve all stream information in the result set final HashSet<Stream> allStreams = Sets.newHashSet(streamService.all().iterator()); streams = Sets.newHashSet(Collections2.transform(Sets.filter(allStreams, new Predicate<Stream>() { @Override public boolean apply(Stream input) { return streamIds.contains(input.getId()); } }), new Function<Stream, StreamDescription>() { @Nullable @Override public StreamDescription apply(@Nullable Stream stream) { return StreamDescription.of(stream); } })); // resolve all used inputs and nodes from the result set final Map<String, Node> nodeMap = serverNodes.asMap(); for (final String nodeId : usedInputIds.keySet()) { final Node node = nodeMap.get(nodeId); if (node != null) { final HashSet<Input> allInputs = Sets.newHashSet(node.getInputs()); inputs = Sets.newHashSet(Collections2.transform(Sets.filter(allInputs, new Predicate<Input>() { @Override public boolean apply(Input input) { final Set<String> inputIds = usedInputIds.get(nodeId); return inputIds != null && inputIds.contains(input.getId()); } }), new Function<Input, InputDescription>() { @Nullable @Override public InputDescription apply(Input input) { return new InputDescription(input); } })); } } // resolve radio inputs for (final String radioId : usedRadioIds.keySet()) { try { final Radio radio = nodeService.loadRadio(radioId); nodes.put(radio.getId(), new NodeDescription(radio)); final HashSet<Input> allRadioInputs = Sets.newHashSet(radio.getInputs()); inputs.addAll(Collections2.transform(Sets.filter(allRadioInputs, new Predicate<Input>() { @Override public boolean apply(Input input) { return usedRadioIds.get(radioId).contains(input.getId()); } }), new Function<Input, InputDescription>() { @Override public InputDescription apply(Input input) { return new InputDescription(input); } })); } catch (NodeService.NodeNotFoundException e) { Logger.warn("Could not load radio node " + radioId, e); } } searchResult.setAllFields(getAllFields()); // histogram resolution (strangely aka interval) if (interval == null || interval.isEmpty() || !SearchTools.isAllowedDateHistogramInterval(interval)) { interval = determineHistogramResolution(searchResult); } histogramResult = search.dateHistogram(interval); formattedHistogramResults = formatHistogramResults(histogramResult.getResults(), displayWidth); } catch (IOException e) { return status(504, views.html.errors.error.render(ApiClient.ERROR_MSG_IO, e, request())); } catch (APIException e) { if (e.getHttpCode() == 400) { try { QueryParseError qpe = objectMapper.readValue(e.getResponseBody(), QueryParseError.class); return ok(views.html.search.queryerror.render(currentUser(), q, qpe, savedSearch, fields, stream)); } catch (IOException ioe) { // Ignore } } String message = "There was a problem with your search. We expected HTTP 200, but got a HTTP " + e.getHttpCode() + "."; return status(504, views.html.errors.error.render(message, e, request())); } return ok(views.html.search.index.render(currentUser(), q, search, page, savedSearch, selectedFields, searchResult, histogramResult, formattedHistogramResults, nodes, Maps.uniqueIndex(streams, new Function<StreamDescription, String>() { @Nullable @Override public String apply(@Nullable StreamDescription stream) { return stream == null ? null : stream.getId(); } }), Maps.uniqueIndex(inputs, new Function<InputDescription, String>() { @Nullable @Override public String apply(@Nullable InputDescription input) { return input == null ? null : input.getId(); } }), stream)); }
From source file:org.apache.twill.internal.AbstractTwillController.java
@Override public final ListenableFuture<Set<String>> restartInstances( Map<String, ? extends Set<Integer>> runnableToInstanceIds) { Map<String, String> runnableToStringInstanceIds = Maps.transformEntries(runnableToInstanceIds, new Maps.EntryTransformer<String, Set<Integer>, String>() { @Override/* ww w .j a va2s . co m*/ public String transformEntry(String runnableName, Set<Integer> instanceIds) { validateInstanceIds(runnableName, instanceIds); return GSON.toJson(instanceIds, new TypeToken<Set<Integer>>() { }.getType()); } }); Command updateStateCommand = Command.Builder.of(Constants.RESTART_RUNNABLES_INSTANCES) .addOptions(runnableToStringInstanceIds).build(); Message message = SystemMessages.updateRunnablesInstances(updateStateCommand); return sendMessage(message, runnableToInstanceIds.keySet()); }
From source file:co.cask.cdap.internal.app.runtime.procedure.ProcedureDispatcher.java
private ProcedureRequest createProcedureRequest(HttpRequest request, Channel channel, String requestMethod) { try {/* ww w .jav a 2 s.com*/ Map<String, String> args; ChannelBuffer content; if (HttpMethod.POST.equals(request.getMethod())) { content = request.getContent(); } else { //GET method - Get key/value pairs from the URI Map<String, List<String>> queryParams = new QueryStringDecoder(request.getUri()).getParameters(); content = ChannelBuffers.EMPTY_BUFFER; if (!queryParams.isEmpty()) { content = jsonEncode(Maps.transformEntries(queryParams, MULTIMAP_TO_MAP_FUNCTION), QUERY_PARAMS_TYPE, ChannelBuffers.dynamicBuffer(request.getUri().length())); } } if (content == null || !content.readable()) { args = ImmutableMap.of(); } else { args = GSON.fromJson(new InputStreamReader(new ChannelBufferInputStream(content), Charsets.UTF_8), REQUEST_TYPE); } //Extract the GET method name Matcher methodMatcher = METHOD_GET_PATTERN.matcher(requestMethod); if (methodMatcher.find()) { requestMethod = methodMatcher.group(1); } return new DefaultProcedureRequest(requestMethod, args); } catch (Exception ex) { errorResponse(HttpResponseStatus.BAD_REQUEST, channel, "Only json map<string,string> is supported."); } return null; }
From source file:biz.dfch.j.graylog2.plugin.input.dfchBizExecScript.java
@Override public Map<String, Object> getAttributes() { return Maps.transformEntries(getConfiguration().getSource(), new Maps.EntryTransformer<String, Object, Object>() { @Override//from ww w . j a v a 2s. c o m public Object transformEntry(String key, Object value) { return value; } }); }