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

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

Introduction

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

Prototype

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

Source Link

Document

Returns the single element contained in iterable , or defaultValue if the iterable is empty.

Usage

From source file:org.graylog2.shared.rest.resources.system.ThroughputResource.java

@GET
@Timed//from w w w  .j  a  va 2s.  c o  m
@RequiresPermissions(RestPermissions.THROUGHPUT_READ)
@ApiOperation(value = "Current throughput of this node in messages per second")
@Produces(MediaType.APPLICATION_JSON)
public Throughput total() {
    final SortedMap<String, Gauge> gauges = metricRegistry
            .getGauges(MetricUtils.filterSingleMetric(GlobalMetricNames.OUTPUT_THROUGHPUT_RATE));
    final Gauge gauge = Iterables.getOnlyElement(gauges.values(), null);
    if (gauge == null || !(gauge.getValue() instanceof Number)) {
        return Throughput.create(0);
    } else {
        return Throughput.create(((Number) gauge.getValue()).longValue());
    }
}

From source file:com.sun.tools.hat.internal.server.InstancesQuery.java

@Override
public void run() {
    ClassResolver resolver = new ClassResolver(snapshot, true);
    JavaClass clazz = resolver.apply(query);
    List<JavaClass> referrers = Lists.transform(params.get("referrer"), resolver);
    boolean referee = Boolean.parseBoolean(Iterables.getOnlyElement(params.get("referee"), "false"));
    String instancesOf;//from   ww w.  ja  v a2s  .c o m
    if (newObjects)
        instancesOf = referee ? "New referees" : "New instances";
    else
        instancesOf = referee ? "Referees" : "Instances";
    startHtml(String.format("%s of %s%s", instancesOf, clazz.getName(),
            includeSubclasses ? " (including subclasses)" : ""));
    if (referrers.isEmpty()) {
        out.print("<strong>");
        printClass(clazz);
        out.print("</strong><br><br>");
    } else {
        printBreadcrumbs(path, null, null, clazz, referrers, null);
    }
    Collection<JavaHeapObject> objects = Misc.getInstances(clazz, includeSubclasses, referrers);
    if (referee) {
        int size = referrers.size();
        JavaClass prev = size > 1 ? referrers.get(size - 2) : clazz;
        objects = Misc.getRefereesByClass(objects, prev);
    }
    long totalSize = 0;
    long instances = 0;
    for (JavaHeapObject obj : objects) {
        if (newObjects && !obj.isNew())
            continue;
        printThing(obj);
        out.println("<br>");
        totalSize += obj.getSize();
        instances++;
    }
    out.println("<h2>Total of " + instances + " instances occupying " + totalSize + " bytes.</h2>");
    endHtml();
}

From source file:com.palantir.atlasdb.http.TextDelegateDecoder.java

@Override
public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
    Collection<String> contentTypes = response.headers().get(HttpHeaders.CONTENT_TYPE);
    // In the case of multiple content types, or an unknown content type, we'll use the delegate instead.
    if (contentTypes != null && contentTypes.size() == 1
            && Iterables.getOnlyElement(contentTypes, "").equals(MediaType.TEXT_PLAIN)) {
        return stringDecoder.decode(response, type);
    }/* ww  w .j a v a2 s  . c  o  m*/

    return delegate.decode(response, type);
}

From source file:brooklyn.networking.cloudstack.CloudstackNetworking.java

public String findDomainIdForAccount(String accountName) {
    Set<Account> accounts = client.getAccountClient()
            .listAccounts(ListAccountsOptions.Builder.name(accountName));
    Account account = Iterables.getOnlyElement(accounts, null);
    if (account == null) {
        throw new IllegalStateException("No account found in " + loc + "} with name " + accountName);
    }//from w w  w  . j  av  a  2  s .co  m
    return account.getDomainId();
}

From source file:com.github.blacklocus.rdsecho.utl.EchoUtil.java

public Optional<DBInstance> promotedInstance() {
    return Optional.fromNullable(Iterables.getOnlyElement(rdsFind.instances(rdsFind.instanceHasTag(cfg.region(),
            cfg.accountNumber(), getTagEchoStage(), EchoConst.STAGE_PROMOTED)), null));
}

From source file:com.b2international.snowowl.snomed.datastore.SnomedRefSetMemberLookupService.java

@Override
public SnomedRefSetMemberIndexEntry getComponent(final IBranchPath branchPath, final String uuid) {
    return SnomedRequests.prepareSearchMember().setLimit(2).filterById(uuid)
            .build(SnomedDatastoreActivator.REPOSITORY_UUID, branchPath.getPath())
            .execute(ApplicationContext.getServiceForClass(IEventBus.class))
            .then(new Function<SnomedReferenceSetMembers, SnomedRefSetMemberIndexEntry>() {
                @Override//from  ww  w.  j  a  v a  2s.  c o  m
                public SnomedRefSetMemberIndexEntry apply(SnomedReferenceSetMembers input) {
                    final SnomedReferenceSetMember member = Iterables.getOnlyElement(input, null);
                    return member == null ? null : SnomedRefSetMemberIndexEntry.builder(member).build();
                }
            }).getSync();
}

