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:com.cinchapi.concourse.importer.JsonImporter.java

/**
 * Given a string of JSON data, upsert it into Concourse.
 * //from   www.  java 2 s. c o m
 * @param json
 * @return the records that were affected by the import
 */
protected Set<Long> upsertJsonString(String json) {
    // TODO call concourse.upsert(json) when method is ready
    // NOTE: The following implementation is very inefficient, but will
    // suffice until the upsert functionality is available
    Set<Long> records = Sets.newHashSet();
    for (Multimap<String, Object> data : Convert.anyJsonToJava(json)) {
        Long record = MoreObjects.firstNonNull(
                (Long) Iterables.getOnlyElement(data.get(Constants.JSON_RESERVED_IDENTIFIER_NAME), null),
                Time.now());
        data.removeAll(Constants.JSON_RESERVED_IDENTIFIER_NAME);
        for (String key : data.keySet()) {
            for (Object value : data.get(key)) {
                concourse.add(key, value, record);
            }
        }
        records.add(record);
    }
    return records;
}

From source file:ratpack.configuration.internal.DefaultConfigurationFactoryFactory.java

@Override
public ConfigurationFactory build(ConfigurationSource configurationSource) throws ConfigurationException {
    TypeCoercingProperties props = LaunchConfigsInternal.consolidatePropertiesFromGlobalProperties(
            StandardSystemProperty.USER_DIR.value(), classLoader, configurationSource.getOverrideProperties(),
            configurationSource.getDefaultProperties());
    try {/* www . java2s  . co  m*/
        Class<ConfigurationFactory> configurationFactoryClass = props.asClass(CONFIGURATION_FACTORY,
                ConfigurationFactory.class);
        if (configurationFactoryClass != null) {
            return configurationFactoryClass.newInstance();
        }
    } catch (ReflectiveOperationException ex) {
        throw new ConfigurationException("Could not instantiate specified configuration factory class "
                + props.asString(CONFIGURATION_FACTORY, null), ex);
    }
    ServiceLoader<ConfigurationFactory> serviceLoader = ServiceLoader.load(ConfigurationFactory.class,
            classLoader);
    try {
        return Iterables.getOnlyElement(serviceLoader, new DefaultConfigurationFactory());
    } catch (IllegalArgumentException ex) {
        throw new ConfigurationException(
                "Multiple possible configuration factories were found; please specify one with the '"
                        + CONFIGURATION_FACTORY + "' property",
                ex);
    }
}

From source file:org.janusgraph.graphdb.types.vertices.RelationTypeVertex.java

public InternalRelationType getBaseType() {
    Entry entry = Iterables.getOnlyElement(getRelated(TypeDefinitionCategory.RELATIONTYPE_INDEX, Direction.IN),
            null);// w ww  .jav a2  s .  co  m
    if (entry == null)
        return null;
    assert entry.getSchemaType() instanceof InternalRelationType;
    return (InternalRelationType) entry.getSchemaType();
}

From source file:org.summer.dsl.xannotation.typesystem.XbaseWithAnnotationsTypeComputer.java

protected void _computeTypes(XAnnotation object, ITypeComputationState state) {
    JvmType annotationType = object.getAnnotationType();
    if (annotationType != null && !annotationType.eIsProxy()) {
        if (annotationType instanceof JvmAnnotationType) {
            XExpression expression = object.getValue();
            if (expression != null) {
                Iterable<JvmFeature> iterable = ((JvmAnnotationType) annotationType)
                        .findAllFeaturesByName("value");
                JvmFeature value = Iterables.getOnlyElement(iterable, null);
                if (value != null) {
                    if (value instanceof JvmOperation) {
                        computeTypes(object, (JvmOperation) value, expression, state);
                    } else {
                        throw new IllegalStateException("Unexpected feature type " + value);
                    }/*from   ww  w  .  j a  v  a2 s .  c  o  m*/
                } else {
                    state.addDiagnostic(
                            new EObjectDiagnosticImpl(Severity.ERROR, IssueCodes.ANNOTATIONS_NO_VALUE_ATTRIBUTE,
                                    "The attribute value is undefined for the annotation type "
                                            + annotationType.getSimpleName(),
                                    object, XannotationPackage.Literals.XANNOTATION__VALUE, -1, null));
                    state.withNonVoidExpectation().computeTypes(expression);
                }
            } else {
                List<XAnnotationElementValuePair> valuePairs = object.getElementValuePairs();
                for (XAnnotationElementValuePair pair : valuePairs) {
                    computeTypes(object, pair.getElement(), pair.getValue(), state);
                }
            }
        } else {
            state.addDiagnostic(new EObjectDiagnosticImpl(Severity.ERROR, IssueCodes.INCOMPATIBLE_TYPES,
                    String.format("Type mismatch: cannot convert from %s to Annotation",
                            annotationType.getSimpleName()),
                    object, XannotationPackage.Literals.XANNOTATION__ANNOTATION_TYPE, -1, null));
            computeChildTypesForUnknownAnnotation(object, state);
        }
        state.acceptActualType(new ParameterizedTypeReference(state.getReferenceOwner(), annotationType));
    } else {
        computeChildTypesForUnknownAnnotation(object, state);
    }
}

