List of usage examples for com.google.common.collect Iterables tryFind
public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate)
From source file:brooklyn.networking.cloudstack.legacy.LegacyJcloudsCloudstackSubnetLocation.java
@Override protected JcloudsSshMachineLocation createJcloudsSshMachineLocation(ComputeService computeService, NodeMetadata node, String vmHostname1, Optional<HostAndPort> sshHostAndPort, ConfigBag setup) throws IOException { String subnetSpecificHostname = null; String vmHostname = vmHostname1; String sshHost = vmHostname;//from ww w . j av a 2 s. com Integer sshPort = null; PortForwardManager pfw = null; String publicIpId = null; final String serviceNetworkId = getConfig(CLOUDSTACK_SERVICE_NETWORK_ID); boolean portForwardingMode = Strings.isBlank(serviceNetworkId); LOG.debug("creating subnet JcloudsSshMachineLocation -- port forwarding={}, node={}", new Object[] { node, portForwardingMode }); if (!portForwardingMode) { LOG.debug( "Using service network for Brooklyn access - service network ID is {} - searching for NIC connected to this network", serviceNetworkId); CloudStackApi cloudStackApi = getComputeService().getContext().unwrapApi(CloudStackApi.class); VirtualMachineApi vmClient = cloudStackApi.getVirtualMachineApi(); VirtualMachine vm = vmClient.getVirtualMachine(node.getProviderId()); Iterable<NIC> allNics = vm.getNICs(); Predicate<NIC> isServiceNetwork = new Predicate<NIC>() { @Override public boolean apply(@Nullable NIC input) { return input != null && serviceNetworkId.equals(input.getNetworkId()); } }; Optional<NIC> serviceNic = Iterables.tryFind(allNics, isServiceNetwork); Iterable<NIC> otherNics = Iterables.filter(allNics, Predicates.not(isServiceNetwork)); checkState(serviceNic.isPresent(), "unable to identify NIC connected to service network " + serviceNetworkId); String ipAddress = serviceNic.get().getIPAddress(); checkState(Strings.isNonBlank(ipAddress), "no IP address on the NIC connected to service network " + serviceNetworkId); checkState(!Iterables.isEmpty(otherNics), "VM needs another NIC, in addition to the service network"); // NIC anotherNic = Iterables.get(otherNics, 0); sshHost = ipAddress; sshPort = 22; } else { pfw = getRequiredConfig(PORT_FORWARDING_MANAGER); publicIpId = getRequiredConfig(CLOUDSTACK_TIER_PUBLIC_IP_ID); Cidr cidr = getConfig(MANAGEMENT_ACCESS_CIDR); // others, besides 22! int privatePort = 22; int publicPort = pfw.acquirePublicPort(publicIpId); systemCreatePortForwarding(cidr, publicPort, node, privatePort); sshPort = publicPort; sshHost = checkNotNull(pfw.getPublicIpHostname(publicIpId), "No ip recorded for id %s", publicIpId); } LOG.info("Created VM in " + this + " in subnet at " + node + ", ssh accessible via " + sshHost + ":" + sshPort); // and wait for it to be reachable LOG.debug(" waiting for new VM " + node + " in " + this + " to be port reachable on " + sshHost + ":" + sshPort); boolean isReachable = NetworkMultiAddressUtils2.isAccessible(sshHost, sshPort, TimeUnit.MINUTES.toMillis(15)); if (!isReachable) { throw new IllegalStateException("Unable to contact forwarded SSH port for new VM " + node + " in " + this + " on " + sshHost + ":" + sshPort); } if (!NetworkMultiAddressUtils2.isResolveable(vmHostname)) { String oldHostname = vmHostname; vmHostname = Iterables.getFirst(Iterables.concat(node.getPublicAddresses(), node.getPrivateAddresses()), null); LOG.info("Renaming unresolvable hostname " + oldHostname + " to " + vmHostname); } // "public hostname" might be different // - sometimes it is not pingable from brooklyn (making sensors hard) // - sometimes furthest is the public one, we might want it // (eg if we are in different 10.x subnet - closest not always accessible) // or we might want nearest (if public is not accessible); // and also consider we are on /16 subnet with host, host has another 10.x/8 address, but no public address; // ie furthest might be inaccessible for other reasons // TODO i think the "right" way to do this is to have a pluggable "address chooser" ? LOG.debug(" vmHostname: " + vmHostname); // supply forwarded host and port Map<String, Object> sshConfig = extractSshConfig(setup, node); sshConfig.put(SshMachineLocation.SSH_HOST.getName(), sshHost); if (sshPort != null) sshConfig.put(SshMachineLocation.SSH_PORT.getName(), sshPort); if (LOG.isDebugEnabled()) { LOG.debug( "creating JcloudsSshMachineLocation in subnet {}, service network {}, for {}@{} for {} with {}", new Object[] { getRequiredConfig(CLOUDSTACK_SUBNET_NETWORK_ID), getConfig(CLOUDSTACK_SERVICE_NETWORK_ID), getUser(setup), vmHostname, setup.getDescription(), Entities.sanitize(sshConfig) }); } final JcloudsSshMachineLocation l = new AbstractJcloudsSubnetSshMachineLocation( MutableMap.builder().put("address", Networking.getInetAddressWithFixedName(vmHostname)) .put("displayName", vmHostname).put("user", getUser(setup)) // don't think "config" does anything .putAll(sshConfig).put("config", sshConfig).put("jcloudsParent", this).put("node", node) .put("port", sshPort).put(CALLER_CONTEXT, setup.get(CALLER_CONTEXT)).build(), this, node) { @Override public HostAndPort getSocketEndpointFor(Cidr accessor, int privatePort) { return getPortForwardingTo(accessor, this, privatePort); } }; l.init(); getManagementContext().getLocationManager().manage(l); l.setConfig(SUBNET_HOSTNAME_CONFIG, subnetSpecificHostname); l.setConfig(VM_IDENTIFIER, node.getId()); if (portForwardingMode) { // record port 22 forwarding pfw.associate(publicIpId, sshPort, l, 22); } LOG.debug(" waiting for new VM {} in {} to be SSH reachable on {}:{}", new Object[] { node, this, sshHost, sshPort }); final AtomicBoolean isActive = new AtomicBoolean(false); Repeater.create().repeat(new Runnable() { @Override public void run() { try { int rc = l.execCommands("test accessibility", ImmutableList.of("hostname")); isActive.set(rc == 0); } catch (Throwable t) { isActive.set(false); } } }).every(Duration.FIVE_SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return isActive.get(); } }).limitTimeTo(Duration.FIVE_MINUTES).run(); LOG.debug(" waited for new VM {} in {} to be SSH reachable on {}:{}, result={}", new Object[] { node, this, sshHost, sshPort, isActive.get() }); OperatingSystem operatingSystem = l.getNode().getOperatingSystem(); if (operatingSystem != null) { OsFamily family = operatingSystem.getFamily(); LOG.info("VM {}: OS family is {}", new Object[] { node, family }); if (family != OsFamily.WINDOWS && family != OsFamily.UNRECOGNIZED) { LOG.warn("VM {}: disabling iptables", new Object[] { node }); l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty", Arrays.asList(BashCommands.dontRequireTtyForSudo())); l.execScript("disabling iptables", Arrays.asList("sudo /etc/init.d/iptables stop", "sudo chkconfig iptables off")); } else { LOG.warn("VM {}: NOT disabling iptables because OS family is {}", new Object[] { node, family }); } } else { LOG.warn("VM {}: NOT disabling iptables because OS is not detected", new Object[] { node }); } String setupScript = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_URL); if (Strings.isNonBlank(setupScript)) { String setupVarsString = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_VARS); Map<String, String> substitutions = (setupVarsString != null) ? Splitter.on(",").withKeyValueSeparator(":").split(setupVarsString) : ImmutableMap.<String, String>of(); String scriptContent = ResourceUtils.create(this).getResourceAsString(setupScript); String script = TemplateProcessor.processTemplateContents(scriptContent, substitutions); l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty", Arrays.asList(BashCommands.dontRequireTtyForSudo())); l.execCommands("Customizing node " + this, ImmutableList.of(script)); } return l; }
From source file:org.apache.stanbol.client.enhancer.model.EnhancementStructure.java
/** * Returns an {@link EntityAnnotation} by its associated dereferenced * {@link Entity} URI/* w w w . j a v a 2 s . c o m*/ * * @param entityUri * @return */ public EntityAnnotation getEntityAnnotation(final String entityUri) { return Iterables.tryFind(getEntityAnnotations(), new Predicate<EntityAnnotation>() { @Override public boolean apply(final EntityAnnotation ea) { return ea.getDereferencedEntity().getUri().equals(entityUri); } }).orNull(); }
From source file:org.graylog2.inputs.InputServiceImpl.java
@Override public Extractor getExtractor(final Input input, final String extractorId) throws NotFoundException { final Optional<Extractor> extractor = Iterables.tryFind(this.getExtractors(input), new Predicate<Extractor>() { @Override/*from ww w. j a v a 2s . c om*/ public boolean apply(Extractor extractor) { return extractor.getId().equals(extractorId); } }); if (!extractor.isPresent()) { LOG.error("Extractor <{}> not found.", extractorId); throw new javax.ws.rs.NotFoundException("Couldn't find extractor " + extractorId); } return extractor.get(); }
From source file:org.opensaml.storage.impl.ServletRequestScopedStorageService.java
/** * Reconstitute stored data./*from w ww . ja v a 2 s. c o m*/ * * @throws IOException if an error occurs reconstituting the data */ protected void load() throws IOException { final Map<String, Map<String, MutableStorageRecord>> contextMap = getContextMap(); // Check for recursion. If load() is called directly, the above getter will // call us, which means we need to short-circuit the "outer" load call by // detecting that data has been loaded already. if (!contextMap.isEmpty()) { return; } log.trace("Loading storage state from cookie in current request"); setDirty(false); // Search for our cookie. final Cookie[] cookies = httpServletRequest.getCookies(); if (cookies == null) { return; } final Optional<Cookie> cookie = Iterables.tryFind(Arrays.asList(cookies), new Predicate<Cookie>() { public boolean apply(@Nullable final Cookie c) { return c != null && c.getName().equals(cookieName); } }); if (!cookie.isPresent() || cookie.get().getValue() == null || cookie.get().getValue().isEmpty()) { return; } try { final StringBuffer keyAliasUsed = new StringBuffer(); final String decrypted = dataSealer.unwrap(URISupport.doURLDecode(cookie.get().getValue()), keyAliasUsed); log.trace("Data after decryption: {}", decrypted); final JsonReader reader = Json.createReader(new StringReader(decrypted)); final JsonStructure st = reader.read(); if (!(st instanceof JsonObject)) { throw new IOException("Found invalid data structure while parsing context map"); } final JsonObject obj = (JsonObject) st; for (final Map.Entry<String, JsonValue> context : obj.entrySet()) { if (context.getValue().getValueType() != JsonValue.ValueType.OBJECT) { contextMap.clear(); throw new IOException("Found invalid data structure while parsing context map"); } final JsonObject contextRecords = (JsonObject) context.getValue(); for (Map.Entry<String, JsonValue> record : contextRecords.entrySet()) { final JsonObject fields = (JsonObject) record.getValue(); Long exp = null; if (fields.containsKey("x")) { exp = fields.getJsonNumber("x").longValueExact(); } create(context.getKey(), record.getKey(), fields.getString("v"), exp); } } if (keyStrategy != null) { try { setDirty(!keyStrategy.getDefaultKey().getFirst().equals(keyAliasUsed.toString())); } catch (final KeyException e) { log.error("Exception while accessing default key during stale key detection", e); setDirty(false); } } else { setDirty(false); } } catch (final NullPointerException | ClassCastException | ArithmeticException | JsonException e) { contextMap.clear(); setDirty(true); log.error("Exception while parsing context map", e); throw new IOException("Found invalid data structure while parsing context map", e); } catch (final DataExpiredException e) { setDirty(true); log.debug("Secured data or key has expired"); return; } catch (final DataSealerException e) { setDirty(true); log.error("Exception unwrapping secured data", e); throw new IOException("Exception unwrapping secured data", e); } }
From source file:org.opencms.xml.containerpage.CmsFormatterConfiguration.java
/** * Selects the best matching formatter for the provided type and width from this configuration.<p> * * This method first tries to find the formatter for the provided container type. * If this fails, it returns the width based formatter that matched the container width.<p> * * @param containerTypes the container types (comma separated) * @param containerWidth the container width * @param allowNested if nested containers are allowed * * @return the matching formatter, or <code>null</code> if none was found *///from w w w . j a va 2s . co m public I_CmsFormatterBean getDefaultFormatter(final String containerTypes, final int containerWidth, final boolean allowNested) { Optional<I_CmsFormatterBean> result = Iterables.tryFind(m_allFormatters, new MatchesTypeOrWidth(containerTypes, containerWidth, allowNested)); return result.orNull(); }
From source file:com.textocat.textokit.commons.io.axml.AXMLContentHandler.java
private void onAnnotationEnd(final String aType) throws SAXParseException { final String type = toTypeName(aType); Optional<Annotation> annoOpt = Iterables.tryFind(openAnnotations, new Predicate<Annotation>() { @Override//w w w .j a v a2 s.co m public boolean apply(Annotation input) { return Objects.equal(type, input.getType()); } }); if (annoOpt.isPresent()) { Annotation anno = annoOpt.get(); openAnnotations.remove(anno); anno.setEnd(textBuilder.length()); annotations.add(anno); } else { throw new SAXParseException("End of an element closes an unknown annotation", locator); } }
From source file:org.zanata.service.impl.TranslationServiceImpl.java
private void validateReviewPermissionIfApplicable(List<TransUnitUpdateRequest> translationRequests, HProjectIteration projectIteration, HLocale hLocale) { Optional<TransUnitUpdateRequest> hasReviewRequest = Iterables.tryFind(translationRequests, new Predicate<TransUnitUpdateRequest>() { @Override/*from w w w.java 2 s .co m*/ public boolean apply(TransUnitUpdateRequest input) { return isReviewState(input.getNewContentState()); } }); if (hasReviewRequest.isPresent()) { identity.checkPermission("translation-review", projectIteration.getProject(), hLocale); } }
From source file:org.opencms.xml.containerpage.CmsFormatterConfiguration.java
/** * Selects the best matching schema formatter for the provided type and width from this configuration.<p> * * @param containerTypes the container types (comma separated) * @param containerWidth the container width * * @return the matching formatter, or <code>null</code> if none was found */// w w w.j ava2 s. c o m public I_CmsFormatterBean getDefaultSchemaFormatter(final String containerTypes, final int containerWidth) { Optional<I_CmsFormatterBean> result = Iterables.tryFind(m_allFormatters, Predicates .and(new IsSchemaFormatter(), new MatchesTypeOrWidth(containerTypes, containerWidth, false))); return result.orNull(); }
From source file:org.gradle.api.publication.maven.internal.pom.DefaultPomDependenciesConverter.java
private Optional<Dependency> findEqualIgnoreScopeVersionAndExclusions(Collection<Dependency> dependencies, Dependency candidate) {//w w w . java 2 s .c om // For project dependencies de-duplication // Ignore scope on purpose // Ignore version because Maven doesn't support dependencies with different versions on different scopes // Ignore exclusions because we don't know how to choose/merge them // Consequence is that we use the highest version and the exclusions of highest priority dependency when de-duplicating // Use Maven Dependency "Management Key" as discriminator: groupId:artifactId:type:classifier final String candidateManagementKey = candidate.getManagementKey(); return Iterables.tryFind(dependencies, new Predicate<Dependency>() { @Override public boolean apply(Dependency dependency) { return dependency.getManagementKey().equals(candidateManagementKey); } }); }
From source file:org.eclipse.mylyn.internal.gerrit.core.remote.GerritReviewRemoteFactory.java
private IReviewItemSet getReviewItemSet(List<IReviewItemSet> sets, Integer parentKey) { final String patchSetNumber = parentKey.toString(); return Iterables.tryFind(sets, new Predicate<IReviewItemSet>() { public boolean apply(IReviewItemSet set) { return set.getId().equals(patchSetNumber); }// w ww. j a v a 2 s . co m }).orNull(); }