List of usage examples for com.google.common.collect Multimap asMap
Map<K, Collection<V>> asMap();
From source file:com.cloudera.flume.master.ConfigManager.java
/** * Creates two tables for display in the primitive webapp. * /*from www. j a v a2s . co m*/ * TODO convert to a generic report */ @Override synchronized public ReportEvent getMetrics() { StringBuilder html = new StringBuilder(); html.append("<h2>Node configuration</h2>\n<table border=\"1\"><tr>" + "<th>Node</th><th>Version</th><th>Flow ID</th><th>Source</th>" + "<th>Sink</th></tr>"); Map<String, FlumeConfigData> cfgs = new TreeMap<String, FlumeConfigData>(cfgStore.getConfigs()); synchronized (cfgs) { for (Entry<String, FlumeConfigData> e : cfgs.entrySet()) { appendHtmlFlumeConfigData(html, e.getKey(), e.getValue()); } } html.append("</table>\n\n"); // a table that has a mapping from physical nodes to logical nodes. html.append("<h2>Physical/Logical Node mapping</h2>\n<table border=\"1\">" + "<tr><th>physical node</th><th>logical node</th></tr>"); Multimap<String, String> nodes = cfgStore.getLogicalNodeMap(); synchronized (nodes) { for (Entry<String, Collection<String>> e : nodes.asMap().entrySet()) { appendHtmlPhysicalLogicalMapping(html, e.getKey(), e.getValue()); } } html.append("</table>\n\n"); return ReportEvent.createLegacyHtmlReport("configs", html.toString()); }
From source file:com.continuuity.http.BasicHttpResponder.java
/** * Respond to the client saying the response will be in chunks. Add chunks to response using @{link sendChunk} * and @{link sendChunkEnd}.//w w w . j a va2 s . c o m * @param status the status code to respond with. Defaults to 200-OK if null. * @param headers additional headers to send with the response. May be null. */ @Override public void sendChunkStart(HttpResponseStatus status, Multimap<String, String> headers) { HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status != null ? status : HttpResponseStatus.OK); if (headers != null) { for (Map.Entry<String, Collection<String>> entry : headers.asMap().entrySet()) { response.setHeader(entry.getKey(), entry.getValue()); } } response.setChunked(true); response.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); channel.write(response); }
From source file:org.eclipse.m2e.core.internal.project.registry.BasicProjectRegistry.java
public Map<ArtifactKey, Collection<IFile>> getWorkspaceArtifacts(String groupId, String artifactId) { Multimap<ArtifactKey, IFile> artifacts = HashMultimap.create(); for (Map.Entry<ArtifactKey, Set<IFile>> entry : workspaceArtifacts.entrySet()) { ArtifactKey workspaceKey = entry.getKey(); if (groupId.equals(workspaceKey.getGroupId()) && artifactId.equals(workspaceKey.getArtifactId())) { artifacts.putAll(workspaceKey, entry.getValue()); }/* w w w . j ava 2 s . com*/ } return artifacts.asMap(); }
From source file:org.sonar.server.measure.index.ProjectMeasuresIndex.java
private Map<String, QueryBuilder> createFilters(ProjectMeasuresQuery query) { Map<String, QueryBuilder> filters = new HashMap<>(); filters.put("__authorization", authorizationTypeSupport.createQueryFilter()); Multimap<String, MetricCriterion> metricCriterionMultimap = ArrayListMultimap.create(); query.getMetricCriteria().forEach(//from w ww. jav a 2s .c om metricCriterion -> metricCriterionMultimap.put(metricCriterion.getMetricKey(), metricCriterion)); metricCriterionMultimap.asMap().entrySet().forEach(entry -> { BoolQueryBuilder metricFilters = boolQuery(); entry.getValue().stream() .map(criterion -> nestedQuery(FIELD_MEASURES, boolQuery().filter(termQuery(FIELD_MEASURES_KEY, criterion.getMetricKey())) .filter(toValueQuery(criterion)))) .forEach(metricFilters::must); filters.put(entry.getKey(), metricFilters); }); query.getQualityGateStatus().ifPresent(qualityGateStatus -> filters.put(ALERT_STATUS_KEY, termQuery(FIELD_QUALITY_GATE_STATUS, QUALITY_GATE_STATUS.get(qualityGateStatus.name())))); query.getProjectUuids().ifPresent(projectUuids -> filters.put("ids", termsQuery("_id", projectUuids))); query.getLanguages() .ifPresent(languages -> filters.put(FILTER_LANGUAGES, termsQuery(FIELD_LANGUAGES, languages))); query.getOrganizationUuid().ifPresent(organizationUuid -> filters.put(FIELD_ORGANIZATION_UUID, termQuery(FIELD_ORGANIZATION_UUID, organizationUuid))); query.getTags().ifPresent(tags -> filters.put(FIELD_TAGS, termsQuery(FIELD_TAGS, tags))); createTextQueryFilter(query).ifPresent(queryBuilder -> filters.put("textQuery", queryBuilder)); return filters; }
From source file:org.apache.phoenix.hbase.index.write.TrackingParallelWriterIndexCommitter.java
@Override public void write(Multimap<HTableInterfaceReference, Mutation> toWrite, final boolean allowLocalUpdates, final int clientVersion) throws MultiIndexWriteFailureException { Set<Entry<HTableInterfaceReference, Collection<Mutation>>> entries = toWrite.asMap().entrySet(); TaskBatch<Boolean> tasks = new TaskBatch<Boolean>(entries.size()); List<HTableInterfaceReference> tables = new ArrayList<HTableInterfaceReference>(entries.size()); for (Entry<HTableInterfaceReference, Collection<Mutation>> entry : entries) { // get the mutations for each table. We leak the implementation here a little bit to save // doing a complete copy over of all the index update for each table. final List<Mutation> mutations = kvBuilder.cloneIfNecessary((List<Mutation>) entry.getValue()); // track each reference so we can get at it easily later, when determing failures final HTableInterfaceReference tableReference = entry.getKey(); final RegionCoprocessorEnvironment env = this.env; if (env != null && !allowLocalUpdates && tableReference.getTableName() .equals(env.getRegion().getTableDescriptor().getTableName().getNameAsString())) { continue; }/*from w ww. j a va2 s . c o m*/ tables.add(tableReference); /* * Write a batch of index updates to an index table. This operation stops (is cancelable) via two * mechanisms: (1) setting aborted or stopped on the IndexWriter or, (2) interrupting the running thread. * The former will only work if we are not in the midst of writing the current batch to the table, though we * do check these status variables before starting and before writing the batch. The latter usage, * interrupting the thread, will work in the previous situations as was at some points while writing the * batch, depending on the underlying writer implementation (HTableInterface#batch is blocking, but doesn't * elaborate when is supports an interrupt). */ tasks.add(new Task<Boolean>() { /** * Do the actual write to the primary table. */ @SuppressWarnings("deprecation") @Override public Boolean call() throws Exception { Table table = null; try { // this may have been queued, but there was an abort/stop so we try to early exit throwFailureIfDone(); if (allowLocalUpdates && env != null && tableReference.getTableName() .equals(env.getRegion().getTableDescriptor().getTableName().getNameAsString())) { try { throwFailureIfDone(); IndexUtil.writeLocalUpdates(env.getRegion(), mutations, true); return Boolean.TRUE; } catch (IOException ignord) { // when it's failed we fall back to the standard & slow way if (LOG.isTraceEnabled()) { LOG.trace( "indexRegion.batchMutate failed and fall back to HTable.batch(). Got error=" + ignord); } } } if (LOG.isTraceEnabled()) { LOG.trace("Writing index update:" + mutations + " to table: " + tableReference); } // if the client can retry index writes, then we don't need to retry here HTableFactory factory = clientVersion < MetaDataProtocol.MIN_CLIENT_RETRY_INDEX_WRITES ? retryingFactory : noRetriesFactory; table = factory.getTable(tableReference.get()); throwFailureIfDone(); table.batch(mutations, null); } catch (InterruptedException e) { // reset the interrupt status on the thread Thread.currentThread().interrupt(); throw e; } catch (Exception e) { throw e; } finally { if (table != null) { table.close(); } } return Boolean.TRUE; } private void throwFailureIfDone() throws SingleIndexWriteFailureException { if (stopped.isStopped() || (env != null && (env.getConnection() == null || env.getConnection().isClosed() || env.getConnection().isAborted())) || Thread.currentThread().isInterrupted()) { throw new SingleIndexWriteFailureException( "Pool closed, not attempting to write to the index!", null); } } }); } List<Boolean> results = null; try { LOG.debug("Waiting on index update tasks to complete..."); results = this.pool.submitUninterruptible(tasks); } catch (ExecutionException e) { throw new RuntimeException("Should not fail on the results while using a WaitForCompletionTaskRunner", e); } catch (EarlyExitFailure e) { throw new RuntimeException("Stopped while waiting for batch, quiting!", e); } // track the failures. We only ever access this on return from our calls, so no extra // synchronization is needed. We could update all the failures as we find them, but that add a // lot of locking overhead, and just doing the copy later is about as efficient. List<HTableInterfaceReference> failures = new ArrayList<HTableInterfaceReference>(); int index = 0; for (Boolean result : results) { // there was a failure if (result == null) { // we know which table failed by the index of the result failures.add(tables.get(index)); } index++; } // if any of the tasks failed, then we need to propagate the failure if (failures.size() > 0) { // make the list unmodifiable to avoid any more synchronization concerns throw new MultiIndexWriteFailureException(Collections.unmodifiableList(failures), PhoenixIndexFailurePolicy.getDisableIndexOnFailure(env)); } return; }
From source file:org.jetbrains.kotlin.resolve.DeclarationResolver.java
public void checkRedeclarationsInPackages(@NotNull KotlinCodeAnalyzer resolveSession, @NotNull Multimap<FqName, JetElement> topLevelFqNames) { for (Map.Entry<FqName, Collection<JetElement>> entry : topLevelFqNames.asMap().entrySet()) { FqName fqName = entry.getKey();// www .ja v a 2 s .com Collection<JetElement> declarationsOrPackageDirectives = entry.getValue(); if (fqName.isRoot()) continue; Set<DeclarationDescriptor> descriptors = getTopLevelDescriptorsByFqName(resolveSession, fqName); if (descriptors.size() > 1) { for (JetElement declarationOrPackageDirective : declarationsOrPackageDirectives) { PsiElement reportAt = declarationOrPackageDirective instanceof JetNamedDeclaration ? declarationOrPackageDirective : ((JetPackageDirective) declarationOrPackageDirective).getNameIdentifier(); trace.report(Errors.REDECLARATION.on(reportAt, fqName.shortName().asString())); } } } }
From source file:ezbake.common.http.request.Request.java
public void setHeaders(Multimap<String, String> headers) { this.headers.clear(); for (Map.Entry<String, Collection<String>> h : headers.asMap().entrySet()) { this.headers.putAll(h.getKey().toUpperCase(), h.getValue()); }//from ww w.jav a 2 s .co m }
From source file:co.cask.http.BasicHttpResponder.java
@Override public ChunkResponder sendChunkStart(HttpResponseStatus status, @Nullable Multimap<String, String> headers) { Preconditions.checkArgument(responded.compareAndSet(false, true), "Response has been already sent"); Preconditions.checkArgument((status.getCode() >= 200 && status.getCode() < 210), "Http Chunk Failure"); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status); if (headers != null) { for (Map.Entry<String, Collection<String>> entry : headers.asMap().entrySet()) { response.setHeader(entry.getKey(), entry.getValue()); }/* ww w . j a v a2s.c o m*/ } response.setChunked(true); response.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); if (keepAlive) { response.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } channel.write(response); return new ChannelChunkResponder(channel, keepAlive); }
From source file:org.terasology.web.servlet.ModuleServlet.java
@GET @Path("show") @Produces(MediaType.TEXT_HTML)/*from w w w . j a v a 2s . co m*/ public Viewable show() { logger.info("Requested module list as HTML"); Set<Name> names = model.getModuleIds(); // the key needs to be string, so that FreeMarker can use it for lookups Multimap<String, Module> map = TreeMultimap.create(String.CASE_INSENSITIVE_ORDER, versionComparator); for (Name name : names) { map.putAll(name.toString(), model.getModuleVersions(name)); } ImmutableMap<Object, Object> dataModel = ImmutableMap.builder().put("items", map.asMap()) .put("version", VersionInfo.getVersion()).build(); return new Viewable("/module-list.ftl", dataModel); }
From source file:com.facebook.buck.android.AndroidBinaryInstallGraphEnhancer.java
private List<BuildRule> createResourceInstallRules(ExopackageInfo.ResourcesInfo resourcesInfo, SourcePathRuleFinder ruleFinder, SourcePath manifestPath, SourcePath deviceExoContents) { // We construct a single ExopackageResourcesInstaller for each creator of exopackage resources. // This is done because the installers will synchronize on the underlying AndroidDevicesHelper // and so we don't want a single rule to generate a bunch of resource files and then take up a // bunch of build threads all waiting on each other. Multimap<BuildRule, ExopackagePathAndHash> creatorMappedPaths = resourcesInfo.getResourcesPaths().stream() .collect(ImmutableListMultimap .toImmutableListMultimap((ExopackagePathAndHash pathAndHash) -> ruleFinder .getRule(pathAndHash.getPath()).orElse(null), v -> v)); List<BuildRule> installers = new ArrayList<>(); int index = 0; for (Collection<ExopackagePathAndHash> paths : creatorMappedPaths.asMap().values()) { installers.add(new ExopackageResourcesInstaller( buildTarget.withAppendedFlavors(EXO_FILE_RESOURCE_INSTALL_FLAVOR, InternalFlavor.of(String.format("resources-%d", index))), projectFilesystem, ruleFinder, paths, manifestPath, deviceExoContents)); index++;//www.j a v a2 s . com } return installers; }