Example usage for com.google.common.collect Multimap asMap

List of usage examples for com.google.common.collect Multimap asMap

Introduction

In this page you can find the example usage for com.google.common.collect Multimap asMap.

Prototype

Map<K, Collection<V>> asMap();

Source Link

Document

Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values.

Usage

From source file:org.n52.janmayen.http.MediaType.java

/**
 * Constructs a media type using the supplied parameters.
 *
 * @param type       the type (may be <code>null</code> for a wild card)
 * @param subtype    the subtype (may be <code>null</code> for a wild card)
 * @param parameters the parameter map/*from   www .j a  v a2  s  .  c  om*/
 * @deprecated use {@link #MediaType(java.lang.String, java.lang.String, java.util.Map) }
 */
@Deprecated
public MediaType(String type, String subtype, Multimap<String, String> parameters) {
    this(type, subtype, parameters.asMap());
}

From source file:org.jclouds.openstack.keystone.v2_0.suppliers.LocationIdToURIFromAccessForTypeAndVersion.java

@VisibleForTesting
Map<String, Endpoint> firstEndpointInLocation(Multimap<String, Endpoint> locationToEndpoints) {
    Builder<String, Endpoint> locationToEndpointBuilder = ImmutableMap.<String, Endpoint>builder();
    for (Map.Entry<String, Collection<Endpoint>> entry : locationToEndpoints.asMap().entrySet()) {
        String locationId = entry.getKey();
        Collection<Endpoint> endpoints = entry.getValue();
        switch (endpoints.size()) {
        case 0:/*  w ww .  j a  va2 s .  c o m*/
            logNoEndpointsInLocation(locationId);
            break;
        default:
            locationToEndpointBuilder.put(locationId, Iterables.get(endpoints, 0));
        }
    }
    return locationToEndpointBuilder.build();
}

From source file:org.jclouds.openstack.keystone.v2_0.suppliers.LocationIdToURIFromAccessForTypeAndVersion.java

@VisibleForTesting
Map<String, Endpoint> refineToVersionSpecificEndpoint(Multimap<String, Endpoint> locationToEndpoints) {
    Builder<String, Endpoint> locationToEndpointBuilder = ImmutableMap.<String, Endpoint>builder();
    for (Map.Entry<String, Collection<Endpoint>> entry : locationToEndpoints.asMap().entrySet()) {
        String locationId = entry.getKey();
        Collection<Endpoint> endpoints = entry.getValue();
        switch (endpoints.size()) {
        case 0:/*from   w w  w.  java  2 s.  c  o m*/
            logNoEndpointsInLocation(locationId);
            break;
        default:
            putIfPresent(locationId, strictMatchEndpointVersion(endpoints, locationId),
                    locationToEndpointBuilder);
        }

    }
    return locationToEndpointBuilder.build();
}

From source file:exporter.DataExporter.java

public void flush(Multimap<Path, Long> results) {
    try (BufferedWriter bw = Files.newBufferedWriter(generateFilePathWithTimestamp(),
            Charset.forName(charsetName), StandardOpenOption.WRITE, StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING)) {
        TsvWriter writer = new TsvWriter(bw, new TsvWriterSettings());

        results.asMap().forEach(flushRow(writer));

        writer.close();//w w  w .  j av a2  s .  co  m
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.aksw.simba.bengal.triple2nl.DocumentGenerator.java

private Map<Node, Collection<Triple>> groupBySubject(Set<Triple> triples) {
    Multimap<Node, Triple> subject2Triples = HashMultimap.create();
    for (Triple triple : triples) {
        subject2Triples.put(triple.getSubject(), triple);
    }//from   w  w w  .  j a  va  2  s  .c o  m
    return subject2Triples.asMap();
}

From source file:com.google.devrel.gmscore.tools.apk.arsc.ArscBlamer.java

/** Generates blame mappings. */
public void blame() {
    Multimap<ResourceEntry, TypeChunk.Entry> entries = getResourceEntries();
    for (Entry<ResourceEntry, Collection<TypeChunk.Entry>> entry : entries.asMap().entrySet()) {
        ResourceEntry resourceEntry = entry.getKey();
        PackageChunk packageChunk = Preconditions
                .checkNotNull(resourceTable.getPackage(resourceEntry.packageName()));
        int keyCount = packageChunk.getKeyStringPool().getStringCount();
        int typeCount = packageChunk.getTypeStringPool().getStringCount();
        for (TypeChunk.Entry chunkEntry : entry.getValue()) {
            blameKeyOrType(keyToBlame, packageChunk, chunkEntry.keyIndex(), resourceEntry, keyCount);
            blameKeyOrType(typeToBlame, packageChunk, chunkEntry.parent().getId() - 1, resourceEntry,
                    typeCount);/*from  w  w  w  . j  a  v  a  2s . co m*/
            blameFromTypeChunkEntry(chunkEntry);
        }
        blamePackage(packageChunk, resourceEntry);
    }
    Multimaps.invertFrom(entries, typeEntryToBlame);
    for (TypeChunk.Entry entry : typeEntryToBlame.keySet()) {
        blameFromTypeChunkEntry(entry);
    }
}

From source file:com.b2international.snowowl.snomed.datastore.request.DescriptionRequestHelper.java

private Map<String, SnomedDescription> extractFirst(
        Multimap<String, SnomedDescription> descriptionsByConceptId) {
    Map<String, SnomedDescription> uniqueMap = Maps.transformValues(descriptionsByConceptId.asMap(),
            values -> Iterables.getFirst(values, null));
    return ImmutableMap.copyOf(Maps.filterValues(uniqueMap, Predicates.notNull()));
}

From source file:com.squareup.wire.schema.EnumType.java

private void validateTagUniqueness(Linker linker) {
    Multimap<Integer, EnumConstant> tagToConstant = LinkedHashMultimap.create();
    for (EnumConstant constant : constants) {
        tagToConstant.put(constant.tag(), constant);
    }// w ww  .j av  a 2  s .  c o m

    for (Map.Entry<Integer, Collection<EnumConstant>> entry : tagToConstant.asMap().entrySet()) {
        if (entry.getValue().size() > 1) {
            StringBuilder error = new StringBuilder();
            error.append(String.format("multiple enum constants share tag %s:", entry.getKey()));
            int index = 1;
            for (EnumConstant constant : entry.getValue()) {
                error.append(String.format("\n  %s. %s (%s)", index++, constant.name(), constant.location()));
            }
            linker.addError("%s", error);
        }
    }
}

From source file:org.spf4j.perf.impl.ms.tsdb.TSDBMeasurementStore.java

/**
 * Quantized recorders will have min, max avg charts and distribution charts
 * generated. Counting recorders will have simple charts generated.
 *
 * @param startTimeMillis//from  www .  j  a v  a2  s.c o  m
 * @param endTimeMillis
 * @param width
 * @param height
 * @return
 * @throws IOException
 */
@JmxExport(name = "generateChartsInterval", description = "generate charts for all measurements in specified interval")
public List<String> generateCharts(final long startTimeMillis, final long endTimeMillis, final int width,
        final int height) throws IOException {
    try {
        database.flush();
        List<String> result = new ArrayList<>();
        Collection<TSTable> columnsInfo = database.getTSTables();
        for (TSTable info : columnsInfo) {
            TimeSeries data = database.read(info.getTableName(), startTimeMillis, endTimeMillis);
            if (data.getTimeStamps().length > 0) {
                if (canGenerateMinMaxAvgCount(info)) {
                    result.add(generateMinMaxAvgCountChart(info, data, width, height));
                }
                if (canGenerateHeatChart(info)) {
                    result.add(generateHeatChart(info, data, width, height));
                }
            }
        }
        Multimap<String, TSTable> counters = getCounters(columnsInfo);
        for (Map.Entry<String, Collection<TSTable>> entry : counters.asMap().entrySet()) {
            Collection<TSTable> tables = entry.getValue();
            int l = tables.size();
            long[][] timestamps = new long[l][];
            double[][] cdata = new double[l][];
            double[][] cdata2 = new double[l][];
            int i = 0;
            String[] measurementNames = new String[cdata.length];
            String[] measurementNames2 = new String[cdata2.length];
            String uom1 = "count";
            String uom2 = "";
            for (TSTable colInfo : tables) {
                TimeSeries data = database.read(colInfo.getTableName(), startTimeMillis, endTimeMillis);
                timestamps[i] = data.getTimeStamps();
                final long[][] values = data.getValues();
                cdata[i] = Arrays.getColumnAsDoubles(values, colInfo.getColumnIndex("count"));
                cdata2[i] = Arrays.getColumnAsDoubles(values, colInfo.getColumnIndex("total"));
                measurementNames[i] = colInfo.getTableName() + ".count";
                measurementNames2[i] = colInfo.getTableName() + ".total";
                uom2 = new String(colInfo.getTableMetaData(), Charsets.UTF_8);
                i++;
            }
            result.add(generateCountChart(entry.getKey(), timestamps, measurementNames, measurementNames2, uom1,
                    uom2, cdata, cdata2, width, height));
        }
        LOG.info("Generated charts {}", result);
        return result;
    } catch (IOException | RuntimeException ex) {
        LOG.error("Error while generating charts", ex);
        throw ex;
    }
}

From source file:com.facebook.presto.server.ResourceUtil.java

public static Session createSessionForRequest(HttpServletRequest servletRequest, AccessControl accessControl,
        SessionPropertyManager sessionPropertyManager, QueryId queryId) {
    String catalog = trimEmptyToNull(servletRequest.getHeader(PRESTO_CATALOG));
    String schema = trimEmptyToNull(servletRequest.getHeader(PRESTO_SCHEMA));
    assertRequest((catalog != null) || (schema == null), "Schema is set but catalog is not");

    String user = trimEmptyToNull(servletRequest.getHeader(PRESTO_USER));
    assertRequest(user != null, "User must be set");

    Principal principal = servletRequest.getUserPrincipal();
    try {//from ww w .  j  a va 2  s  .c o  m
        accessControl.checkCanSetUser(principal, user);
    } catch (AccessDeniedException e) {
        throw new WebApplicationException(e.getMessage(), Status.FORBIDDEN);
    }

    Identity identity = new Identity(user, Optional.ofNullable(principal));
    SessionBuilder sessionBuilder = Session.builder(sessionPropertyManager).setQueryId(queryId)
            .setIdentity(identity).setSource(servletRequest.getHeader(PRESTO_SOURCE)).setCatalog(catalog)
            .setSchema(schema).setRemoteUserAddress(servletRequest.getRemoteAddr())
            .setUserAgent(servletRequest.getHeader(USER_AGENT));

    String timeZoneId = servletRequest.getHeader(PRESTO_TIME_ZONE);
    if (timeZoneId != null) {
        sessionBuilder.setTimeZoneKey(getTimeZoneKey(timeZoneId));
    }

    String language = servletRequest.getHeader(PRESTO_LANGUAGE);
    if (language != null) {
        sessionBuilder.setLocale(Locale.forLanguageTag(language));
    }

    // parse session properties
    Multimap<String, Entry<String, String>> sessionPropertiesByCatalog = HashMultimap.create();
    for (String sessionHeader : splitSessionHeader(servletRequest.getHeaders(PRESTO_SESSION))) {
        parseSessionHeader(sessionHeader, sessionPropertiesByCatalog, sessionPropertyManager);
    }

    // verify user can set the session properties
    try {
        for (Entry<String, Entry<String, String>> property : sessionPropertiesByCatalog.entries()) {
            String catalogName = property.getKey();
            String propertyName = property.getValue().getKey();
            if (catalogName == null) {
                accessControl.checkCanSetSystemSessionProperty(identity, propertyName);
            } else {
                accessControl.checkCanSetCatalogSessionProperty(identity, catalogName, propertyName);
            }
        }
    } catch (AccessDeniedException e) {
        throw new WebApplicationException(e.getMessage(), Status.BAD_REQUEST);
    }
    sessionBuilder.setSystemProperties(toMap(sessionPropertiesByCatalog.get(null)));
    for (Entry<String, Collection<Entry<String, String>>> entry : sessionPropertiesByCatalog.asMap()
            .entrySet()) {
        if (entry.getKey() != null) {
            sessionBuilder.setCatalogProperties(entry.getKey(), toMap(entry.getValue()));
        }
    }

    return sessionBuilder.build();
}