List of usage examples for com.google.common.collect Multimap keySet
Set<K> keySet();
From source file:com.arpnetworking.tsdcore.sinks.MonitordSink.java
/** * {@inheritDoc}//from w ww . ja v a2 s. com */ @Override protected Collection<byte[]> serialize(final PeriodicData periodicData) { final Period period = periodicData.getPeriod(); final Multimap<String, AggregatedData> indexedData = prepareData(periodicData); final Multimap<String, Condition> indexedConditions = prepareConditions(periodicData.getConditions()); // Serialize final List<byte[]> serializedData = Lists.newArrayListWithCapacity(indexedData.size()); final StringBuilder stringBuilder = new StringBuilder(); for (final String key : indexedData.keySet()) { final Collection<AggregatedData> namedData = indexedData.get(key); if (!namedData.isEmpty()) { stringBuilder.setLength(0); final AggregatedData first = Iterables.getFirst(namedData, null); final String name = new StringBuilder().append(first.getFQDSN().getService()).append("_") .append(period.toString(ISOPeriodFormat.standard())).append("_") .append(first.getFQDSN().getMetric()).toString(); int maxStatus = 0; final StringBuilder dataBuilder = new StringBuilder(); for (final AggregatedData datum : namedData) { if (!datum.isSpecified()) { continue; } dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("%3D") .append(datum.getValue().getValue()).append("%3B"); final String conditionKey = datum.getFQDSN().getService() + "_" + datum.getFQDSN().getMetric() + "_" + datum.getFQDSN().getCluster() + "_" + datum.getFQDSN().getStatistic(); for (final Condition condition : indexedConditions.get(conditionKey)) { dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("_") .append(condition.getName()).append("%3D") .append(condition.getThreshold().getValue()).append("%3B"); if (condition.isTriggered().isPresent() && condition.isTriggered().get()) { // Collect the status of this metric final Object severity = condition.getExtensions().get("severity"); int status = _unknownSeverityStatus; if (severity != null && _severityToStatus.containsKey(severity)) { status = _severityToStatus.get(severity); } maxStatus = Math.max(status, maxStatus); } } } // Don't send an empty payload if (dataBuilder.length() == 0) { continue; } stringBuilder.append("run_every=").append(period.toStandardSeconds().getSeconds()).append("&path=") .append(first.getFQDSN().getCluster()).append("%2f") .append(periodicData.getDimensions().get("host")).append("&monitor=").append(name) .append("&status=").append(maxStatus).append("×tamp=") .append((int) Unit.SECOND.convert(periodicData.getStart().getMillis(), Unit.MILLISECOND)) .append("&output=").append(name).append("%7C").append(dataBuilder.toString()); stringBuilder.setLength(stringBuilder.length() - 3); serializedData.add(stringBuilder.toString().getBytes(Charset.forName("UTF-8"))); } } return serializedData; }
From source file:org.nuxeo.ecm.platform.groups.audit.service.acl.AclExcelLayoutBuilder.java
/** * Render local AND inherited ACL.//from www . j a v a 2s . c o m * <ul> * <li>Local acl only are rendered with default font. * <li>Inherited acl only are rendered with gray font. * <li>Mixed acl (local and inherited) are rendered with default font. * </ul> */ protected void renderAcl(Multimap<String, Pair<String, Boolean>> localAcls, Multimap<String, Pair<String, Boolean>> inheritedAcls) throws ClientException { Set<String> users = new HashSet<String>(); users.addAll(localAcls.keySet()); users.addAll(inheritedAcls.keySet()); for (String user : users) { int column = layout.getUserColumn(user); String localAclsString = formatAcl(localAcls.get(user)); String inheritedAclsString = formatAcl(inheritedAcls.get(user)); if ("".equals(localAclsString) && "".equals(inheritedAclsString)) { } else if (!"".equals(localAclsString) && !"".equals(inheritedAclsString)) { String info = localAclsString + "," + inheritedAclsString; excel.setCell(treeLineCursor, column, info); } else if (!"".equals(localAclsString) && "".equals(inheritedAclsString)) { String info = localAclsString; excel.setCell(treeLineCursor, column, info); } else if ("".equals(localAclsString) && !"".equals(inheritedAclsString)) { String info = inheritedAclsString; excel.setCell(treeLineCursor, column, info, grayTextStyle); } } }
From source file:com.btoddb.chronicle.Chronicle.java
/** * Should be called by a {@link Catcher} after receiving events. * * @param catcherId ID of the catcher for reporting and routing * @param events list of {@link Event}s//from ww w .ja va 2s . c o m */ public void handleCatcher(String catcherId, Collection<Event> events) { Multimap<PlunkerRunner, Event> routingMap = LinkedListMultimap.create(); // divide events by route for (Event event : events) { for (Router router : config.getRouters().values()) { PlunkerRunner runner; if (null != (runner = router.canRoute(catcherId, event))) { routingMap.put(runner, event); } } } if (!routingMap.isEmpty()) { for (PlunkerRunner runner : routingMap.keySet()) { try { runner.run(routingMap.get(runner)); } catch (Exception e) { Utils.logAndThrow(logger, String.format("exception while handle events from catcher, %s", catcherId), e); } } } else { config.getErrorHandler().handle(events); } }
From source file:edu.isi.karma.modeling.alignment.learner.SteinerNodes.java
private void computeCoherenceList() { if (nodes == null || nodes.size() == 0) return;//from w ww . j a v a2 s . c o m Map<String, Integer> patternSize = new HashMap<String, Integer>(); Map<String, String> patternGuid = new HashMap<String, String>(); int guidSize = new RandomGUID().toString().length(); for (Node n : nodes) { for (String p : n.getModelIds()) { Integer size = patternSize.get(p); if (size == null) patternSize.put(p, 1); else patternSize.put(p, ++size); if (!patternGuid.containsKey(p)) { String guid = new RandomGUID().toString(); patternGuid.put(p, guid); } } } // find the maximum pattern size int maxPatternSize = 0; for (Entry<String, Integer> entry : patternSize.entrySet()) { if (entry.getValue().intValue() > maxPatternSize) maxPatternSize = entry.getValue().intValue(); } List<String> listOfNodesLargestPatterns = new ArrayList<String>(); for (Node n : nodes) { List<String> patternIds = new ArrayList<String>(n.getModelIds()); Collections.sort(patternIds); String[] nodeMaxPatterns = new String[maxPatternSize]; Arrays.fill(nodeMaxPatterns, ""); for (String p : patternIds) { int size = patternSize.get(p).intValue(); nodeMaxPatterns[size - 1] += patternGuid.get(p); } for (int i = maxPatternSize - 1; i >= 0; i--) { if (nodeMaxPatterns[i] != null && nodeMaxPatterns[i].trim().length() > 0) { listOfNodesLargestPatterns.add(nodeMaxPatterns[i]); break; } } } Function<String, String> stringEqualiy = new Function<String, String>() { @Override public String apply(final String s) { return s; } }; Multimap<String, String> index = Multimaps.index(listOfNodesLargestPatterns, stringEqualiy); this.coherenceList.clear(); int x, y; for (String s : index.keySet()) { if (s.trim().length() == 0) continue; x = index.get(s).size(); y = x > 0 ? index.get(s).iterator().next().length() / guidSize : 0; CoherenceItem ci = new CoherenceItem(x, y); this.coherenceList.add(ci); } Collections.sort(this.coherenceList); }
From source file:com.arpnetworking.tsdcore.sinks.KMonDSink.java
/** * {@inheritDoc}//w w w . j a va 2s. c om */ @Override protected Collection<byte[]> serialize(final PeriodicData periodicData) { final Period period = periodicData.getPeriod(); final Multimap<String, AggregatedData> indexedData = prepareData(periodicData); final Multimap<String, Condition> indexedConditions = prepareConditions(periodicData.getConditions()); // Serialize final List<byte[]> serializedData = Lists.newArrayListWithCapacity(indexedData.size()); final StringBuilder stringBuilder = new StringBuilder(); for (final String key : indexedData.keySet()) { final Collection<AggregatedData> namedData = indexedData.get(key); if (!namedData.isEmpty()) { stringBuilder.setLength(0); final AggregatedData first = Iterables.getFirst(namedData, null); final String name = new StringBuilder().append(first.getFQDSN().getService()).append("_") .append(period.toString(ISOPeriodFormat.standard())).append("_") .append(first.getFQDSN().getMetric()).toString(); int maxStatus = 0; boolean hasAlert = false; final StringBuilder dataBuilder = new StringBuilder(); for (final AggregatedData datum : namedData) { if (!datum.isSpecified()) { continue; } dataBuilder.append(datum.getFQDSN().getStatistic().getName()).append("%3D") .append(datum.getValue().getValue()).append("%3B"); final String conditionKey = datum.getFQDSN().getService() + "_" + datum.getFQDSN().getMetric() + "_" + datum.getFQDSN().getCluster() + "_" + datum.getFQDSN().getStatistic(); for (final Condition condition : indexedConditions.get(conditionKey)) { hasAlert = true; maxStatus = serializeCondition(maxStatus, dataBuilder, datum, condition); } } // Don't send an empty payload if (dataBuilder.length() == 0) { continue; } stringBuilder.append("run_every=").append(period.toStandardSeconds().getSeconds()) .append("&has_alert=").append(hasAlert).append("&path=") .append(first.getFQDSN().getCluster()).append("%2f") .append(periodicData.getDimensions().get("host")).append("&monitor=").append(name) .append("&status=").append(maxStatus).append("×tamp=") .append((int) Unit.SECOND.convert(periodicData.getStart().getMillis(), Unit.MILLISECOND)) .append("&output=").append(name).append("%7C").append(dataBuilder.toString()); stringBuilder.setLength(stringBuilder.length() - 3); serializedData.add(stringBuilder.toString().getBytes(Charset.forName("UTF-8"))); } } return serializedData; }
From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraVerifier.java
protected static void sanityCheckRingConsistency(Set<InetSocketAddress> currentAddrs, String keyspace, boolean isSsl, boolean safetyDisabled, int socketTimeoutMillis, int socketQueryTimeoutMillis) { Multimap<Set<TokenRange>, InetSocketAddress> tokenRangesToHost = HashMultimap.create(); for (InetSocketAddress addr : currentAddrs) { Cassandra.Client client = null;/*w w w . j ava2 s .c o m*/ try { client = CassandraClientFactory.getClientInternal(addr, isSsl, socketTimeoutMillis, socketQueryTimeoutMillis); try { client.describe_keyspace(keyspace); } catch (NotFoundException e) { log.info( "Tried to check ring consistency for node {} before keyspace was fully setup; aborting check for now.", addr, e); return; } tokenRangesToHost.put(ImmutableSet.copyOf(client.describe_ring(keyspace)), addr); } catch (Exception e) { log.warn("failed to get ring info from host: {}", addr, e); } finally { if (client != null) { client.getOutputProtocol().getTransport().close(); } } } if (tokenRangesToHost.isEmpty()) { log.error( "Failed to get ring info for entire Cassandra cluster ({}); ring could not be checked for consistency.", keyspace); return; } if (tokenRangesToHost.keySet().size() == 1) { return; } RuntimeException e = new IllegalStateException( "Hosts have differing ring descriptions. This can lead to inconsistent reads and lost data. "); log.error("QA-86204 " + e.getMessage() + tokenRangesToHost, e); if (tokenRangesToHost.size() > 2) { for (Entry<Set<TokenRange>, Collection<InetSocketAddress>> entry : tokenRangesToHost.asMap() .entrySet()) { if (entry.getValue().size() == 1) { log.error("Host: " + entry.getValue().iterator().next() + " disagrees with the other nodes about the ring state."); } } } if (tokenRangesToHost.keySet().size() == 2) { ImmutableList<Set<TokenRange>> sets = ImmutableList.copyOf(tokenRangesToHost.keySet()); Set<TokenRange> set1 = sets.get(0); Set<TokenRange> set2 = sets.get(1); log.error("Hosts are split. group1: " + tokenRangesToHost.get(set1) + " group2: " + tokenRangesToHost.get(set2)); } logErrorOrThrow(e.getMessage(), safetyDisabled); }
From source file:org.apache.drill.exec.memory.AccountorImpl.java
public void close() { // remove the fragment context and reset fragment limits whenever an allocator closes if (parent != null && parent.parent == null && limitConsumer != null) { logger.debug("Fragment " + limitConsumer.getIdentifier() + " accountor being closed"); removeLimitConsumer(limitConsumer); }//from w w w.j av a2 s . c o m resetFragmentLimits(); if (ENABLE_ACCOUNTING && !buffers.isEmpty()) { StringBuffer sb = new StringBuffer(); sb.append("Attempted to close accountor with "); sb.append(buffers.size()); sb.append(" buffer(s) still allocated for "); sb.append(limitConsumer.getIdentifier()); sb.append(".\n"); Multimap<DebugStackTrace, DebugStackTrace> multi = LinkedListMultimap.create(); for (DebugStackTrace t : buffers.values()) { multi.put(t, t); } for (DebugStackTrace entry : multi.keySet()) { Collection<DebugStackTrace> allocs = multi.get(entry); sb.append("\n\n\tTotal "); sb.append(allocs.size()); sb.append(" allocation(s) of byte size(s): "); for (DebugStackTrace alloc : allocs) { sb.append(alloc.size); sb.append(", "); } sb.append("at stack location:\n"); entry.addToString(sb); } if (!buffers.isEmpty()) { IllegalStateException e = new IllegalStateException(sb.toString()); if (errorOnLeak) { throw e; } else { logger.warn("Memory leaked.", e); } } } remainder.close(); }
From source file:org.jetbrains.kotlin.resolve.DeclarationResolver.java
private void checkRedeclarationsInPackages(@NotNull TopDownAnalysisContext c) { for (MutablePackageFragmentDescriptor packageFragment : Sets.newHashSet(c.getPackageFragments().values())) { PackageViewDescriptor packageView = packageFragment.getContainingDeclaration() .getPackage(packageFragment.getFqName()); JetScope packageViewScope = packageView.getMemberScope(); Multimap<Name, DeclarationDescriptor> simpleNameDescriptors = packageFragment.getMemberScope() .getDeclaredDescriptorsAccessibleBySimpleName(); for (Name name : simpleNameDescriptors.keySet()) { // Keep only properties with no receiver Collection<DeclarationDescriptor> descriptors = Collections2.filter(simpleNameDescriptors.get(name), new Predicate<DeclarationDescriptor>() { @Override public boolean apply(@Nullable DeclarationDescriptor descriptor) { if (descriptor instanceof PropertyDescriptor) { PropertyDescriptor propertyDescriptor = (PropertyDescriptor) descriptor; return propertyDescriptor.getExtensionReceiverParameter() == null; }/*from www . j av a2s .c om*/ return true; } }); ContainerUtil.addIfNotNull(descriptors, packageViewScope.getPackage(name)); if (descriptors.size() > 1) { for (DeclarationDescriptor declarationDescriptor : descriptors) { for (PsiElement declaration : getDeclarationsByDescriptor(declarationDescriptor)) { assert declaration != null : "Null declaration for descriptor: " + declarationDescriptor + " " + (declarationDescriptor != null ? DescriptorRenderer.FQ_NAMES_IN_TYPES.render(declarationDescriptor) : ""); trace.report(REDECLARATION.on(declaration, declarationDescriptor.getName().asString())); } } } } } }
From source file:org.xacml4j.v30.pdp.DefaultPolicyDecisionPoint.java
/** * Gets all attributes from an {@link EvaluationContext} which were resolved * and not present in the original access decision request * * @param context an evaluation context/*www.j a v a2 s.co m*/ * @return a collection of {@link Attribute} instances */ private Collection<Category> getResolvedAttributes(EvaluationContext context) { Map<AttributeDesignatorKey, BagOfAttributeExp> desig = context.getResolvedDesignators(); Multimap<CategoryId, Attribute> attributes = HashMultimap.create(); for (AttributeDesignatorKey k : desig.keySet()) { BagOfAttributeExp v = desig.get(k); Collection<Attribute> values = attributes.get(k.getCategory()); values.add(Attribute.builder(k.getAttributeId()).issuer(k.getIssuer()).values(v.values()).build()); } Collection<Category> result = new LinkedList<Category>(); for (CategoryId c : attributes.keySet()) { result.add(Category.builder(c).entity(Entity.builder().attributes(attributes.get(c)).build()).build()); } return result; }
From source file:org.eclipse.elk.alg.layered.compound.CompoundGraphPostprocessor.java
/** * {@inheritDoc}/* www . j a v a 2s .c om*/ */ public void process(final LGraph graph, final IElkProgressMonitor monitor) { monitor.begin("Compound graph postprocessor", 1); // whether bend points should be added whenever crossing a hierarchy boundary boolean addUnnecessaryBendpoints = graph.getProperty(LayeredOptions.UNNECESSARY_BENDPOINTS); // restore the cross-hierarchy map that was built by the preprocessor Multimap<LEdge, CrossHierarchyEdge> crossHierarchyMap = graph .getProperty(InternalProperties.CROSS_HIERARCHY_MAP); // remember all dummy edges we encounter; these need to be removed at the end Set<LEdge> dummyEdges = Sets.newHashSet(); // iterate over all original edges for (LEdge origEdge : crossHierarchyMap.keySet()) { List<CrossHierarchyEdge> crossHierarchyEdges = new ArrayList<CrossHierarchyEdge>( crossHierarchyMap.get(origEdge)); // put the cross-hierarchy edges in proper order from source to target Collections.sort(crossHierarchyEdges, new CrossHierarchyEdgeComparator(graph)); LPort sourcePort = crossHierarchyEdges.get(0).getActualSource(); LPort targetPort = crossHierarchyEdges.get(crossHierarchyEdges.size() - 1).getActualTarget(); origEdge.getBendPoints().clear(); // determine the reference graph for all bend points LNode referenceNode = sourcePort.getNode(); LGraph referenceGraph; if (LGraphUtil.isDescendant(targetPort.getNode(), referenceNode)) { referenceGraph = referenceNode.getProperty(InternalProperties.NESTED_LGRAPH); } else { referenceGraph = referenceNode.getGraph(); } // check whether there are any junction points KVectorChain junctionPoints = origEdge.getProperty(LayeredOptions.JUNCTION_POINTS); if (Iterables.any(crossHierarchyEdges, HAS_JUNCTION_POINTS_PREDICATE)) { // if so, make sure the original edge has an empty non-null junction point list if (junctionPoints == null) { junctionPoints = new KVectorChain(); origEdge.setProperty(LayeredOptions.JUNCTION_POINTS, junctionPoints); } else { junctionPoints.clear(); } } else if (junctionPoints != null) { origEdge.setProperty(LayeredOptions.JUNCTION_POINTS, null); } // apply the computed layouts to the cross-hierarchy edge KVector lastPoint = null; for (CrossHierarchyEdge chEdge : crossHierarchyEdges) { // transform all coordinates from the graph of the dummy edge to the reference graph KVector offset = new KVector(); LGraphUtil.changeCoordSystem(offset, chEdge.getGraph(), referenceGraph); LEdge ledge = chEdge.getEdge(); KVectorChain bendPoints = new KVectorChain(); bendPoints.addAllAsCopies(0, ledge.getBendPoints()); bendPoints.offset(offset); // Note: if an NPE occurs here, that means KLay Layered has replaced the original edge KVector sourcePoint = new KVector(ledge.getSource().getAbsoluteAnchor()); KVector targetPoint = new KVector(ledge.getTarget().getAbsoluteAnchor()); sourcePoint.add(offset); targetPoint.add(offset); if (lastPoint != null) { KVector nextPoint; if (bendPoints.isEmpty()) { nextPoint = targetPoint; } else { nextPoint = bendPoints.getFirst(); } // we add the source point as a bend point to properly connect the hierarchy levels // either if the last point of the previous hierarchy edge segment is a certain // level of tolerance away or if we are required to add unnecessary bend points boolean xDiffEnough = Math .abs(lastPoint.x - nextPoint.x) > OrthogonalRoutingGenerator.TOLERANCE; boolean yDiffEnough = Math .abs(lastPoint.y - nextPoint.y) > OrthogonalRoutingGenerator.TOLERANCE; if ((!addUnnecessaryBendpoints && xDiffEnough && yDiffEnough) || (addUnnecessaryBendpoints && (xDiffEnough || yDiffEnough))) { origEdge.getBendPoints().add(sourcePoint); } } origEdge.getBendPoints().addAll(bendPoints); if (bendPoints.isEmpty()) { lastPoint = sourcePoint; } else { lastPoint = bendPoints.getLast(); } // copy junction points KVectorChain ledgeJPs = ledge.getProperty(LayeredOptions.JUNCTION_POINTS); if (ledgeJPs != null) { KVectorChain jpCopies = new KVectorChain(); jpCopies.addAllAsCopies(0, ledgeJPs); jpCopies.offset(offset); junctionPoints.addAll(jpCopies); } // add offset to target port with a special property if (chEdge.getActualTarget() == targetPort) { if (targetPort.getNode().getGraph() != chEdge.getGraph()) { // the target port is in a different coordinate system -- recompute the offset offset = new KVector(); LGraphUtil.changeCoordSystem(offset, targetPort.getNode().getGraph(), referenceGraph); } origEdge.setProperty(InternalProperties.TARGET_OFFSET, offset); } // copy labels back to the original edge Iterator<LLabel> labelIterator = ledge.getLabels().listIterator(); while (labelIterator.hasNext()) { LLabel currLabel = labelIterator.next(); if (currLabel.getProperty(InternalProperties.ORIGINAL_LABEL_EDGE) != origEdge) { continue; } LGraphUtil.changeCoordSystem(currLabel.getPosition(), ledge.getSource().getNode().getGraph(), referenceGraph); labelIterator.remove(); origEdge.getLabels().add(currLabel); } // remember the dummy edge for later removal (dummy edges may be in use by several // different original edges, which is why we cannot just go and remove it now) dummyEdges.add(ledge); } // restore the original source port and target port origEdge.setSource(sourcePort); origEdge.setTarget(targetPort); } // remove the dummy edges from the graph (dummy ports and dummy nodes are retained) for (LEdge dummyEdge : dummyEdges) { dummyEdge.setSource(null); dummyEdge.setTarget(null); } monitor.done(); }