Example usage for com.google.common.collect Iterables find

List of usage examples for com.google.common.collect Iterables find

Introduction

In this page you can find the example usage for com.google.common.collect Iterables find.

Prototype

public static <T> T find(Iterable<T> iterable, Predicate<? super T> predicate) 

Source Link

Document

Returns the first element in iterable that satisfies the given predicate; use this method only when such an element is known to exist.

Usage

From source file:org.jclouds.fujitsu.fgcp.compute.functions.VServerMetadataToNodeMetadata.java

protected Location parseLocation(VServerWithVNICs from) {
    try {//from w ww . ja  v a 2 s .  co  m
        return Iterables.find(locations.get(), new FindLocationForVServer(from));
    } catch (NoSuchElementException e) {
        logger.warn("could not find a matching realm for server %s", from);
    }
    return null;
}

From source file:msi.gaml.descriptions.ActionDescription.java

@SuppressWarnings("rawtypes")
public boolean verifyArgs(final IDescription caller, final Arguments args) {
    final Arguments names = args == null ? NULL_ARGS : args;
    final Iterable<IDescription> formalArgs = getFormalArgs();
    final boolean noArgs = names.isEmpty();
    if (noArgs) {
        final Iterable<IDescription> formalArgsWithoutDefault = Iterables.filter(formalArgs,
                each -> !each.hasFacet(DEFAULT));
        if (Iterables.isEmpty(formalArgsWithoutDefault)) {
            return true;
        }/*from w  w w  . j  a v a2s  .  c  o  m*/
    }

    final List<String> allArgs = getArgNames();
    if (caller.getKeyword().equals(DO) || caller.getKeyword().equals(INVOKE)) {
        // If the names were not known at the time of the creation of the
        // caller, only the order
        if (names.containsKey("0")) {
            int index = 0;
            for (final String the_name : allArgs) {
                final String key = String.valueOf(index++);
                final IExpressionDescription old = names.get(key);
                if (old != null) {
                    names.put(the_name, old);
                    names.remove(key);
                }
            }
        }
    }

    // We compute the list of mandatory args

    if (formalArgs != null) {
        for (final IDescription c : formalArgs) {
            final String n = c.getName();
            if (c.hasFacet(DEFAULT)) {
                // AD: we compile the default (which is, otherwise, not
                // computed before validation
                c.getFacet(DEFAULT).compile(this);
                continue;
            }
            if (c.hasFacet(OPTIONAL) && c.getFacet(OPTIONAL).equalsString(FALSE) || !c.hasFacet(OPTIONAL)) {
                if (!names.containsKey(n)) {
                    caller.error(
                            "Missing argument " + n + " in call to " + getName() + ". Arguments passed are : "
                                    + names,
                            IGamlIssue.MISSING_ARGUMENT, caller.getUnderlyingElement(null), new String[] { n });
                    return false;
                }

            }
        }
    }

    for (final Map.Entry<String, IExpressionDescription> arg : names.entrySet()) {
        // A null value indicates a previous compilation error in the
        // arguments
        if (arg != null) {
            final String the_name = arg.getKey();
            if (!allArgs.contains(the_name)) {
                caller.error("Unknown argument " + the_name + " in call to " + getName(),
                        IGamlIssue.UNKNOWN_ARGUMENT, arg.getValue().getTarget(), new String[] { arg.getKey() });
                return false;
            } else if (arg.getValue() != null && arg.getValue().getExpression() != null) {
                final IDescription formalArg = Iterables.find(formalArgs,
                        input -> input.getName().equals(the_name));
                final IType<?> formalType = formalArg.getGamlType();
                final IType<?> callerType = arg.getValue().getExpression().getGamlType();
                if (Types.intFloatCase(formalType, callerType)) {
                    caller.warning("The argument " + the_name + " (of type " + callerType
                            + ") will be casted to " + formalType, IGamlIssue.WRONG_TYPE,
                            arg.getValue().getTarget());
                } else {
                    boolean accepted = formalType == Types.NO_TYPE || callerType.isTranslatableInto(formalType);
                    accepted = accepted || callerType == Types.NO_TYPE && formalType.getDefault() == null;
                    if (!accepted) {
                        caller.error("The type of argument " + the_name + " should be " + formalType,
                                IGamlIssue.WRONG_TYPE, arg.getValue().getTarget());
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

From source file:org.xrepl.xscript.util.EcoreUtil3.java

public static EEnumLiteral getEnumLiteral(EEnum enumType, final Enumerator enumerator) {
    return Iterables.find(enumType.getELiterals(), new Predicate<EEnumLiteral>() {

        public boolean apply(EEnumLiteral input) {
            return enumerator.toString().equals(input.getLiteral());
        }/*  w  w  w .  j ava 2s .c  o  m*/
    });
}

From source file:org.dasein.cloud.jclouds.vcloud.director.compute.VAppTemplateSupport.java

@Override
public @Nullable MachineImage getMachineImage(@Nonnull String machineImageId)
        throws CloudException, InternalException {
    RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> ctx = provider.getCloudClient();

    try {//w ww  .j a  v a2  s.co m
        try {
            VAppTemplate template = ctx.getApi().getVAppTemplateClient()
                    .getVAppTemplate(provider.toHref(ctx, machineImageId));

            if (template == null) {
                return null;
            }
            URI vdcURI = Iterables
                    .find(template.getLinks(), Predicates.and(LinkPredicates.relEquals(Link.Rel.UP),
                            LinkPredicates.typeEquals(VCloudDirectorMediaType.VDC)))
                    .getHref();
            Vdc vdc = ctx.getApi().getVdcClient().getVdc(vdcURI);
            URI orgURI = Iterables.find(vdc.getLinks(), Predicates.and(LinkPredicates.relEquals(Link.Rel.UP),
                    LinkPredicates.typeEquals(VCloudDirectorMediaType.VDC))).getHref();
            AdminOrg org = ctx.getApi().getOrgClient().getOrg(orgURI);

            return toMachineImage(ctx, org, template);
        } catch (AuthorizationException e) {
            return null;
        } catch (RuntimeException e) {
            logger.error("Error looking up machine image " + machineImageId + ": " + e.getMessage());
            if (logger.isDebugEnabled()) {
                e.printStackTrace();
            }
            throw new CloudException(e);
        }
    } finally {
        ctx.close();
    }
}

From source file:org.linagora.linshare.view.tapestry.pages.uploadrequest.Content.java

@Log
public StreamResponse onActionFromDownload(String uuid) throws BusinessException {
    UploadRequestEntryVo entry = Iterables.find(entries, UploadRequestEntryVo.equalTo(uuid));

    try {//ww w.ja v a 2s  . c  om
        InputStream stream = uploadRequestFacade.getFileStream(userVo, entry);
        return new FileStreamResponse(entry.getDocument(), stream);
    } catch (Exception e) {
        logger.error("File don't exist anymore.");
        businessMessagesManagementService
                .notify(new BusinessException(BusinessErrorCode.UPLOAD_REQUEST_ENTRY_FILE_UNREACHABLE,
                        "File unreachable in file system, please remove the entry"));
        return null;
    }
}

From source file:org.dasein.cloud.jclouds.vcloud.director.VCloudDirector.java

public @Nonnull AdminOrg getOrg(String name) throws CloudException {
    RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> ctx = getCloudClient();

    try {//from w w  w .j av  a 2s  . c  o m
        Reference orgRef = Iterables.find(ctx.getApi().getOrgClient().getOrgList().getOrgs(),
                ReferencePredicates.nameEquals(name));
        return getOrg(orgRef.getHref());
    } finally {
        ctx.close();
    }
}

From source file:com.netflix.priam.defaultimpl.PriamGuiceModule.java

@Provides
@Singleton//from   ww  w .j  a v a2 s .  c  o m
HostAndPort providePort(PriamConfiguration configuration) {
    ServerFactory serverFactory = configuration.getServerFactory();

    // Our method for obtaining connector factories from the server factory varies depending on the latter's type
    List<ConnectorFactory> connectorFactories;
    if (serverFactory instanceof DefaultServerFactory) {
        connectorFactories = ((DefaultServerFactory) serverFactory).getApplicationConnectors();
    } else if (serverFactory instanceof SimpleServerFactory) {
        connectorFactories = Collections.singletonList(((SimpleServerFactory) serverFactory).getConnector());
    } else {
        throw new IllegalStateException("Encountered an unexpected ServerFactory type");
    }

    // Find the first connector that matches and return its port information (in practice there should
    // be one, and just one, match)
    try {
        HttpConnectorFactory httpConnectorFactory = (HttpConnectorFactory) Iterables.find(connectorFactories,
                Predicates.instanceOf(HttpConnectorFactory.class));

        String host = httpConnectorFactory.getBindHost();
        if (host == null) {
            host = InetAddress.getLocalHost().getHostAddress();
        }

        int port = httpConnectorFactory.getPort();
        return HostAndPort.fromParts(host, port);
    } catch (UnknownHostException ex) {
        throw new IllegalStateException("Unable to determine the local host address for the server", ex);
    } catch (NoSuchElementException ex) {
        throw new IllegalStateException("Did not find a valid HttpConnector for the server", ex);
    }
}

From source file:brooklyn.networking.cloudstack.portforwarding.CloudstackPortForwarder.java

@Override
public HostAndPort openPortForwarding(HasNetworkAddresses targetVm, int targetPort,
        Optional<Integer> optionalPublicPort, Protocol protocol, Cidr accessingCidr) {
    Preconditions.checkNotNull(client);/* w  w  w .ja v a  2s .c  om*/
    final String ipAddress = String.valueOf(targetVm.getPrivateAddresses().toArray()[0]);
    Maybe<VirtualMachine> vm = client.findVmByIp(ipAddress);
    Boolean useVpc = subnetTier.getConfig(USE_VPC);
    String publicIpId = subnetTier.getConfig(PUBLIC_IP_ID);

    if (vm.isAbsentOrNull()) {
        Map<VirtualMachine, List<String>> vmIpMapping = client.getVmIps();
        log.error("Could not find any VMs with Ip Address {}; contenders: {}", ipAddress, vmIpMapping);
        return null;
    }
    NIC nic = Iterables.find(vm.get().getNICs(), new Predicate<NIC>() {
        @Override
        public boolean apply(NIC input) {
            return (input == null) ? false : ipAddress.equals(input.getIPAddress());
        }
    });
    String networkId = nic.getNetworkId();

    Maybe<String> vpcId;
    if (useVpc) {
        vpcId = client.findVpcIdFromNetworkId(networkId);

        if (vpcId.isAbsent()) {
            log.error(
                    "Could not find associated VPCs with Network: {}; continuing without opening port-forwarding",
                    networkId);
            return null;
        }
    } else {
        vpcId = Maybe.absent("use-vpc not enabled");
    }

    try {
        synchronized (mutex) {
            Maybe<PublicIPAddress> allocatedPublicIpAddressId = client
                    .findPublicIpAddressByVmId(vm.get().getId());
            PublicIPAddress publicIpAddress;

            if (allocatedPublicIpAddressId.isPresent()) {
                publicIpAddress = allocatedPublicIpAddressId.get();
            } else if (Strings.isNonBlank(publicIpId)) {
                publicIpAddress = client.getCloudstackGlobalClient().getAddressApi()
                        .getPublicIPAddress(publicIpId);
                if (publicIpAddress == null) {
                    throw new IllegalStateException("No public-ip found with id " + publicIpAddress);
                }
            } else if (useVpc) {
                publicIpAddress = client.createIpAddressForVpc(vpcId.get());
            } else {
                publicIpAddress = client.createIpAddressForNetwork(networkId);
            }

            int publicPort;
            if (optionalPublicPort.isPresent()) {
                publicPort = optionalPublicPort.get();
            } else {
                PortForwardManager pfw = getPortForwardManager();
                publicPort = pfw.acquirePublicPort(publicIpAddress.getId());
            }

            log.info(format("Opening port:%s on vm:%s with IP:%s", targetPort, vm.get().getId(),
                    publicIpAddress.getIPAddress()));
            String jobid = client.createPortForwardRule(networkId, publicIpAddress.getId(),
                    PortForwardingRule.Protocol.TCP, publicPort, vm.get().getId(), targetPort);
            client.waitForJobSuccess(jobid);
            log.debug("Enabled port-forwarding on {}", publicIpAddress.getIPAddress() + ":" + publicPort);
            return HostAndPort.fromParts(publicIpAddress.getIPAddress(), publicPort);
        }
    } catch (Exception e) {
        log.error("Failed creating port forwarding rule on " + this + " to " + targetPort + "; continuing", e);
        // it might already be created, so don't crash and burn too hard!
        return null;
    }
}

From source file:elaborate.editor.model.orm.User.java

public UserSetting setUserSetting(final String key, String value) {
    if (hasUserSetting(key)) {
        UserSetting setting = Iterables.find(Lists.newArrayList(getUserSettings()), userSettingWithKey(key));
        setting.setValue(value);// w  ww  .j  av a  2  s . c o  m
        return setting;

    } else {
        return addUserSetting(key, value);
    }
}

From source file:org.thiesen.jiffs.jobs.fetcher.SubscriptionFetcher.java

private boolean insertNewUniqueStory(final URI sourceUri, final SyndEntry entry) {
    final URI parsedUri = findValidEntryUri(entry);

    if (parsedUri == null) {
        return false;
    }//from w w  w . ja v a2 s  .co m

    final StoryDBO byUri = _storyDAO.findByUri(parsedUri);

    if (byUri != null) {
        return false;
    }

    final StoryDBO newDBO = new StoryDBO();

    newDBO.setSourceUri(sourceUri);
    newDBO.setStoryUri(parsedUri);
    newDBO.setPublicationDate(new DateTime(entry.getPublishedDate()));
    newDBO.setState(StoryState.NEW);
    newDBO.setTitle(entry.getTitle());
    if (entry.getDescription() != null) {
        newDBO.setText(entry.getDescription().getValue());
    } else {
        newDBO.setText("");
    }
    try {
        newDBO.setLinkUri(URI.create(StringUtils.trim(entry.getLink())));
    } catch (IllegalArgumentException e) {
        System.err.println("Invalid Link in entry " + entry.getLink());
        return false;
    }

    @SuppressWarnings("unchecked")
    final List<SyndEnclosure> enclosures = entry.getEnclosures();

    try {
        final SyndEnclosure imageEnclosure = Iterables.find(enclosures, IMAGE_MIME_TYPE_PREDICATE);

        newDBO.setImageUrl(URI.create(imageEnclosure.getUrl()));
    } catch (NoSuchElementException e) {
        // no image.
    }

    _storyDAO.insert(newDBO);

    return true;
}