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

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

Introduction

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

Prototype

@Nullable
public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue) 

Source Link

Document

Returns the first element in iterable or defaultValue if the iterable is empty.

Usage

From source file:com.b2international.snowowl.snomed.reasoner.server.classification.CollectingService.java

private CollectingServiceReference<S> getUnusedServiceReference() throws InterruptedException {

    // TODO: after some tries, we may want to give up
    while (true) {

        final CollectingServiceReference<S> serviceReference = serviceReferenceQueue.poll(1, TimeUnit.SECONDS);

        if (null != serviceReference) {
            return serviceReference;
        }//from  w  ww  .  j  a  v a 2  s. c  o m

        if (!sharedServiceCache.isEmpty()) {
            final IBranchPath evictedBranchPath = Iterables.getFirst(sharedServiceCache.keySet(), null);
            evict(evictedBranchPath);
        }
    }
}

From source file:com.clarkparsia.empire.ds.DataSourceUtil.java

/**
 * Return the type of the resource in the data source.
 * @param theSource the data source//  www .java 2  s .  c  om
 * @param theConcept the concept whose type to lookup
 * @return the rdf:type of the concept, or null if there is an error or one cannot be found.
 */
public static org.openrdf.model.Resource getType(DataSource theSource, Resource theConcept) {
    Iterable<org.openrdf.model.Resource> aTypes = getTypes(theSource, theConcept);
    if (aTypes == null || Iterables.isEmpty(aTypes)) {
        return null;
    } else {
        return Iterables.getFirst(aTypes, null);
    }
}

From source file:fr.xebia.cloud.amazon.aws.tools.AmazonAwsToolsSender.java

/**
 * <p>/*from w ww  . j  a v  a  2 s .com*/
 * Send the tools info by email.
 * </p>
 * 
 * @param userName
 *            valid email used as userName.
 */
public void sendEmail(@Nonnull final String userName) throws Exception {
    Preconditions.checkNotNull(userName, "Given userName can NOT be null");
    logger.debug("Process user {}", userName);

    Map<String, String> templatesParams = Maps.newHashMap();
    templatesParams.put("awsCredentialsHome", "~/.aws");
    templatesParams.put("awsCommandLinesHome", "~/aws-tools");
    templatesParams.put("awsCredentialsWindowsHome", "c:\\aws");
    templatesParams.put("awsCommandLinesWindowsHome", "c:\\aws-tools");
    templatesParams.put("userName", userName);

    User user;

    try {
        user = iam.getUser(new GetUserRequest().withUserName(userName)).getUser();
    } catch (NoSuchEntityException e) {
        logger.debug("User {} does not exist,", userName, e);
        throw e;
    }

    List<BodyPart> attachments = Lists.newArrayList();

    templatesParams.put("credentialsFileName", "aws-credentials.txt");

    // X509 SELF SIGNED CERTIFICATE
    Collection<SigningCertificate> certificates = iam
            .listSigningCertificates(new ListSigningCertificatesRequest().withUserName(user.getUserName()))
            .getCertificates();
    // filter active certificates
    certificates = Collections2.filter(certificates, new Predicate<SigningCertificate>() {
        @Override
        public boolean apply(SigningCertificate signingCertificate) {
            return StatusType.Active.equals(StatusType.fromValue(signingCertificate.getStatus()));
        }
    });

    SigningCertificate signingCertificate = Iterables.getFirst(certificates, null);
    templatesParams.put("X509CertificateFileName", "cert-" + signingCertificate.getCertificateId() + ".pem");
    templatesParams.put("X509PrivateKeyFileName", "pk-" + signingCertificate.getCertificateId() + ".pem");

    sendEmail(templatesParams, attachments, userName);
}

From source file:org.opendaylight.netconf.sal.rest.impl.RestconfDocumentedExceptionMapper.java