From source file:com.twitter.aurora.scheduler.http.StructDump.java

/**
 * Dumps a task struct./*from   w  w  w.  ja  va  2 s.  c  om*/
 *
 * @return HTTP response.
 */
@GET
@Path("/task/{task}")
@Produces(MediaType.TEXT_HTML)
public Response dumpJob(@PathParam("task") final String taskId) {

    return dumpEntity("Task " + taskId, new Work.Quiet<Optional<? extends TBase<?, ?>>>() {
        @Override
        public Optional<? extends TBase<?, ?>> apply(StoreProvider storeProvider) {
            // Deep copy the struct to sidestep any subclass trickery inside the storage system.
            return Optional.fromNullable(Iterables
                    .getOnlyElement(storeProvider.getTaskStore().fetchTasks(Query.taskScoped(taskId)), null)
                    .newBuilder());
        }
    });
}

From source file:org.obiba.opal.core.service.OpalGeneralConfigServiceImpl.java

@Nullable
private ODocument getDocument(ODatabaseDocument db) {
    String className = OpalGeneralConfig.class.getSimpleName();
    if (db.getMetadata().getSchema().getClass(className) == null) {
        return null;
    }/*from  w  w  w.  j a v a2 s.co  m*/
    return Iterables.getOnlyElement(db.browseClass(className), null);
}

From source file:org.eclipse.xtext.xbase.annotations.typesystem.XbaseWithAnnotationsTypeComputer.java

protected void _computeTypes(XAnnotation object, ITypeComputationState state) {
    JvmType annotationType = object.getAnnotationType();
    if (annotationType != null && !annotationType.eIsProxy()) {
        if (annotationType instanceof JvmAnnotationType) {
            XExpression expression = object.getValue();
            if (expression != null) {
                Iterable<JvmFeature> iterable = ((JvmAnnotationType) annotationType)
                        .findAllFeaturesByName("value");
                JvmFeature value = Iterables.getOnlyElement(iterable, null);
                if (value != null) {
                    if (value instanceof JvmOperation) {
                        computeTypes(object, (JvmOperation) value, expression, state);
                    } else {
                        throw new IllegalStateException("Unexpected feature type " + value);
                    }/* w w w . j a v a2 s .  com*/
                } else {
                    state.addDiagnostic(
                            new EObjectDiagnosticImpl(Severity.ERROR, IssueCodes.ANNOTATIONS_NO_VALUE_ATTRIBUTE,
                                    "The attribute value is undefined for the annotation type "
                                            + annotationType.getSimpleName(),
                                    object, XAnnotationsPackage.Literals.XANNOTATION__VALUE, -1, null));
                    state.withNonVoidExpectation().computeTypes(expression);
                }
            } else {
                List<XAnnotationElementValuePair> valuePairs = object.getElementValuePairs();
                if (valuePairs.isEmpty()) {
                    Iterable<JvmFeature> iterable = ((JvmAnnotationType) annotationType)
                            .findAllFeaturesByName("value");
                    JvmFeature value = Iterables.getOnlyElement(iterable, null);
                    if (value != null) {
                        if (value instanceof JvmOperation) {
                            computeTypes(object, (JvmOperation) value, null, state);
                        } else {
                            throw new IllegalStateException("Unexpected feature type " + value);
                        }
                    }
                } else {
                    for (XAnnotationElementValuePair pair : valuePairs) {
                        computeTypes(object, pair.getElement(), pair.getValue(), state);
                    }
                }
            }
        } else {
            state.addDiagnostic(new EObjectDiagnosticImpl(Severity.ERROR, IssueCodes.INCOMPATIBLE_TYPES,
                    String.format("Type mismatch: cannot convert from %s to Annotation",
                            annotationType.getSimpleName()),
                    object, XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE, -1, null));
            computeChildTypesForUnknownAnnotation(object, state);
        }
        state.acceptActualType(state.getReferenceOwner().newParameterizedTypeReference(annotationType));
    } else {
        computeChildTypesForUnknownAnnotation(object, state);
    }
}