From source file:org.xacml4j.v30.AttributeContainer.java

/**
 * Gets a single {@link Attribute} instance with
 * a given attribute identifier/*from   w  ww . j  a v  a 2  s.  co m*/
 *
 * @param attributeId an attribute identifier
 * @return {@link Attribute} instance or {@code null}
 * if no attribute available with a given identifier
 */
public Attribute getOnlyAttribute(String attributeId) {
    return Iterables.getOnlyElement(attributes.get(attributeId), null);
}

From source file:org.obiba.onyx.quartz.magma.QuestionnaireBeanResolver.java

public Object resolve(Class<?> type, ValueSet valueSet, final Variable variable) {
    QuestionnaireParticipant qp = lookupBean(valueSet, variable);
    if (qp == null) {
        // This happens when the participant did not answer a particular questionnaire
        return null;
    }//ww w .j av  a 2  s  .c  o m
    try {
        if (type.equals(QuestionnaireParticipant.class)) {
            return qp;
        }
        if (type.equals(QuestionAnswer.class)) {
            return lookupQuestionAnswer(valueSet, variable);
        }
        if (type.equals(CategoryAnswer.class)) {
            QuestionAnswer qa = lookupQuestionAnswer(valueSet, variable);
            if (qa != null) {
                if (variable.isRepeatable()) {
                    return qa.getCategoryAnswers();
                }
                // Return the only category present in the list. If there are more than one, this will throw and
                // IllegalArgumentException. If there is no such element, then this will return null
                return Iterables.getOnlyElement(qa.getCategoryAnswers(), null);
            }
        }
        if (type.equals(OpenAnswer.class)) {
            QuestionAnswer qa = lookupQuestionAnswer(valueSet, variable);
            if (qa != null) {
                return findOpenAnswer(findCategoryAnswer(qa, variable.getAttributeStringValue("categoryName")),
                        variable.getAttributeStringValue("openAnswerName"));
            }
        }
        if (type.equals(QuestionnairePageMetricAlgorithm.class)) {
            return Iterables.transform(qp.getQuestionnaireMetrics(),
                    new Function<QuestionnaireMetric, QuestionnairePageMetricAlgorithm>() {
                        @Override
                        public QuestionnairePageMetricAlgorithm apply(QuestionnaireMetric from) {
                            return new QuestionnairePageMetricAlgorithm(getQuestionnaire(variable), from);
                        };
                    });
        }
        if (type.equals(QuestionnaireComment.class)) {
            Iterable<QuestionAnswer> answerComments = Iterables.filter(qp.getParticipantAnswers(),
                    new Predicate<QuestionAnswer>() {
                        @Override
                        public boolean apply(QuestionAnswer input) {
                            return input.getComment() != null;
                        }
                    });
            return Iterables.transform(answerComments, new Function<QuestionAnswer, QuestionnaireComment>() {
                @Override
                public QuestionnaireComment apply(QuestionAnswer from) {
                    return new QuestionnaireComment(getQuestionnaire(variable), from);
                }
            });
        }

    } catch (NoSuchElementException e) {
        // Ignore: it only means that the participant did not answer a particular question or category or open answer
        return null;
    }
    return null;

}

From source file:nz.co.testamation.core.mock.smtp.SmtpMockServerImpl.java

@Override
public SmtpMessageWrapper getReceivedEmail() {
    return Iterables.getOnlyElement(getReceivedEmails(), null);
}

From source file:com.google.idea.blaze.android.run.deployinfo.BlazeApkDeployInfoProtoHelper.java

@Nullable
public BlazeAndroidDeployInfo readDeployInfo(BlazeContext context) {
    File deployInfoFile = Iterables.getOnlyElement(deployInfoFiles, null);
    if (deployInfoFile == null) {
        return null;
    }/*  w ww  .ja va 2 s .  co m*/
    AndroidDeployInfoOuterClass.AndroidDeployInfo deployInfo;
    try (InputStream inputStream = new FileInputStream(deployInfoFile)) {
        deployInfo = AndroidDeployInfoOuterClass.AndroidDeployInfo.parseFrom(inputStream);
    } catch (IOException e) {
        LOG.error(e);
        return null;
    }
    String executionRoot = getExecutionRoot(context);
    if (executionRoot == null) {
        return null;
    }
    BlazeAndroidDeployInfo androidDeployInfo = new BlazeAndroidDeployInfo(project, new File(executionRoot),
            deployInfo);

    List<File> manifestFiles = androidDeployInfo.getManifestFiles();
    ManifestParser.getInstance(project).refreshManifests(manifestFiles);

    return androidDeployInfo;
}