@Override
public Response toResponse(final RestconfDocumentedException exception) {

    LOG.debug("In toResponse: {}", exception.getMessage());

    final List<MediaType> accepts = headers.getAcceptableMediaTypes();
    accepts.remove(MediaType.WILDCARD_TYPE);

    LOG.debug("Accept headers: {}", accepts);

    final MediaType mediaType;
    if (accepts != null && accepts.size() > 0) {
        mediaType = accepts.get(0); // just pick the first one
    } else {/*from   w w w.  j  a  v  a  2 s  .  c  o m*/
        // Default to the content type if there's no Accept header
        mediaType = MediaType.APPLICATION_JSON_TYPE;
    }

    LOG.debug("Using MediaType: {}", mediaType);

    final List<RestconfError> errors = exception.getErrors();
    if (errors.isEmpty()) {
        // We don't actually want to send any content but, if we don't set any content here,
        // the tomcat front-end will send back an html error report. To prevent that, set a
        // single space char in the entity.

        return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
    }

    final int status = errors.iterator().next().getErrorTag().getStatusCode();

    final ControllerContext context = ControllerContext.getInstance();
    final DataNodeContainer errorsSchemaNode = (DataNodeContainer) context.getRestconfModuleErrorsSchemaNode();

    if (errorsSchemaNode == null) {
        return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
    }

    Preconditions.checkState(errorsSchemaNode instanceof ContainerSchemaNode,
            "Found Errors SchemaNode isn't ContainerNode");
    final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> errContBuild = Builders
            .containerBuilder((ContainerSchemaNode) errorsSchemaNode);

    final List<DataSchemaNode> schemaList = ControllerContext.findInstanceDataChildrenByName(errorsSchemaNode,
            Draft02.RestConfModule.ERROR_LIST_SCHEMA_NODE);
    final DataSchemaNode errListSchemaNode = Iterables.getFirst(schemaList, null);
    Preconditions.checkState(errListSchemaNode instanceof ListSchemaNode,
            "Found Error SchemaNode isn't ListSchemaNode");
    final CollectionNodeBuilder<MapEntryNode, MapNode> listErorsBuilder = Builders
            .mapBuilder((ListSchemaNode) errListSchemaNode);

    for (final RestconfError error : errors) {
        listErorsBuilder.withChild(toErrorEntryNode(error, errListSchemaNode));
    }
    errContBuild.withChild(listErorsBuilder.build());

    final NormalizedNodeContext errContext = new NormalizedNodeContext(new InstanceIdentifierContext<>(null,
            (DataSchemaNode) errorsSchemaNode, null, context.getGlobalSchema()), errContBuild.build());

    Object responseBody;
    if (mediaType.getSubtype().endsWith("json")) {
        responseBody = toJsonResponseBody(errContext, errorsSchemaNode);
    } else {
        responseBody = toXMLResponseBody(errContext, errorsSchemaNode);
    }

    return Response.status(status).type(mediaType).entity(responseBody).build();
}

From source file:com.google.gerrit.testutil.ConfigSuite.java

private static Field getOnlyField(Class<?> clazz, Class<? extends Annotation> ann) {
    List<Field> fields = Lists.newArrayListWithExpectedSize(1);
    for (Field f : clazz.getFields()) {
        if (f.getAnnotation(ann) != null) {
            fields.add(f);/*from w  w  w . j a  va 2s  . com*/
        }
    }
    checkArgument(fields.size() <= 1, "expected 1 @ConfigSuite.%s field, found: %s", ann.getSimpleName(),
            fields);
    return Iterables.getFirst(fields, null);
}

From source file:fr.mby.opa.picsimpl.dao.DbPictureDao.java

@Override
public Picture loadFullPictureById(final long id) {
    Assert.notNull(id, "Picture Id should be supplied !");

    final EmCallback<Picture> emCallback = new EmCallback<Picture>(this.getEmf()) {

        @Override/*  w w w.ja va  2s  . c  o  m*/
        @SuppressWarnings("unchecked")
        protected Picture executeWithEntityManager(final EntityManager em) throws PersistenceException {
            final Query findByIdQuery = em.createNamedQuery(Picture.LOAD_FULL_PICTURE_BY_ID);
            findByIdQuery.setParameter("id", id);

            final Picture picture = Iterables.getFirst(findByIdQuery.getResultList(), null);
            return picture;
        }
    };

    return emCallback.getReturnedValue();
}

From source file:com.eucalyptus.objectstorage.pipeline.WalrusRESTPipeline.java

/**
 * Is walrus domainname a subdomain of the host header host. If so, then it is likely a bucket prefix.
 * But, since S3 buckets can include '.' can't just parse on '.'s
 * @param fullHostname//from  w ww .j  a v  a 2  s. c o m
 * @return
 */
