List of usage examples for com.google.common.collect Multimap entries
Collection<Map.Entry<K, V>> entries();
From source file:org.sonatype.restsimple.sitebricks.impl.SitebricksServiceDefinitionGenerator.java
private static boolean contentNegotiate(Multimap<String, String> headers, List<MediaType> mediaTypes) { if (mediaTypes.size() == 0) { return true; }// www . jav a2 s .c o m //TODO: Wildcard support for (Map.Entry<String, String> e : headers.entries()) { if (e.getKey().equalsIgnoreCase("Accept")) { if (e.getValue().trim().equals("*/*")) { return true; } for (MediaType mediaType : mediaTypes) { if (mediaType.toMediaType().equalsIgnoreCase(e.getValue())) { return true; } } } } return false; }
From source file:org.opendaylight.protocol.bgp.linkstate.impl.attribute.LinkAttributesParser.java
/** * Parse Link Attributes.// ww w.j a v a 2s.com * * @param attributes key is the tlv type and value is the value of the tlv * @param protocolId to differentiate parsing methods * @return {@link LinkStateAttribute} */ static LinkStateAttribute parseLinkAttributes(final Multimap<Integer, ByteBuf> attributes, final ProtocolId protocolId) { final LinkAttributesBuilder builder = new LinkAttributesBuilder(); final List<SrAdjIds> srAdjIds = new ArrayList<>(); final List<SrLanAdjIds> srLanAdjIds = new ArrayList<>(); final List<PeerSetSids> peerSetSids = new ArrayList<>(); for (final Entry<Integer, ByteBuf> entry : attributes.entries()) { LOG.trace("Link attribute TLV {}", entry.getKey()); final int key = entry.getKey(); final ByteBuf value = entry.getValue(); switch (key) { case TlvUtil.LOCAL_IPV4_ROUTER_ID: builder.setLocalIpv4RouterId(new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value))); LOG.debug("Parsed IPv4 Router-ID of local node: {}", builder.getLocalIpv4RouterId()); break; case TlvUtil.LOCAL_IPV6_ROUTER_ID: builder.setLocalIpv6RouterId(new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value))); LOG.debug("Parsed IPv6 Router-ID of local node: {}", builder.getLocalIpv6RouterId()); break; case REMOTE_IPV4_ROUTER_ID: builder.setRemoteIpv4RouterId(new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value))); LOG.debug("Parsed IPv4 Router-ID of remote node: {}", builder.getRemoteIpv4RouterId()); break; case REMOTE_IPV6_ROUTER_ID: builder.setRemoteIpv6RouterId(new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value))); LOG.debug("Parsed IPv6 Router-ID of remote node: {}", builder.getRemoteIpv6RouterId()); break; case ADMIN_GROUP: builder.setAdminGroup(new AdministrativeGroup(value.readUnsignedInt())); LOG.debug("Parsed Administrative Group {}", builder.getAdminGroup()); break; case MAX_BANDWIDTH: builder.setMaxLinkBandwidth(new Bandwidth(ByteArray.readAllBytes(value))); LOG.debug("Parsed Max Bandwidth {}", builder.getMaxLinkBandwidth()); break; case MAX_RESERVABLE_BANDWIDTH: builder.setMaxReservableBandwidth(new Bandwidth(ByteArray.readAllBytes(value))); LOG.debug("Parsed Max Reservable Bandwidth {}", builder.getMaxReservableBandwidth()); break; case UNRESERVED_BANDWIDTH: parseUnreservedBandwidth(value, builder); break; case TE_METRIC: builder.setTeMetric(new TeMetric(ByteArray.bytesToLong(ByteArray.readAllBytes(value)))); LOG.debug("Parsed Metric {}", builder.getTeMetric()); break; case LINK_PROTECTION_TYPE: builder.setLinkProtection(LinkProtectionType.forValue(value.readShort())); LOG.debug("Parsed Link Protection Type {}", builder.getLinkProtection()); break; case MPLS_PROTOCOL: final BitArray bits = BitArray.valueOf(value, FLAGS_SIZE); builder.setMplsProtocol(new MplsProtocolMask(bits.get(LDP_BIT), bits.get(RSVP_BIT))); LOG.debug("Parsed MPLS Protocols: {}", builder.getMplsProtocol()); break; case METRIC: // length can 3, 2 or 1 builder.setMetric(new Metric(ByteArray.bytesToLong(ByteArray.readAllBytes(value)))); LOG.debug("Parsed Metric {}", builder.getMetric()); break; case SHARED_RISK_LINK_GROUP: parseSrlg(value, builder); break; case LINK_OPAQUE: LOG.debug("Parsed Opaque value : {}", ByteBufUtil.hexDump(value)); break; case LINK_NAME: builder.setLinkName(new String(ByteArray.readAllBytes(value), StandardCharsets.US_ASCII)); LOG.debug("Parsed Link Name : {}", builder.getLinkName()); break; case SR_ADJ_ID: srAdjIds.add(SrLinkAttributesParser.parseAdjacencySegmentIdentifier(value, protocolId)); LOG.debug("Parsed Adjacency Segment Identifier :{}", srAdjIds.get(srAdjIds.size() - 1)); break; case SR_LAN_ADJ_ID: srLanAdjIds.add(SrLinkAttributesParser.parseLanAdjacencySegmentIdentifier(value, protocolId)); LOG.debug("Parsed Adjacency Segment Identifier :{}", srLanAdjIds.get(srLanAdjIds.size() - 1)); break; case PEER_NODE_SID_CODE: builder.setPeerNodeSid( new PeerNodeSidBuilder(SrLinkAttributesParser.parseEpeAdjacencySegmentIdentifier(value)) .build()); LOG.debug("Parsed Peer Segment Identifier :{}", builder.getPeerNodeSid()); break; case PEER_ADJ_SID_CODE: builder.setPeerAdjSid( new PeerAdjSidBuilder(SrLinkAttributesParser.parseEpeAdjacencySegmentIdentifier(value)) .build()); LOG.debug("Parsed Peer Segment Identifier :{}", builder.getPeerAdjSid()); break; case PEER_SET_SID_CODE: peerSetSids.add( new PeerSetSidsBuilder(SrLinkAttributesParser.parseEpeAdjacencySegmentIdentifier(value)) .build()); LOG.debug("Parsed Peer Set Sid :{}", peerSetSids.get(peerSetSids.size() - 1)); break; default: LOG.warn("TLV {} is not a valid link attribute, ignoring it", key); } } if (!srAdjIds.isEmpty()) { builder.setSrAdjIds(srAdjIds); } if (!srLanAdjIds.isEmpty()) { builder.setSrLanAdjIds(srLanAdjIds); } if (!peerSetSids.isEmpty()) { builder.setPeerSetSids(peerSetSids); } LOG.trace("Finished parsing Link Attributes."); return new LinkAttributesCaseBuilder().setLinkAttributes(builder.build()).build(); }
From source file:com.googlecode.blaisemath.graph.GraphUtils.java
/** * Generates connected components from an adjacency map. * @param <V> graph node type// ww w. ja v a2 s . co m * @param adj an adjacency map * @return set of components, as a set of sets */ public static <V> Collection<Set<V>> components(Multimap<V, V> adj) { Map<V, Set<V>> setMap = Maps.newLinkedHashMap(); for (Entry<V, V> en : adj.entries()) { V v1 = en.getKey(); V v2 = en.getValue(); boolean v1InSet = setMap.containsKey(v1); boolean v2InSet = setMap.containsKey(v2); if (v1InSet && v2InSet) { // check if components need to be merged if (setMap.get(v1) != setMap.get(v2)) { Set<V> nue = Sets.newHashSet(Iterables.concat(setMap.get(v1), setMap.get(v2))); for (V v : nue) { setMap.put(v, nue); } } } else if (v1InSet) { // v2 hasn't been seen before Set<V> set = setMap.get(v1); set.add(v2); setMap.put(v2, set); } else if (v2InSet) { // v1 hasn't been seen before Set<V> set = setMap.get(v2); set.add(v1); setMap.put(v1, set); } else { // create new set with v1 and v2 Set<V> set = Sets.newHashSet(v1, v2); setMap.put(v1, set); setMap.put(v2, set); } } return Sets.newLinkedHashSet(setMap.values()); }
From source file:com.google.devtools.build.lib.analysis.config.ConfigurationResolver.java
/** * This method allows resolution of configurations outside of a skyfunction call. * * <p>If {@link BuildConfiguration.Options#trimConfigurations()} is true, transforms a collection * of <Target, Configuration> pairs by trimming each target's configuration to only the fragments * the target and its transitive dependencies need. * * <p>Else returns configurations that unconditionally include all fragments. * * <p>Preserves the original input order (but merges duplicate nodes that might occur due to * top-level configuration transitions) . Uses original (untrimmed) configurations for targets * that can't be evaluated (e.g. due to loading phase errors). * * <p>This is suitable for feeding {@link ConfiguredTargetValue} keys: as general principle {@link * ConfiguredTarget}s should have exactly as much information in their configurations as they need * to evaluate and no more (e.g. there's no need for Android settings in a C++ configured target). * * @param inputs the original targets and configurations * @param asDeps the inputs repackaged as dependencies * @param eventHandler//ww w . ja va 2 s .c o m * @param skyframeExecutor */ // TODO(bazel-team): error out early for targets that fail - untrimmed configurations should // never make it through analysis (and especially not seed ConfiguredTargetValues) public static LinkedHashSet<TargetAndConfiguration> getConfigurationsFromExecutor( Iterable<TargetAndConfiguration> inputs, Multimap<BuildConfiguration, Dependency> asDeps, ExtendedEventHandler eventHandler, SkyframeExecutor skyframeExecutor) throws InterruptedException { Map<Label, Target> labelsToTargets = new LinkedHashMap<>(); for (TargetAndConfiguration targetAndConfig : inputs) { labelsToTargets.put(targetAndConfig.getLabel(), targetAndConfig.getTarget()); } // Maps <target, originalConfig> pairs to <target, finalConfig> pairs for targets that // could be successfully Skyframe-evaluated. Map<TargetAndConfiguration, TargetAndConfiguration> successfullyEvaluatedTargets = new LinkedHashMap<>(); if (!asDeps.isEmpty()) { for (BuildConfiguration fromConfig : asDeps.keySet()) { Multimap<Dependency, BuildConfiguration> trimmedTargets = skyframeExecutor .getConfigurations(eventHandler, fromConfig.getOptions(), asDeps.get(fromConfig)); for (Map.Entry<Dependency, BuildConfiguration> trimmedTarget : trimmedTargets.entries()) { Target target = labelsToTargets.get(trimmedTarget.getKey().getLabel()); successfullyEvaluatedTargets.put(new TargetAndConfiguration(target, fromConfig), new TargetAndConfiguration(target, trimmedTarget.getValue())); } } } LinkedHashSet<TargetAndConfiguration> result = new LinkedHashSet<>(); for (TargetAndConfiguration originalInput : inputs) { if (successfullyEvaluatedTargets.containsKey(originalInput)) { // The configuration was successfully trimmed. result.add(successfullyEvaluatedTargets.get(originalInput)); } else { // Either the configuration couldn't be determined (e.g. loading phase error) or it's null. result.add(originalInput); } } return result; }
From source file:org.opendaylight.protocol.bgp.linkstate.attribute.LinkAttributesParser.java
/** * Parse Link Attributes.//www . j a v a 2 s . c o m * * @param attributes key is the tlv type and value is the value of the tlv * @param protocolId to differentiate parsing methods * @return {@link LinkStateAttribute} */ static LinkStateAttribute parseLinkAttributes(final Multimap<Integer, ByteBuf> attributes, final ProtocolId protocolId) { final LinkAttributesBuilder builder = new LinkAttributesBuilder(); final List<SrAdjIds> srAdjIds = new ArrayList<SrAdjIds>(); final List<SrLanAdjIds> srLanAdjIds = new ArrayList<SrLanAdjIds>(); final List<PeerSetSids> peerSetSids = new ArrayList<PeerSetSids>(); for (final Entry<Integer, ByteBuf> entry : attributes.entries()) { LOG.trace("Link attribute TLV {}", entry.getKey()); final int key = entry.getKey(); final ByteBuf value = entry.getValue(); switch (key) { case TlvUtil.LOCAL_IPV4_ROUTER_ID: builder.setLocalIpv4RouterId(new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value))); LOG.debug("Parsed IPv4 Router-ID of local node: {}", builder.getLocalIpv4RouterId()); break; case TlvUtil.LOCAL_IPV6_ROUTER_ID: builder.setLocalIpv6RouterId(new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value))); LOG.debug("Parsed IPv6 Router-ID of local node: {}", builder.getLocalIpv6RouterId()); break; case REMOTE_IPV4_ROUTER_ID: builder.setRemoteIpv4RouterId(new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value))); LOG.debug("Parsed IPv4 Router-ID of remote node: {}", builder.getRemoteIpv4RouterId()); break; case REMOTE_IPV6_ROUTER_ID: builder.setRemoteIpv6RouterId(new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value))); LOG.debug("Parsed IPv6 Router-ID of remote node: {}", builder.getRemoteIpv6RouterId()); break; case ADMIN_GROUP: builder.setAdminGroup(new AdministrativeGroup(value.readUnsignedInt())); LOG.debug("Parsed Administrative Group {}", builder.getAdminGroup()); break; case MAX_BANDWIDTH: builder.setMaxLinkBandwidth(new Bandwidth(ByteArray.readAllBytes(value))); LOG.debug("Parsed Max Bandwidth {}", builder.getMaxLinkBandwidth()); break; case MAX_RESERVABLE_BANDWIDTH: builder.setMaxReservableBandwidth(new Bandwidth(ByteArray.readAllBytes(value))); LOG.debug("Parsed Max Reservable Bandwidth {}", builder.getMaxReservableBandwidth()); break; case UNRESERVED_BANDWIDTH: parseUnreservedBandwidth(value, builder); break; case TE_METRIC: builder.setTeMetric(new TeMetric(ByteArray.bytesToLong(ByteArray.readAllBytes(value)))); LOG.debug("Parsed Metric {}", builder.getTeMetric()); break; case LINK_PROTECTION_TYPE: builder.setLinkProtection(LinkProtectionType.forValue(value.readShort())); LOG.debug("Parsed Link Protection Type {}", builder.getLinkProtection()); break; case MPLS_PROTOCOL: final BitArray bits = BitArray.valueOf(value, FLAGS_SIZE); builder.setMplsProtocol(new MplsProtocolMask(bits.get(LDP_BIT), bits.get(RSVP_BIT))); LOG.debug("Parsed MPLS Protocols: {}", builder.getMplsProtocol()); break; case METRIC: // length can 3, 2 or 1 builder.setMetric(new Metric(ByteArray.bytesToLong(ByteArray.readAllBytes(value)))); LOG.debug("Parsed Metric {}", builder.getMetric()); break; case SHARED_RISK_LINK_GROUP: parseSrlg(value, builder); break; case LINK_OPAQUE: LOG.debug("Parsed Opaque value : {}", ByteBufUtil.hexDump(value)); break; case LINK_NAME: builder.setLinkName(new String(ByteArray.readAllBytes(value), Charsets.US_ASCII)); LOG.debug("Parsed Link Name : {}", builder.getLinkName()); break; case SR_ADJ_ID: srAdjIds.add(new SrAdjIdsBuilder( SrLinkAttributesParser.parseAdjacencySegmentIdentifier(value, protocolId)).build()); LOG.debug("Parsed Adjacency Segment Identifier :{}", srAdjIds.get(srAdjIds.size() - 1)); break; case SR_LAN_ADJ_ID: srLanAdjIds.add(SrLinkAttributesParser.parseLanAdjacencySegmentIdentifier(value, protocolId)); LOG.debug("Parsed Adjacency Segment Identifier :{}", srLanAdjIds.get(srLanAdjIds.size() - 1)); break; case PEER_NODE_SID_CODE: builder.setPeerNodeSid( new PeerNodeSidBuilder(SrLinkAttributesParser.parseAdjacencySegmentIdentifier(value, null)) .build()); LOG.debug("Parsed Peer Segment Identifier :{}", builder.getPeerNodeSid()); break; case PEER_ADJ_SID_CODE: builder.setPeerAdjSid( new PeerAdjSidBuilder(SrLinkAttributesParser.parseAdjacencySegmentIdentifier(value, null)) .build()); LOG.debug("Parsed Peer Segment Identifier :{}", builder.getPeerAdjSid()); break; case PEER_SET_SID_CODE: peerSetSids.add( new PeerSetSidsBuilder(SrLinkAttributesParser.parseAdjacencySegmentIdentifier(value, null)) .build()); LOG.debug("Parsed Peer Set Sid :{}", peerSetSids.get(peerSetSids.size() - 1)); break; default: LOG.warn("TLV {} is not a valid link attribute, ignoring it", key); } } if (!srAdjIds.isEmpty()) { builder.setSrAdjIds(srAdjIds); } if (!srLanAdjIds.isEmpty()) { builder.setSrLanAdjIds(srLanAdjIds); } if (!peerSetSids.isEmpty()) { builder.setPeerSetSids(peerSetSids); } LOG.trace("Finished parsing Link Attributes."); return new LinkAttributesCaseBuilder().setLinkAttributes(builder.build()).build(); }
From source file:com.sun.tools.hat.internal.server.QueryHandler.java
/** * Returns a link to <code>/<var>path</var>/<var>pathInfo</var></code> * with the given label and parameters.//from w ww. ja va 2s . com * * @param path the static portion of the link target (should only * contain trusted text) * @param pathInfo the non-static portion of the link target (will be * URL-encoded) * @param label the link text to use * @param params any {@code GET} parameters to append to the link target * @return an HTML {@code <a>} tag formatted as described */ protected static String formatLink(String path, String pathInfo, String label, Multimap<String, String> params) { StringBuilder sb = new StringBuilder(); @SuppressWarnings("resource") // StringBuilder is not closeable Formatter fmt = new Formatter(sb); fmt.format("<a href='/%s/%s?", path, encodeForURL(Strings.nullToEmpty(pathInfo))); if (params != null) { for (Map.Entry<String, String> entry : params.entries()) { fmt.format("%s=%s&", encodeForURL(entry.getKey()), encodeForURL(entry.getValue())); } } sb.setLength(sb.length() - 1); fmt.format("'>%s</a>", Misc.encodeHtml(label)); return sb.toString(); }
From source file:org.streamingpool.ext.tensorics.streamfactory.DetailedTensoricsExpressionStreamFactory.java
private static Flowable<?> triggerObservable(Multimap<StreamId<?>, ? extends Flowable<?>> flowables, EvaluationStrategy strategy, DiscoveryService discoveryService) { if (strategy instanceof ContinuousEvaluation) { Collection<? extends Flowable<?>> streams = flowables.values(); if (streams.isEmpty()) { LOGGER.warn("The expression does not contain any streams. " + "Therefore it will never emit! This rarely might be what you want ;-)"); }/*w w w . ja v a 2s . co m*/ return Flowable.combineLatest(streams, TRIGGER_CONTEXT_COMBINER); } if (strategy instanceof BufferedEvaluation) { List<? extends Flowable<?>> triggeringObservables = flowables.entries().stream() .filter(e -> (e.getKey() instanceof OverlapBufferStreamId)).map(Entry::getValue) .collect(toList()); if (triggeringObservables.isEmpty()) { throw new NoBufferedStreamSpecifiedException(); } return zip(triggeringObservables, ImmutableSet::of); } if (strategy instanceof TriggeredEvaluation) { return fromPublisher(discoveryService.discover(((TriggeredEvaluation) strategy).triggeringStreamId())); } throw new IllegalArgumentException( "Unknown evaluationStrategy '" + strategy + "'. Cannot create trigger Observable."); }
From source file:org.jclouds.rest.internal.RestAnnotationProcessor.java
private static <K, V> Map<K, V> convertUnsafe(Multimap<K, V> in) { LinkedHashMap<K, V> out = Maps.newLinkedHashMap(); for (Entry<K, V> entry : in.entries()) { out.put(entry.getKey(), entry.getValue()); }/*from w w w . j a va 2 s . c om*/ return ImmutableMap.copyOf(out); }
From source file:com.liveramp.hank.storage.cueball.Cueball.java
public static DiskPartitionAssignment getDataDirectoryAssignments(DataDirectoriesConfigurator configurator, Collection<Integer> partitionNumbers) { ArrayList<String> sortedDataDirectories = new ArrayList<String>(configurator.getDataDirectories()); Collections.sort(sortedDataDirectories); LinkedList<Integer> sortedPartitions = new LinkedList<>(partitionNumbers); Collections.sort(sortedPartitions); // TODO we can make this dynamic based on disk size, but not urgent double numPartitionsPerDisk = (double) partitionNumbers.size() / sortedDataDirectories.size(); Multimap<String, Integer> partitionsPerDisk = HashMultimap.create(); for (String dataDirectory : sortedDataDirectories) { int numToAssign = (int) Math.ceil(numPartitionsPerDisk * (partitionsPerDisk.keySet().size() + 1)) - partitionsPerDisk.values().size(); for (int i = 0; i < numToAssign && !sortedPartitions.isEmpty(); i++) { partitionsPerDisk.put(dataDirectory, sortedPartitions.pop()); }//from w ww.j a va2s . com } Map<Integer, String> inverse = Maps.newHashMap(); for (Map.Entry<String, Integer> entry : partitionsPerDisk.entries()) { inverse.put(entry.getValue(), entry.getKey()); } return new DiskPartitionAssignment(inverse); }
From source file:org.ow2.proactive.scheduler.authentication.ManageUsers.java
/** * Stores the groups in group.cfg/*from w w w . ja v a 2s . c o m*/ */ private static void storeGroups(String groupFilePath, Multimap<String, String> groups) throws ManageUsersException { try { try (PrintWriter writer = new PrintWriter( new OutputStreamWriter(new FileOutputStream(groupFilePath)))) { for (Map.Entry<String, String> userEntry : groups.entries()) { writer.println(userEntry.getKey() + ":" + userEntry.getValue()); } } } catch (IOException e) { exitWithErrorMessage("could not write group file : " + groupFilePath, null, e); } System.out.println("Stored group file in " + groupFilePath); }