List of usage examples for com.google.common.collect Multimap size
int size();
From source file:com.arpnetworking.tsdcore.sinks.KMonDSink.java
/** * {@inheritDoc}/*from w ww .ja v a 2 s. c o m*/ */ @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:org.sosy_lab.cpachecker.cpa.value.refiner.ValueAnalysisConcreteErrorPathAllocator.java
private Map<LeftHandSide, Address> generateVariableAddresses( Multimap<IDExpression, MemoryLocation> pMemoryLocationsInPath) { Map<LeftHandSide, Address> result = Maps.newHashMapWithExpectedSize(pMemoryLocationsInPath.size()); // Start with Address 0 Address nextAddressToBeAssigned = Address.valueOf(BigInteger.ZERO); for (IDExpression variable : pMemoryLocationsInPath.keySet()) { result.put(variable, nextAddressToBeAssigned); // leave enough space for values between addresses nextAddressToBeAssigned = generateNextAddresses(pMemoryLocationsInPath.get(variable), nextAddressToBeAssigned); }/*from w ww . ja v a2 s . co m*/ return result; }
From source file:org.apache.cassandra.service.StorageProxy.java
/*** * /*from w w w .j av a2 s . co m*/ * @param rm * @param hintedEndpoints * @param responseHandler * @param localDataCenter * @param insertLocalMessages * @param consistency_level * @throws IOException */ //write1.0insertLocalhintedEndpointsby Hycz private static void sendToHintedEndpoints(final RowMutation rm, Multimap<InetAddress, InetAddress> hintedEndpoints, IWriteResponseHandler responseHandler, String localDataCenter, boolean insertLocalMessages, ConsistencyLevel consistency_level) throws IOException { // Multimap that holds onto all the messages and addresses meant for a specific datacenter Map<String, Multimap<Message, InetAddress>> dcMessages = new HashMap<String, Multimap<Message, InetAddress>>( hintedEndpoints.size()); MessageProducer producer = new CachingMessageProducer(rm); for (Map.Entry<InetAddress, Collection<InetAddress>> entry : hintedEndpoints.asMap().entrySet()) { InetAddress destination = entry.getKey(); Collection<InetAddress> targets = entry.getValue(); String dc = DatabaseDescriptor.getEndpointSnitch().getDatacenter(destination); if (targets.size() == 1 && targets.iterator().next().equals(destination)) { // // unhinted writes if (destination.equals(FBUtilities.getLocalAddress())) { if (insertLocalMessages) insertLocal(rm, responseHandler); } // else { // belongs on a different server if (logger.isDebugEnabled()) logger.debug( "insert writing key " + ByteBufferUtil.bytesToHex(rm.key()) + " to " + destination); Multimap<Message, InetAddress> messages = dcMessages.get(dc); if (messages == null) { messages = HashMultimap.create(); dcMessages.put(dc, messages); } messages.put(producer.getMessage(Gossiper.instance.getVersion(destination)), destination); } } // hint else { // hinted messages are unique, so there is no point to adding a hop by forwarding via another node. // thus, we use sendRR/sendOneWay directly here. Message hintedMessage = rm.getMessage(Gossiper.instance.getVersion(destination)); for (InetAddress target : targets) { if (!target.equals(destination)) { addHintHeader(hintedMessage, target); if (logger.isDebugEnabled()) logger.debug("insert writing key " + ByteBufferUtil.bytesToHex(rm.key()) + " to " + destination + " for " + target); } } // non-destination hints are part of the callback and count towards consistency only under CL.ANY if (targets.contains(destination) || consistency_level == ConsistencyLevel.ANY) MessagingService.instance().sendRR(hintedMessage, destination, responseHandler); else MessagingService.instance().sendOneWay(hintedMessage, destination); } } // sendMessages(localDataCenter, dcMessages, responseHandler); }
From source file:org.jclouds.compute.stub.extensions.StubSecurityGroupExtension.java
@Override public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort, Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> ipRanges, Iterable<String> groupIds, SecurityGroup group) {/*from www . ja v a 2 s .c om*/ IpPermission.Builder ipBuilder = IpPermission.builder(); ipBuilder.ipProtocol(protocol); ipBuilder.fromPort(startPort); ipBuilder.toPort(endPort); if (tenantIdGroupNamePairs.size() > 0) { ipBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs); } if (Iterables.size(ipRanges) > 0) { ipBuilder.cidrBlocks(ipRanges); } if (Iterables.size(groupIds) > 0) { ipBuilder.groupIds(groupIds); } IpPermission perm = ipBuilder.build(); SecurityGroupBuilder builder = SecurityGroupBuilder.fromSecurityGroup(checkNotNull(group, "group")); builder.ipPermission(perm); SecurityGroup newGroup = builder.build(); if (groups.containsKey(newGroup.getId())) { groups.remove(newGroup.getId()); } groups.put(newGroup.getId(), newGroup); return newGroup; }
From source file:org.jclouds.compute.stub.extensions.StubSecurityGroupExtension.java
@Override public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort, Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> ipRanges, Iterable<String> groupIds, SecurityGroup group) {/*from www . java 2 s.c o m*/ IpPermission.Builder ipBuilder = IpPermission.builder(); ipBuilder.ipProtocol(protocol); ipBuilder.fromPort(startPort); ipBuilder.toPort(endPort); if (tenantIdGroupNamePairs.size() > 0) { ipBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs); } if (Iterables.size(ipRanges) > 0) { ipBuilder.cidrBlocks(ipRanges); } if (Iterables.size(groupIds) > 0) { ipBuilder.groupIds(groupIds); } IpPermission perm = ipBuilder.build(); SecurityGroupBuilder builder = SecurityGroupBuilder.fromSecurityGroup(checkNotNull(group, "group")); builder.ipPermissions(); builder.ipPermissions(filter(group.getIpPermissions(), not(equalTo(perm)))); SecurityGroup newGroup = builder.build(); if (groups.containsKey(newGroup.getId())) { groups.remove(newGroup.getId()); } groups.put(newGroup.getId(), newGroup); return newGroup; }
From source file:org.eclipse.xtext.serializer.sequencer.ContextFinder.java
@Override public Set<ISerializationContext> findByContents(EObject semanticObject, Iterable<ISerializationContext> contextCandidates) { if (semanticObject == null) throw new NullPointerException(); initConstraints();/* ww w . j av a2 s . co m*/ Multimap<IConstraint, ISerializationContext> constraints; if (contextCandidates != null) constraints = getConstraints(semanticObject, contextCandidates); else constraints = getConstraints(semanticObject); if (constraints.size() < 2) return Sets.newLinkedHashSet(constraints.values()); for (IConstraint cand : Lists.newArrayList(constraints.keySet())) if (!isValidValueQuantity(cand, semanticObject)) constraints.removeAll(cand); if (constraints.size() < 2) return Sets.newLinkedHashSet(constraints.values()); LinkedHashSet<ISerializationContext> result = Sets.newLinkedHashSet(constraints.values()); for (EStructuralFeature feat : semanticObject.eClass().getEAllStructuralFeatures()) { if (transientValueUtil.isTransient(semanticObject, feat) != ValueTransient.NO) continue; if (feat.isMany() && ((List<?>) semanticObject.eGet(feat)).isEmpty()) continue; Multimap<AbstractElement, ISerializationContext> assignments = collectAssignments(constraints, feat); Set<AbstractElement> assignedElements = findAssignedElements(semanticObject, feat, assignments); Set<ISerializationContext> keep = Sets.newHashSet(); for (AbstractElement ele : assignedElements) keep.addAll(assignments.get(ele)); result.retainAll(keep); } return result; }
From source file:steps.squash.BookingSteps.java
public BookingSteps(CourtAndTimeSlotChooserPage courtAndTimeSlotChooserPage, ErrorPage errorPage, CourtReservationPage courtReservationPage, BookingSet bookings) { this.courtAndTimeSlotChooserPage = courtAndTimeSlotChooserPage; this.errorPage = errorPage; this.courtReservationPage = courtReservationPage; bookingsPotentiallyMadeDuringScenario = bookings; Then("^court start times should be every (\\d{2}) minutes between (\\d{1,2}(?::\\d{2})? (?:AM|PM)) and (\\d{1,2}(?::\\d{2})? (?:AM|PM)) inclusive$", (String intervalMinutes, String tFirstS, String tLastS) -> { java.time.LocalTime tFirst = new StepArgumentTransforms.LocalTimeConverter().transform(tFirstS); java.time.LocalTime tLast = new StepArgumentTransforms.LocalTimeConverter().transform(tLastS); assertTrue("Expect bookings page to be loaded before calling this method", this.courtAndTimeSlotChooserPage.isLoaded()); List<java.time.LocalTime> startTimes = this.courtAndTimeSlotChooserPage .getAllPossibleBookingStartTimes(); // Check first start time assertTrue("Expected first start time to be at " + tFirst.toString() + " but got: " + startTimes.get(0), startTimes.get(0).toString().equals(tFirst.toString())); // Check each subsequent start time is <intervalMinutes> later Iterator<java.time.LocalTime> it = startTimes.iterator(); java.time.LocalTime previousTime = it.next(); while (it.hasNext()) { java.time.LocalTime currentTime = it.next(); assertTrue(//from ww w .j ava 2 s. c om "Court start times should be " + intervalMinutes + " minutes apart. Previous time: " + previousTime.toString() + " Next time: " + currentTime.toString(), previousTime.plusMinutes(Integer.parseInt(intervalMinutes)).equals(currentTime)); previousTime = currentTime; } // Check last start time assertTrue( "Expected last start time to be at " + tLast.toString() + " but got: " + startTimes.get(startTimes.size() - 1), startTimes.get(startTimes.size() - 1).toString().equals(tLast.toString())); }); Given("^I have viewed bookings for today$", () -> { viewBookingsForDate(java.time.LocalDate.now()); }); When("^I view bookings for today$", () -> { viewBookingsForDate(java.time.LocalDate.now()); }); When("^I attempt to view bookings for the (earliest|most future) date$", (String earliestOrLatest) -> { List<LocalDate> bookingDates = this.courtAndTimeSlotChooserPage.getAllPossibleBookingDates(); viewBookingsForDate(earliestOrLatest.equals("earliest") ? bookingDates.get(0) : bookingDates.get(bookingDates.size() - 1)); }); When("^I attempt to view bookings for a date (\\d+) days in the future$", (Integer daysAhead) -> { viewBookingsForDate(java.time.LocalDate.now().plusDays(daysAhead)); }); When("^I attempt to view bookings for a date (\\d+) day(?:s)? in the past$", (Integer daysAgo) -> { viewBookingsForDate(java.time.LocalDate.now().minusDays(daysAgo)); }); When("^I (attempt to |)book court (\\d) at (\\d{1,2}:\\d{1,2} (?:AM|PM)) today using password (.*)$", (String attemptOrNot, Integer court, String timeS, String password) -> { java.time.LocalTime time = new StepArgumentTransforms.LocalTimeConverter().transform(timeS); attemptToBookCourt(court, time, java.time.LocalDate.now(), "A.Shabana/J.Power", password, attemptOrNot.equals("attempt to ") ? false : true); }); When("^I (attempt to |)book court (\\d) at (\\d{1,2}:\\d{1,2} (?:AM|PM)) today for (.*)$", (String attemptOrNot, Integer court, String timeS, String name) -> { java.time.LocalTime time = new StepArgumentTransforms.LocalTimeConverter().transform(timeS); attemptToBookCourt(court, time, java.time.LocalDate.now(), name, "pAssw0rd", attemptOrNot.equals("attempt to ") ? false : true); }); Given("^I have booked court (\\d) at (\\d{1,2}:\\d{1,2} (?:AM|PM)) today$", (Integer court, String timeS) -> { java.time.LocalTime time = new StepArgumentTransforms.LocalTimeConverter().transform(timeS); attemptToBookCourt(court, time, java.time.LocalDate.now(), "A.Shabana/J.Power", "pAssw0rd", true); }); When("^I book court (\\d) at (\\d{1,2}:\\d{1,2} (?:AM|PM))( today|)$", (Integer court, String timeS, String todayOrNot) -> { java.time.LocalTime time = new StepArgumentTransforms.LocalTimeConverter().transform(timeS); attemptToBookCourt(court, time, todayOrNot.equals(" today") ? java.time.LocalDate.now() : this.courtAndTimeSlotChooserPage.getDate(), "A.Shabana/J.Power", "pAssw0rd", true); }); Then("^court (\\d) (should(?:| not)?) be booked at (\\d{1,2}:\\d{1,2} (?:AM|PM))( today|)$", (Integer court, String shouldOrNot, String timeS, String todayOrNot) -> { java.time.LocalTime time = new StepArgumentTransforms.LocalTimeConverter().transform(timeS); assertCourtBooked(court, time, todayOrNot.equals(" today") ? java.time.LocalDate.now() : this.courtAndTimeSlotChooserPage.getDate(), shouldOrNot); }); Then("^there should be (\\d{1,2}) booked court(?:s)?(?: today)?$", (Integer numBookedCourts) -> { LocalDate date = java.time.LocalDate.now(); if (!this.courtAndTimeSlotChooserPage.getDate().equals(date)) { System.out.println("Dates unequal - so selecting date"); this.courtAndTimeSlotChooserPage.selectDate(date); } Multimap<Integer, java.time.LocalTime> bookedTimes = this.courtAndTimeSlotChooserPage .getBookedStartTimes(); assertTrue("Expected " + numBookedCourts.toString() + " booked courts, got " + bookedTimes.size() + " booked courts", (bookedTimes.size() == numBookedCourts)); }); Then("^I should be shown bookings for a date (\\d+) days in the future$", this::assertBookingsShownFor); Then("^I should be taken to the (squash booking page|error page)$", (String pageName) -> { // Assert the expected page is loaded if (pageName.equals("squash booking page")) { assertTrue("Squash booking page should be fully loaded", this.courtAndTimeSlotChooserPage.isLoaded()); } else { // HtmlUnit redirects immediately from the error page. String webDriverType = System.getProperty("WebDriverType"); if (!webDriverType.equals("HtmlUnit")) { assertTrue("Squash error page should be fully loaded", this.errorPage.isLoaded()); } } }); Then("^I should be shown bookings for today$", this::assertBookingsShownForToday); Then("^I should receive feedback that the booking details were invalid$", () -> { assertTrue("Expected to have received feedback that the booking details were invalid", this.courtReservationPage.hasReceivedFeedbackOnInvalidBookingDetails()); }); }
From source file:org.waveprotocol.wave.examples.fedone.waveserver.CertificateManagerImpl.java
/** * Dequeue all signer info requests for a given signer id and a specific domain. * * @param signerId to dequeue requests for * @param error if there was an error, null for success * @param domain to dequeue the signer requests for *//* ww w .j ava 2 s.co m*/ private synchronized void dequeueSignerInfoRequestForDomain(ByteString signerId, FederationError error, String domain) { Multimap<String, SignerInfoPrefetchResultListener> domainListeners = signerInfoRequests.get(signerId); if (domainListeners == null) { LOG.info("There are no domain listeners for signer " + signerId + " domain " + domain); return; } else { LOG.info("Dequeuing " + domainListeners.size() + " listeners for domain " + domain); } for (SignerInfoPrefetchResultListener listener : domainListeners.get(domain)) { if (error == null) { listener.onSuccess(retrieveSignerInfo(signerId)); } else { listener.onFailure(error); } } domainListeners.removeAll(domain); if (domainListeners.isEmpty()) { // No listeners for any domains, delete the signer id for the overall map signerInfoRequests.remove(signerId); } }
From source file:com.zimbra.cs.db.DbBlobConsistency.java
public static int getNumRows(DbConnection conn, Mailbox mbox, String tableName, String idColName, Multimap<Integer, Integer> idRevs) throws ServiceException { Set<Integer> mail_itemIds = new HashSet<Integer>(); Multimap<Integer, Integer> rev_itemIds = HashMultimap.create(); for (Integer itemId : idRevs.keySet()) { Collection<Integer> revs = idRevs.get(itemId); for (int rev : revs) { if (rev == 0) { mail_itemIds.add(itemId); } else { rev_itemIds.put(itemId, rev); }/*www .j av a2 s. c o m*/ } } PreparedStatement stmt = null; ResultSet rs = null; try { StringBuffer sql = new StringBuffer(); boolean revisionTable = tableName.startsWith(DbMailItem.TABLE_REVISION); sql.append("SELECT COUNT(*) FROM ").append(DbMailbox.qualifyTableName(mbox, tableName)) .append(" WHERE ").append(DbMailItem.IN_THIS_MAILBOX_AND); if (!revisionTable || mail_itemIds.size() > 0) { if (mail_itemIds.size() == 0) { sql.append(idColName).append(" in ('')"); } else { sql.append(DbUtil.whereIn(idColName, mail_itemIds.size())); } } if (revisionTable) { if (mail_itemIds.size() > 0 && rev_itemIds.size() > 0) { sql.append(" OR "); } if (rev_itemIds.size() > 0) { sql.append(DbUtil.whereIn(Db.getInstance().concat(idColName, "'-'", "version"), rev_itemIds.size())); } } stmt = conn.prepareStatement(sql.toString()); int pos = 1; pos = DbMailItem.setMailboxId(stmt, mbox, pos); for (int itemId : mail_itemIds) { stmt.setInt(pos++, itemId); } if (revisionTable) { for (Integer itemId : rev_itemIds.keySet()) { Collection<Integer> revs = rev_itemIds.get(itemId); for (int rev : revs) { stmt.setString(pos++, itemId + "-" + rev); } } } rs = stmt.executeQuery(); rs.next(); return rs.getInt(1); } catch (SQLException e) { throw ServiceException.FAILURE("getting number of rows for matching id's in " + tableName, e); } finally { DbPool.closeResults(rs); DbPool.quietCloseStatement(stmt); } }
From source file:com.android.tools.lint.checks.ResourceCycleDetector.java
private void findCycles(@NonNull Context context, @NonNull ResourceType type, @NonNull Multimap<String, String> map) { Set<String> visiting = Sets.newHashSetWithExpectedSize(map.size()); Set<String> seen = Sets.newHashSetWithExpectedSize(map.size()); for (String from : map.keySet()) { if (seen.contains(from)) { continue; }/*from ww w.j ava 2 s . c o m*/ List<String> chain = dfs(map, from, visiting); if (chain != null && chain.size() > 2) { // size 1 chains are handled directly seen.addAll(chain); Collections.reverse(chain); if (mChains == null) { mChains = Maps.newEnumMap(ResourceType.class); mLocations = Maps.newEnumMap(ResourceType.class); context.getDriver().requestRepeat(this, Scope.RESOURCE_FILE_SCOPE); } List<List<String>> list = mChains.get(type); if (list == null) { list = Lists.newArrayList(); mChains.put(type, list); } list.add(chain); } } }