List of usage examples for com.google.common.collect Iterables get
public static <T> T get(Iterable<T> iterable, int position)
From source file:com.opengamma.strata.report.framework.expression.IterableTokenEvaluator.java
@Override public EvaluationResult evaluate(Iterable<?> iterable, CalculationFunctions functions, String firstToken, List<String> remainingTokens) { String token = firstToken.toLowerCase(Locale.ENGLISH); Integer index = Ints.tryParse(token); if (index != null) { try {//from w ww . j ava 2 s . co m return EvaluationResult.success(Iterables.get(iterable, index), remainingTokens); } catch (IndexOutOfBoundsException e) { return invalidTokenFailure(iterable, token); } } Set<String> tokens = tokens(iterable); for (Object item : iterable) { if (!fieldValues(item).contains(token)) { continue; } if (!tokens.contains(token)) { return ambiguousTokenFailure(iterable, token); } return EvaluationResult.success(item, remainingTokens); } return invalidTokenFailure(iterable, token); }
From source file:brooklyn.entity.waratek.cloudvm.WaratekNodePlacementStrategy.java
@Override public List<Location> locationsForAdditions(Multimap<Location, Entity> currentMembers, Collection<? extends Location> locs, int numToAdd) { if (locs.isEmpty() && numToAdd > 0) { throw new IllegalArgumentException( "No locations supplied, when requesting locations for " + numToAdd + " nodes"); }/*from www .j a v a 2 s .com*/ List<WaratekMachineLocation> available = Lists .newArrayList(Iterables.filter(locs, WaratekMachineLocation.class)); int remaining = numToAdd; for (WaratekMachineLocation machine : available) { remaining -= machine.getAvailableJvcCount(); } if (LOG.isDebugEnabled()) { LOG.debug("Requested {}, Need {} more from new JVMs, Current JVMs {}", new Object[] { numToAdd, remaining, Iterables.toString(Iterables.transform(locs, identity())) }); } if (remaining > 0) { // FIXME what happens if there are no JVMs available? WaratekMachineLocation machine = Iterables.get(available, 0); // Grow the JVM cluster; based on max number of JVCs int maxSize = machine.getMaxSize(); int delta = (remaining / maxSize) + (remaining % maxSize > 0 ? 1 : 0); Collection<Entity> added = machine.getWaratekInfrastructure().getVirtualMachineCluster() .resizeByDelta(delta); if (LOG.isDebugEnabled()) { LOG.debug("Added {} JVMs: {}", delta, Iterables.toString(Iterables.transform(added, identity()))); } // Add the newly created locations for each JVM // TODO wait until all JVMs have started up? Collection<WaratekMachineLocation> jvms = Collections2.transform(added, new Function<Entity, WaratekMachineLocation>() { @Override public WaratekMachineLocation apply(@Nullable Entity input) { return ((JavaVirtualMachine) input).getDynamicLocation(); } }); available.addAll(jvms); } // Logic from parent, with enhancements and types List<Location> result = Lists.newArrayList(); Map<WaratekMachineLocation, Integer> sizes = toAvailableLocationSizes(available); for (int i = 0; i < numToAdd; i++) { WaratekMachineLocation smallest = null; int minSize = 0; for (WaratekMachineLocation loc : sizes.keySet()) { int size = sizes.get(loc); if (smallest == null || size < minSize) { smallest = loc; minSize = size; } } Preconditions.checkState(smallest != null, "smallest was null; locs=%s", sizes.keySet()); result.add(smallest); // Update population in locations, removing if maximum reached int maxSize = smallest.getMaxSize(); int currentSize = sizes.get(smallest) + 1; if (currentSize < maxSize) { sizes.put(smallest, currentSize); } else { sizes.remove(smallest); } } if (LOG.isDebugEnabled()) { LOG.debug("Placement for {} nodes: {}", numToAdd, Iterables.toString(Iterables.transform(result, identity()))); } return result; }
From source file:ru.parallel.octotron.core.persistence.GraphManager.java
private GraphEntity GetEntity(IUniqueID<?> id) { Collection<GraphLink> links = graph_service.GetLinks("AID", id.GetID()); Collection<GraphObject> objects = graph_service.GetObjects("AID", id.GetID()); if (!links.isEmpty() && !objects.isEmpty()) throw new ExceptionModelFail("found few entities with the same id: " + id.GetID()); if (objects.size() == 1) return Iterables.get(objects, 0); else if (objects.size() > 1) throw new ExceptionModelFail("found multiple objects with AID: " + id.GetID()); if (links.size() == 1) return Iterables.get(links, 0); else if (links.size() > 1) throw new ExceptionModelFail("found multiple links with AID: " + id.GetID()); throw new ExceptionModelFail("could not get entity for AID: " + id.GetID()); }
From source file:net.lldp.checksims.algorithm.similaritymatrix.output.MatrixThresholdPrinter.java
/** * Print significant results in a similarity matrix. * * @param matrix Matrix to print//from w ww. j a v a2 s.c om * @return Results in matrix over threshold * @throws InternalAlgorithmError Thrown on internal error processing matrix */ @Override public String printMatrix(SimilarityMatrix matrix) throws InternalAlgorithmError { checkNotNull(matrix); StringBuilder builder = new StringBuilder(); DecimalFormat formatter = new DecimalFormat("0.##"); ImmutableSet<AlgorithmResults> results = matrix.getBaseResults(); Set<AlgorithmResults> filteredBelowThreshold = results.stream().filter( (result) -> result.percentMatchedA().gtEQ(threshold) || result.percentMatchedB().gtEQ(threshold)) .collect(Collectors.toCollection(HashSet::new)); if (filteredBelowThreshold.isEmpty()) { builder.append("No significant matches found.\n"); } // Loop until all results over threshold consumed while (!filteredBelowThreshold.isEmpty()) { // Find the largest single result Real largest = Real.ZERO; AlgorithmResults largestResult = Iterables.get(filteredBelowThreshold, 0); for (AlgorithmResults result : filteredBelowThreshold) { if (result.percentMatchedA().greaterThan(largest)) { largest = result.percentMatchedA(); largestResult = result; } if (result.percentMatchedB().greaterThan(largest)) { largest = result.percentMatchedB(); largestResult = result; } } Real largerOfTwo; Real smallerOfTwo; Submission largerSubmission; Submission smallerSubmission; if (largestResult.percentMatchedA().greaterThanEqualTo(largestResult.percentMatchedB())) { largerOfTwo = largestResult.percentMatchedA().multiply(new Real(100)); smallerOfTwo = largestResult.percentMatchedB().multiply(new Real(100)); largerSubmission = largestResult.a; smallerSubmission = largestResult.b; } else { largerOfTwo = largestResult.percentMatchedB().multiply(new Real(100)); smallerOfTwo = largestResult.percentMatchedA().multiply(new Real(100)); largerSubmission = largestResult.b; smallerSubmission = largestResult.a; } // We have the largest single result, print it builder.append("Found match of "); builder.append(formatter.format(largerOfTwo.asDouble())); builder.append("% (inverse match "); builder.append(formatter.format(smallerOfTwo.asDouble())); builder.append("%) between submissions \""); builder.append(largerSubmission.getName()); builder.append("\" and \""); builder.append(smallerSubmission.getName()); builder.append("\"\n"); // Remove the largest results filteredBelowThreshold.remove(largestResult); } return builder.toString(); }
From source file:org.jclouds.compute.callables.InitAndStartScriptOnNode.java
protected ExecResponse runCommand(String command) { ExecResponse returnVal;//from www . j ava 2 s . c om logger.debug(">> running [%s] as %s@%s", command.replace(node.getAdminPassword() != null ? node.getAdminPassword() : "XXXXX", "XXXXX"), node.getCredentials().identity, Iterables.get(node.getPublicAddresses(), 0)); returnVal = ssh.exec(command); return returnVal; }
From source file:org.jclouds.location.suppliers.OnlyLocationOrFirstZoneOrRegionMatchingRegionId.java
@Override @Singleton//from w ww.j a va2 s . c om public Location get() { Set<? extends Location> locations = locationsSupplier.get(); if (locationsSupplier.get().size() == 1) return getOnlyElement(locationsSupplier.get()); IsRegionAndIdEqualsOrIsZoneParentIdEquals matcher = null; try { String region = injector.getInstance(Key.get(String.class, Region.class)); if (region == null) return Iterables.get(locationsSupplier.get(), 0); matcher = injector.getInstance(IsRegionAndIdEqualsOrIsZoneParentIdEquals.class); Location toReturn = Iterables.find(locations, matcher); return toReturn.getScope() == LocationScope.REGION ? toReturn : toReturn.getParent(); } catch (NoSuchElementException e) { throw new IllegalStateException(String.format("region %s not found in %s", matcher, locations)); } }
From source file:com.google.javascript.jscomp.J2clConstantHoisterPass.java
private void maybeHoistClassField(Collection<Node> assignments, Collection<Node> hoistableFunctions) { // The field is only assigned twice: if (assignments.size() != 2) { return;/* w ww.j a v a2 s . c o m*/ } Node first = Iterables.get(assignments, 0); Node second = Iterables.get(assignments, 1); // One of them is the top level declaration and the other is the assignment in clinit. Node topLevelDeclaration = isClassFieldDeclaration(first) ? first : second; Node clinitAssignment = isClinitFieldAssignment(first) ? first : second; if (!isClassFieldDeclaration(topLevelDeclaration) || !isClinitFieldAssignment(clinitAssignment)) { return; } // And it is assigned to a literal value; hence could be used in static eval and safe to move: Node assignmentRhs = clinitAssignment.getSecondChild(); if (!NodeUtil.isLiteralValue(assignmentRhs, true /* includeFunctions */) || (assignmentRhs.isFunction() && !hoistableFunctions.contains(assignmentRhs))) { return; } // And the assignment are in the same script: if (NodeUtil.getEnclosingScript(clinitAssignment) != NodeUtil.getEnclosingScript(topLevelDeclaration)) { return; } // At this point the only case some could observe the declaration value is the when you have // cycle between clinits and the field is accessed before initialization; which is almost always // a bug and GWT never assumed this state is observable in its optimization, yet nobody // complained. So it is safe to upgrade it to a constant. hoistConstantLikeField(clinitAssignment, topLevelDeclaration); }
From source file:org.jclouds.virtualbox.functions.IMachineToSshClient.java
@Override public SshClient apply(final IMachine vm) { String sshPort = "22"; String guestIdentity = vm.getExtraData(GUEST_OS_USER); String guestCredential = vm.getExtraData(GUEST_OS_PASSWORD); LoginCredentials loginCredentials = LoginCredentials.builder().user(guestIdentity).password(guestCredential) .authenticateSudo(true).build(); String clientIpAddress = null; long nicSlot = 0; while (nicSlot < 4 && Strings.isNullOrEmpty(clientIpAddress)) { INetworkAdapter networkAdapter = vm.getNetworkAdapter(nicSlot); if (networkAdapter.getAttachmentType().equals(NetworkAttachmentType.NAT)) { for (String nameProtocolnumberAddressInboudportGuestTargetport : networkAdapter.getNATEngine() .getRedirects()) {/*from w w w.j a v a2 s .c o m*/ Iterable<String> stuff = Splitter.on(',') .split(nameProtocolnumberAddressInboudportGuestTargetport); String protocolNumber = Iterables.get(stuff, 1); String hostAddress = Iterables.get(stuff, 2); String inboundPort = Iterables.get(stuff, 3); String targetPort = Iterables.get(stuff, 5); if ("1".equals(protocolNumber) && "22".equals(targetPort)) { clientIpAddress = hostAddress; sshPort = inboundPort; } } } else if (networkAdapter.getAttachmentType().equals(NetworkAttachmentType.Bridged)) { clientIpAddress = networkUtils.getIpAddressFromNicSlot(vm.getName(), networkAdapter.getSlot()); } else if (networkAdapter.getAttachmentType().equals(NetworkAttachmentType.HostOnly)) { clientIpAddress = networkUtils.getValidHostOnlyIpFromVm(vm.getName()); } nicSlot++; } return sshClientFactory.create(HostAndPort.fromParts(clientIpAddress, Integer.parseInt(sshPort)), loginCredentials); }
From source file:com.google.errorprone.bugpatterns.collectionincompatibletype.TypeArgOfMethodArgMatcher.java
@Override Type extractSourceType(MethodInvocationTree tree, VisitorState state) { return extractTypeArgAsMemberOfSupertype( ASTHelpers.getType(Iterables.get(tree.getArguments(), methodArgIndex)), state.getSymbolFromString(methodArgTypeName), methodArgTypeArgIndex, state.getTypes()); }
From source file:org.richfaces.servlet.PushServletContainerInitializer.java
public void onStartup(Set<Class<?>> clasess, ServletContext servletContext) throws ServletException { if (Boolean.valueOf(servletContext.getInitParameter(SKIP_SERVLET_REGISTRATION_PARAM))) { return;/*w ww . j a v a2s .co m*/ } if (!isAtmospherePresent()) { return; } if (hasFilterMapping(PushFilter.class, servletContext)) { return; } try { String pushHandlerMapping; ServletRegistration servletRegistration = getServletRegistration(PushServlet.class, servletContext); if (servletRegistration == null) { registerPushServlet(servletContext); pushHandlerMapping = PUSH_CONTEXT_DEFAULT_MAPPING; } else { pushHandlerMapping = Iterables.get(servletRegistration.getMappings(), 0); } servletContext.setAttribute(PushContextFactoryImpl.PUSH_HANDLER_MAPPING_ATTRIBUTE, pushHandlerMapping); } catch (Exception e) { servletContext.log( MessageFormat.format("Exception registering RichFaces Push Servlet: {0]", e.getMessage()), e); } }