private boolean maybeBucketHostedStyle(String fullHostHeader) {
    try {
        return DomainNames
                .absolute(
                        Name.fromString(Iterables.getFirst(hostSplitter.split(fullHostHeader), fullHostHeader)))
                .subdomain(DomainNames.externalSubdomain(Walrus.class));
    } catch (Exception e) {
        LOG.error("Error parsing domain name from hostname: " + fullHostHeader, e);
        return false;
    }
}

From source file:com.eucalyptus.compute.common.internal.tags.TagSupport.java

public static TagSupport fromIdentifier(@Nonnull final String id) {
    return supportByIdentifierPrefix.get(Iterables.getFirst(idSplitter.split(id), ""));
}

From source file:com.hubspot.jinjava.interpret.JinjavaInterpreter.java

private void resolveBlockStubs(OutputList output, Stack<String> blockNames) {
    for (BlockPlaceholderOutputNode blockPlaceholder : output.getBlocks()) {

        if (!blockNames.contains(blockPlaceholder.getBlockName())) {
            Collection<List<? extends Node>> blockChain = blocks.get(blockPlaceholder.getBlockName());
            List<? extends Node> block = Iterables.getFirst(blockChain, null);

            if (block != null) {
                List<? extends Node> superBlock = Iterables.get(blockChain, 1, null);
                context.setSuperBlock(superBlock);

                OutputList blockValueBuilder = new OutputList();

                for (Node child : block) {
                    blockValueBuilder.addNode(child.render(this));
                }//  w w w .  ja  v a  2 s  . c o m

                blockNames.push(blockPlaceholder.getBlockName());
                resolveBlockStubs(blockValueBuilder, blockNames);
                blockNames.pop();

                context.removeSuperBlock();

                blockPlaceholder.resolve(blockValueBuilder.getValue());
            }
        }

        if (!blockPlaceholder.isResolved()) {
            blockPlaceholder.resolve("");
        }
    }
}

From source file:br.com.tecsinapse.exporter.importer.ImporterUtils.java

public static final Map<Method, TableCellMapping> getMappedMethods(Class<?> clazz, final Class<?> group) {

    Set<Method> cellMappingMethods = ReflectionUtils.getAllMethods(clazz,
            ReflectionUtils.withAnnotation(TableCellMapping.class));
    cellMappingMethods.addAll(//from w w  w . j ava 2  s .c om
            ReflectionUtils.getAllMethods(clazz, ReflectionUtils.withAnnotation(TableCellMappings.class)));

    Multimap<Method, Optional<TableCellMapping>> tableCellMappingByMethod = FluentIterable
            .from(cellMappingMethods).index(new Function<Method, Optional<TableCellMapping>>() {
                @Override
                public Optional<TableCellMapping> apply(@Nonnull Method method) {
                    checkNotNull(method);
                    return Optional.fromNullable(method.getAnnotation(TableCellMapping.class))
                            .or(getFirstTableCellMapping(method.getAnnotation(TableCellMappings.class), group));
                }
            }).inverse();

    tableCellMappingByMethod = filterEntries(tableCellMappingByMethod,
            new Predicate<Entry<Method, Optional<TableCellMapping>>>() {
                @Override
                public boolean apply(@Nonnull Entry<Method, Optional<TableCellMapping>> entry) {
                    checkNotNull(entry);
                    return entry.getValue().isPresent()
                            && any(Lists.newArrayList(entry.getValue().get().groups()), assignableTo(group));
                }
            });

    Multimap<Method, TableCellMapping> methodByTableCellMapping = transformValues(tableCellMappingByMethod,
            new Function<Optional<TableCellMapping>, TableCellMapping>() {
                @Override
                public TableCellMapping apply(@Nonnull Optional<TableCellMapping> tcmOptional) {
                    checkNotNull(tcmOptional);
                    return tcmOptional.get();
                }
            });

    return Maps.transformValues(methodByTableCellMapping.asMap(),
            new Function<Collection<TableCellMapping>, TableCellMapping>() {
                @Override
                public TableCellMapping apply(@Nonnull Collection<TableCellMapping> tcms) {
                    checkNotNull(tcms);
                    return Iterables.getFirst(tcms, null);
                }
            });
}