List of usage examples for com.google.common.collect Iterables size
public static int size(Iterable<?> iterable)
From source file:com.datastax.driver.core.utils.SocketChannelMonitor.java
/** * <p/>//from ww w .jav a 2 s . c om * Report for all sockets matching the given predicate. The report format reflects the number of open, closed, * live and total sockets created. This is logged at DEBUG if enabled. * <p/> * <p/> * If TRACE is enabled, each individual socket will be logged as well. * * @param channelFilter used to determine which sockets to report on. */ public void report(Predicate<SocketChannel> channelFilter) { if (logger.isDebugEnabled()) { Iterable<SocketChannel> channels = matchingChannels(channelFilter); Iterable<SocketChannel> open = Iterables.filter(channels, openChannels); Iterable<SocketChannel> closed = Iterables.filter(channels, Predicates.not(openChannels)); logger.debug( "Channel states: {} open, {} closed, live {}, total sockets created " + "(including those that don't match filter) {}.", Iterables.size(open), Iterables.size(closed), Iterables.size(channels), channelsCreated.get()); if (logger.isTraceEnabled()) { logger.trace("Open channels {}.", open); logger.trace("Closed channels {}.", closed); } } }
From source file:com.facebook.buck.util.bser.BserSerializer.java
@SuppressWarnings("unchecked") private static ByteBuffer appendRecursive(ByteBuffer buffer, Object value, CharsetEncoder utf8Encoder) throws IOException { if (value instanceof Boolean) { buffer = increaseBufferCapacityIfNeeded(buffer, 1); buffer.put(((boolean) value) ? BSER_TRUE : BSER_FALSE); } else if (value == null) { buffer = increaseBufferCapacityIfNeeded(buffer, 1); buffer.put(BSER_NULL);// ww w . j av a 2 s. c o m } else if (value instanceof String) { buffer = appendString(buffer, (String) value, utf8Encoder); } else if (value instanceof Double || value instanceof Float) { buffer = increaseBufferCapacityIfNeeded(buffer, 9); buffer.put(BSER_REAL); buffer.putDouble((double) value); } else if (value instanceof Long) { buffer = appendLong(buffer, (long) value); } else if (value instanceof Integer) { buffer = appendLong(buffer, (int) value); } else if (value instanceof Short) { buffer = appendLong(buffer, (short) value); } else if (value instanceof Byte) { buffer = appendLong(buffer, (byte) value); } else if (value instanceof Map<?, ?>) { Map<Object, Object> map = (Map<Object, Object>) value; int mapLen = map.size(); BserIntegralEncodedSize encodedSize = getEncodedSize(mapLen); buffer = increaseBufferCapacityIfNeeded(buffer, 2 + encodedSize.size); buffer.put(BSER_OBJECT); buffer = appendLongWithSize(buffer, mapLen, encodedSize); for (Map.Entry<Object, Object> entry : map.entrySet()) { if (!(entry.getKey() instanceof String)) { throw new IOException(String.format("Unrecognized map key type %s, expected string", entry.getKey().getClass())); } buffer = appendString(buffer, (String) entry.getKey(), utf8Encoder); buffer = appendRecursive(buffer, entry.getValue(), utf8Encoder); } } else if (value instanceof Iterable<?>) { Iterable<Object> iterable = (Iterable<Object>) value; int len = Iterables.size(iterable); BserIntegralEncodedSize encodedSize = getEncodedSize(len); buffer = increaseBufferCapacityIfNeeded(buffer, 2 + encodedSize.size); buffer.put(BSER_ARRAY); buffer = appendLongWithSize(buffer, len, encodedSize); for (Object obj : iterable) { buffer = appendRecursive(buffer, obj, utf8Encoder); } } else { throw new RuntimeException("Cannot encode object: " + value); } return buffer; }
From source file:edu.mit.streamjit.util.bytecode.Module.java
public void dump(PrintWriter writer) { writer.write("module " + toString()); writer.println();//from ww w .j ava2 s . c o m List<Klass> mutable = new ArrayList<>(), immutable = new ArrayList<>(); for (Klass k : klasses) if (k.isMutable()) mutable.add(k); else immutable.add(k); writer.write(mutable.size() + " mutable klasses"); writer.println(); for (Klass k : mutable) { k.dump(writer); writer.println(); } writer.write(immutable.size() + " immutable klasses"); writer.println(); for (Klass k : immutable) { //For brevity, just print names. writer.write(k.getName()); writer.println(); } writer.println(); writer.write(Iterables.size(types()) + " types"); writer.println(); for (Type t : types()) { writer.write(t.toString()); writer.println(); } writer.println(); writer.write(Iterables.size(constants()) + " constants"); writer.println(); for (Constant<?> c : constants()) { writer.write(c.toString()); writer.println(); } }
From source file:org.obiba.opal.web.identifiers.IdentifiersMappingResource.java
@GET @Path("/_count") public String getEntitiesCount(@QueryParam("type") String entityType) { ensureEntityType(entityType);/*from w w w . j a v a2s . c om*/ return String.valueOf(Iterables.size(getUnitIdentifiers(entityType))); }
From source file:io.brooklyn.ambari.AmbariClusterImpl.java
@Override public void init() { super.init(); isHostGroupsDeployment = Iterables.size(getHostGroups()) > 0; addChild(createServerSpec(getConfig(SECURITY_GROUP))); if (!getConfig(SERVER_COMPONENTS).isEmpty()) { for (AmbariServer ambariServer : getAmbariServers()) { ambariServer.config().set(SoftwareProcess.CHILDREN_STARTABLE_MODE, SoftwareProcess.ChildStartableMode.BACKGROUND_LATE); EntitySpec<? extends AmbariAgent> agentSpec = AmbariAgentImpl.createAgentSpec(this, null); ambariServer.addChild(agentSpec); }/*from www. ja va 2 s. c om*/ } services = MutableList.copyOf(getConfig(HADOOP_SERVICES)); calculateTotalAgents(); if (!isHostGroupsDeployment) { createClusterTopology(); if (services.size() == 0) { services.addAll(DEFAULT_SERVICES); } } addEnricher(Enrichers.builder().propagating(Attributes.MAIN_URI).from(getMasterAmbariServer()).build()); componentsByNode = new MutableMap<String, List<String>>(); addDeprecatedExtraServiceToExtraServices(); for (EntitySpec<? extends ExtraService> entitySpec : getConfig(EXTRA_HADOOP_SERVICES)) { LOG.warn(EXTRA_HADOOP_SERVICES.getName() + " configuration key is deprecated. Extra services should now be defined through as children by using 'brooklyn.children'"); addChild(entitySpec); } final Iterable<String> ambariHostGroupNames = transform(getHostGroups(), new Function<AmbariHostGroup, String>() { @Nullable @Override public String apply(@Nullable AmbariHostGroup ambariHostGroup) { return ambariHostGroup != null ? ambariHostGroup.getDisplayName() : null; } }); for (ExtraService extraService : Entities.descendants(this, ExtraService.class)) { if (extraService.getConfig(ExtraService.SERVICE_NAME) == null && extraService.getConfig(ExtraService.COMPONENT_NAMES) == null) { continue; } if (isHostGroupsDeployment) { checkNotNull(extraService.getConfig(ExtraService.COMPONENT_NAMES), "Entity \"%s\" must define a list of components names as this is a host groups based deployment. Please use the \"%s\" configuration key", extraService.getEntityType().getName(), ExtraService.COMPONENT_NAMES.getName()); for (ExtraService.ComponentMapping componentMapping : extraService.getComponentMappings()) { if (!componentMapping.getHost().equals(getConfig(SERVER_HOST_GROUP)) && !Iterables.contains(ambariHostGroupNames, componentMapping.getHost())) { throw new IllegalStateException(String.format( "Extra component \"%s\" of entity \"%s\" cannot be bound to \"%s\" host group because it does not exist. Please choose from %s or " + getConfig(SERVER_HOST_GROUP), componentMapping.getComponent(), extraService.getEntityType().getName(), componentMapping.getHost(), ambariHostGroupNames)); } if (!componentsByNode.containsKey(componentMapping.getHost())) { componentsByNode.put(componentMapping.getHost(), MutableList.<String>of()); } componentsByNode.get(componentMapping.getHost()).add(componentMapping.getComponent()); } } else { checkNotNull(extraService.getConfig(ExtraService.SERVICE_NAME), "Entity \"%s\" must define a service name as this is a services based deployment. Please use the \"%s\" configuration key", extraService.getEntityType().getName(), ExtraService.SERVICE_NAME.getName()); if (StringUtils.isNotBlank(extraService.getConfig(ExtraService.SERVICE_NAME))) { services.add(extraService.getConfig(ExtraService.SERVICE_NAME)); } } } }
From source file:eu.esdihumboldt.hale.ui.cst.debug.metadata.internal.TreeGraphMLProvider.java
/** * method for gathering the string of a node value * /*w ww. ja v a 2 s . com*/ * @param value the node value * @return the dot-format-string */ private String getChildrencountString(Object value) { if (value instanceof Instance) { String ivalue = "Instance(" + Iterables.size(((Instance) value).getPropertyNames()) + ")"; return ivalue; } if (value instanceof Group) { return "Group(" + Iterables.size(((Group) value).getPropertyNames()) + ")"; } return value.toString(); }
From source file:fr.evercraft.essentials.command.EELag.java
private boolean commandLag(final CommandSource player) { Double tps = this.getTPS(); List<Text> list = new ArrayList<Text>(); list.add(EEMessages.LAG_TIME.getFormat().toText("<time>", this.plugin.getEverAPI().getManagerUtils() .getDate().formatDate(ManagementFactory.getRuntimeMXBean().getStartTime()))); list.add(EEMessages.LAG_TPS.getFormat().toText("<tps>", Text.builder(tps.toString()).color(getColorTPS(tps)).build())); list.add(EEMessages.LAG_HISTORY_TPS.getFormat().toText("<tps>", getHistoryTPS())); list.add(EEMessages.LAG_MEMORY.getFormat().toText("<usage>", String.valueOf(Runtime.getRuntime().totalMemory() / 1024 / 1024), "<total>", String.valueOf(Runtime.getRuntime().maxMemory() / 1024 / 1024))); List<Text> worlds = new ArrayList<Text>(); for (World world : this.plugin.getEServer().getWorlds()) { Map<String, EReplace<?>> replaces = new HashMap<String, EReplace<?>>(); replaces.put("<world>", EReplace.of(world.getName())); replaces.put("<entities>", EReplace.of(String.valueOf(world.getEntities().size()))); replaces.put("<tiles>", EReplace.of(String.valueOf(world.getTileEntities().size()))); replaces.put("<chunks>", EReplace.of(String.valueOf(Iterables.size(world.getLoadedChunks())))); Text text = EEMessages.LAG_WORLDS_WORLD.getFormat().toText2(replaces); if (!text.getHoverAction().isPresent() && EEMessages.LAG_WORLDS_WORLD_HOVER.getMessage().getChat().isPresent()) { text = text.toBuilder().onHover( TextActions.showText(EEMessages.LAG_WORLDS_WORLD_HOVER.getFormat().toText2(replaces))) .build();/*www.ja v a2 s . c om*/ } worlds.add(text); } list.add(EEMessages.LAG_WORLDS.getFormat().toText("<worlds>", Text.joinWith(EEMessages.LAG_WORLDS_SEPARATOR.getText(), worlds))); this.plugin.getEverAPI().getManagerService().getEPagination().sendTo( EEMessages.LAG_TITLE.getText().toBuilder().onClick(TextActions.runCommand("/lag")).build(), list, player); return true; }
From source file:org.killbill.billing.invoice.calculator.InvoiceCalculatorUtils.java
private static BigDecimal computeInvoiceAmountAdjustedForAccountCredit(final Currency currency, final Iterable<InvoiceItem> invoiceItems) { BigDecimal amountAdjusted = BigDecimal.ZERO; if (invoiceItems == null || !invoiceItems.iterator().hasNext()) { return KillBillMoney.of(amountAdjusted, currency); }/* w w w . j a v a 2s .co m*/ for (final InvoiceItem invoiceItem : invoiceItems) { final Iterable<InvoiceItem> otherInvoiceItems = Iterables.filter(invoiceItems, new Predicate<InvoiceItem>() { @Override public boolean apply(final InvoiceItem input) { return !input.getId().equals(invoiceItem.getId()); } }); if (InvoiceItemType.CREDIT_ADJ.equals(invoiceItem.getInvoiceItemType()) && (Iterables.size(otherInvoiceItems) == 1 && InvoiceItemType.CBA_ADJ .equals(otherInvoiceItems.iterator().next().getInvoiceItemType()) && otherInvoiceItems.iterator().next().getInvoiceId().equals(invoiceItem.getInvoiceId()) && otherInvoiceItems.iterator().next().getAmount() .compareTo(invoiceItem.getAmount().negate()) == 0)) { amountAdjusted = amountAdjusted.add(invoiceItem.getAmount()); } } return KillBillMoney.of(amountAdjusted, currency); }
From source file:org.killbill.billing.jaxrs.resources.UsageResource.java
@TimedResource @POST/*from w w w . j a v a 2 s. c o m*/ @Consumes(APPLICATION_JSON) @Produces(APPLICATION_JSON) @ApiOperation(value = "Record usage for a subscription") @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid subscription (e.g. inactive)") }) public Response recordUsage(final SubscriptionUsageRecordJson json, @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason, @HeaderParam(HDR_COMMENT) final String comment, @javax.ws.rs.core.Context final HttpServletRequest request, @javax.ws.rs.core.Context final UriInfo uriInfo) throws EntitlementApiException, AccountApiException, UsageApiException { verifyNonNullOrEmpty(json, "SubscriptionUsageRecordJson body should be specified"); verifyNonNullOrEmpty(json.getSubscriptionId(), "SubscriptionUsageRecordJson subscriptionId needs to be set", json.getUnitUsageRecords(), "SubscriptionUsageRecordJson unitUsageRecords needs to be set"); Preconditions.checkArgument(!json.getUnitUsageRecords().isEmpty()); for (final UnitUsageRecordJson unitUsageRecordJson : json.getUnitUsageRecords()) { verifyNonNullOrEmpty(unitUsageRecordJson.getUnitType(), "UnitUsageRecordJson unitType need to be set"); Preconditions.checkArgument(Iterables.size(unitUsageRecordJson.getUsageRecords()) > 0, "UnitUsageRecordJson usageRecords must have at least one element."); for (final UsageRecordJson usageRecordJson : unitUsageRecordJson.getUsageRecords()) { verifyNonNull(usageRecordJson.getAmount(), "UsageRecordJson amount needs to be set"); verifyNonNull(usageRecordJson.getRecordDate(), "UsageRecordJson recordDate needs to be set"); } } final CallContext callContext = context.createContext(createdBy, reason, comment, request); // Verify subscription exists.. final Entitlement entitlement = entitlementApi .getEntitlementForId(UUID.fromString(json.getSubscriptionId()), callContext); if (entitlement.getState() != EntitlementState.ACTIVE) { return Response.status(Status.BAD_REQUEST).build(); } final SubscriptionUsageRecord record = json.toSubscriptionUsageRecord(); usageUserApi.recordRolledUpUsage(record, callContext); return Response.status(Status.CREATED).build(); }
From source file:org.geogit.storage.memory.HeapGraphDatabase.java
@Override public int getDepth(ObjectId commitId) { PathToRootWalker walker = new PathToRootWalker(graph.get(commitId).get()); int depth = 0; O: while (walker.hasNext()) { for (Node n : walker.next()) { if (Iterables.size(n.to()) == 0) { break O; }/*from w w w. ja v a 2 s. c om*/ } depth++; } return depth; }