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:eu.stratosphere.sopremo.cleansing.mapping.SpicyUtil.java

public static EvaluationExpression valueForLeaf(IValueGenerator generator, VariablePathExpression targetPath,
        FORule tgd, MappingTask mappingTask) {
    if (generator instanceof NullValueGenerator)
        return ConstantExpression.NULL;
    if (generator instanceof FunctionGenerator) {
        VariableCorrespondence correspondence = XQUtility.findCorrespondenceFromTargetPathWithSameId(targetPath,
                tgd.getCoveredCorrespondences());
        EvaluationExpression expr = ((SopremoFunctionExpression) ((FunctionGenerator) generator).getFunction())
                .getExpr().clone();//w ww  . j  av  a 2  s.  c o m
        if (correspondence == null || correspondence.isConstant())
            return expr;
        List<VariablePathExpression> sourcePaths = correspondence.getSourcePaths();
        for (int index = 0; index < sourcePaths.size(); index++)
            expr = expr.replace(new InputSelection(index), new ObjectAccess(nameForPath(sourcePaths.get(index)))
                    .withInputExpression(new InputSelection(0)));
        return expr;
    }
    if (generator instanceof SkolemFunctionGenerator) {
        SkolemFunctionGenerator skolemGenerator = (SkolemFunctionGenerator) generator;
        if (generator.getSubGenerators().size() > 0) {
            Collection<EvaluationExpression> expressions = new TreeSet<EvaluationExpression>(
                    new Comparator<EvaluationExpression>() {
                        @Override
                        public int compare(EvaluationExpression o1, EvaluationExpression o2) {
                            return o1.toString().compareTo(o2.toString());
                        }
                    });
            skolemString(skolemGenerator, mappingTask, expressions);
            if (expressions.size() == 1)
                return Iterables.getFirst(expressions, null);
            for (int index = 1; index < expressions.size(); index += 2)
                expressions.add(new ConstantExpression("|"));
            return FunctionUtil.createFunctionCall(CoreFunctions.CONCAT, new ArrayCreation(expressions));
        }
        return new ConstantExpression(skolemGenerator.getName());
        // SkolemFunctionGenerator skolemGenerator = (SkolemFunctionGenerator) generator;
        // StringBuilder result = new StringBuilder();
        //
        // result.append(XQUtility.XQUERY_FUNCTION).append("(\"").append(removeRootLabel(skolemGenerator.getName())).append("\", (");
        // if (generator.getSubGenerators().size() > 0) {
        // String skolemString = new XQSkolemHandler().skolemString(skolemGenerator, mappingTask, false).toString();
        // result.append(skolemString);
        // }
        // result.append("))");
        // return result.toString();
    }
    throw new UnsupportedOperationException();
}

From source file:brooklyn.config.render.RendererHints.java

@SuppressWarnings("rawtypes")
private static Object _applyDisplayValueHint(Object target, Object initialValue, boolean includeClass) {
    Iterable<RendererHints.DisplayValue> hints = RendererHints._getHintsFor(target,
            RendererHints.DisplayValue.class);
    if (Iterables.size(hints) > 1) {
        log.warn("Multiple display value hints set for {}; Only one will be applied, using first", target);
    }//from w ww  .  j  av a 2 s  .  co  m

    Optional<RendererHints.DisplayValue> hint = Optional.fromNullable(Iterables.getFirst(hints, null));
    Object value = hint.isPresent() ? hint.get().getDisplayValue(initialValue) : initialValue;
    if (includeClass && value != null && !(value instanceof String) && !(value instanceof Number)
            && !(value.getClass().isPrimitive())) {
        value = _applyDisplayValueHint(value.getClass(), value, false);
    }
    return value;
}

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

@Override
public Long findPictureIdByHash(final String hash) {
    Assert.hasText(hash, "Picture hash should be supplied !");

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

        @Override//from   ww w. ja v  a2s.  co m
        @SuppressWarnings("unchecked")
        protected Long executeWithEntityManager(final EntityManager em) throws PersistenceException {
            final Query findByHashQuery = em.createNamedQuery(Picture.FIND_PICTURE_ID_BY_HASH);
            findByHashQuery.setParameter("hash", hash);

            final Long pictureId = Iterables.getFirst(findByHashQuery.getResultList(), null);
            return pictureId;
        }
    };

    return emCallback.getReturnedValue();
}

From source file:org.sonatype.nexus.repository.storage.MetadataNodeEntityAdapter.java

T findByProperty(final ODatabaseDocumentTx db, final String propName, final Object propValue,
        final Bucket bucket) {
    checkNotNull(propName);/*  w  w  w .j  a  v  a  2 s  .  c om*/
    checkNotNull(propValue);
    checkNotNull(bucket);

    Map<String, Object> parameters = ImmutableMap.of("bucket", bucketEntityAdapter.recordIdentity(bucket),
            "propValue", propValue);
    String query = String.format("select from %s where %s = :bucket and %s = :propValue", getTypeName(),
            P_BUCKET, propName);
    Iterable<ODocument> docs = db.command(new OCommandSQL(query)).execute(parameters);
    ODocument first = Iterables.getFirst(docs, null);
    return first != null ? readEntity(first) : null;
}

From source file:br.com.caelum.vraptor.ioc.guice.GuiceComponentRegistry.java

private Constructor getConstructor(Class componentType) {
    Constructor[] constructors = componentType.getDeclaredConstructors();
    Iterable<Constructor> filteredConstructor = Iterables.filter(Lists.newArrayList(constructors),
            new Predicate<Constructor>() {

                public boolean apply(Constructor constructor) {
                    return constructor.isAnnotationPresent(Inject.class);
                }//from w w  w .j a  v  a2s  .co m

            });
    return Iterables.getFirst(filteredConstructor, constructors[0]);
}

From source file:com.facebook.swift.generator.SwiftGenerator.java

private String extractThriftNamespace(final URI thriftUri) {
    final String path = thriftUri.getPath();
    final String filename = Iterables.getLast(Splitter.on('/').split(path), null);
    Preconditions.checkState(filename != null, "No thrift namespace found in %s", thriftUri);

    final String name = Iterables.getFirst(Splitter.on('.').split(filename), null);
    Preconditions.checkState(name != null, "No thrift namespace found in %s", thriftUri);
    return name;// w ww .  j  a v  a  2s.  c o  m
}

From source file:io.cloudsoft.cloudera.brooklynnodes.DirectClouderaManagerImpl.java

@Override
protected void postDriverStart() {
    super.postDriverStart();
    String cmHost;/*from   www . ja  v  a 2 s.  c  o m*/
    if (getConfig(ClouderaManagerNode.USE_IP_ADDRESS)) {
        cmHost = getAttribute(ADDRESS);
    } else {
        cmHost = getAttribute(HOSTNAME);
    }
    try {
        TempCloudUtils.authorizePing(new Cidr(), Iterables.getFirst(getLocations(), null));
    } catch (Throwable t) {
        log.warn("can't setup firewall/ping: " + t, t);
    }

    setAttribute(CLOUDERA_MANAGER_HOSTNAME, cmHost);
    setAttribute(CLOUDERA_MANAGER_URL, "http://" + cmHost + ":7180/");

    if (!Repeater
            .create(MutableMap.of("timeout", 5 * 60 * 1000, "description",
                    "Waiting for successful REST call to " + this))
            .rethrowException().repeat().every(1, TimeUnit.SECONDS).until(new Callable<Boolean>() {
                public Boolean call() {
                    resetRestCaller();
                    return (getRestCaller().getClusters() != null);
                }
            }).run()) {
        throw new IllegalStateException("Timeout waiting for successful REST call to ${this}");
    }
    log.debug("Detected REST online for DirectCM " + this);
    //TODO accept default license / configurable license ? (is just a gui thing though...)

    //TODO change password on server, ensure RestCallers are reset to use right password
}

From source file:com.davidbracewell.text.morphology.EnglishLemmatizer.java

@Override
public String lemmatize(String string) {
    return Iterables.getFirst(getBaseForms(string), string);
}

From source file:com.ibm.common.geojson.BoundingBox.java

@SuppressWarnings("unchecked")
protected static BoundingBox calculateBoundingBoxGeometries(Iterable<Geometry<?, ?>> geometries) {
    ImmutableSortedSet.Builder<Float> xset = ImmutableSortedSet.naturalOrder();
    ImmutableSortedSet.Builder<Float> yset = ImmutableSortedSet.naturalOrder();
    ImmutableSortedSet.Builder<Float> zset = ImmutableSortedSet.naturalOrder();
    for (Geometry<?, ?> geo : geometries) {
        switch (geo.type()) {
        case POINT:
            Point point = (Point) geo;
            Position position = Iterables.getFirst(point.coordinates(), null);
            xset.add(position.northing());
            yset.add(position.easting());
            if (position.hasAltitude())
                zset.add(position.altitude());
            break;
        case LINESTRING:
        case MULTIPOINT:
            addValues(xset, yset, zset, (Iterable<Position>) geo);
            break;
        case MULTILINESTRING:
        case POLYGON:
            addValuesLineString(xset, yset, zset, (Iterable<LineString>) geo);
            break;
        case MULTIPOLYGON:
            addValuesPolygon(xset, yset, zset, (Iterable<Polygon>) geo);
            break;
        default://from w  w  w . j a v  a  2  s .  c  om
            break;
        }
    }
    return buildBoundingBox(xset.build(), yset.build(), zset.build());
}

From source file:com.google.template.soy.SoyMsgExtractor.java

private void execMain(String[] args) throws IOException, SoySyntaxException {

    final CmdLineParser cmdLineParser = MainClassUtils.parseFlags(this, args, USAGE_PREFIX);

    final Function<String, Void> exitWithErrorFn = new Function<String, Void>() {
        @Override//from  w  ww .j av  a 2  s . co  m
        public Void apply(String errorMsg) {
            MainClassUtils.exitWithError(errorMsg, cmdLineParser, USAGE_PREFIX);
            return null;
        }
    };

    Injector injector = MainClassUtils.createInjector(messagePluginModule, null);

    SoyFileSet.Builder sfsBuilder = injector.getInstance(SoyFileSet.Builder.class);
    MainClassUtils.addSoyFilesToBuilder(sfsBuilder, inputPrefix, srcs, arguments, ImmutableList.<String>of(),
            ImmutableList.<String>of(), exitWithErrorFn);
    sfsBuilder.setAllowExternalCalls(allowExternalCalls);

    File outputFile0;
    if (outputPathFormat.length() != 0) {
        if (outputFile.length() != 0) {
            exitWithErrorFn.apply("Must provide one of output file path or output path format.");
        }
        String inputFilePath = inputPrefix + (Iterables.getFirst(srcs, arguments.get(0)));
        String outputFilePath = MainEntryPointUtils.buildFilePath(outputPathFormat, null, inputFilePath,
                inputPrefix);
        outputFile0 = new File(outputFilePath);
    } else if (outputFile.length() != 0) {
        outputFile0 = new File(outputFile);
    } else {
        exitWithErrorFn.apply("Must provide output file path or output path format.");
        return;
    }

    SoyFileSet sfs = sfsBuilder.build();

    SoyMsgBundle msgBundle = sfs.extractMsgs();

    SoyMsgBundleHandler msgBundleHandler = injector.getInstance(SoyMsgBundleHandler.class);
    OutputFileOptions options = new OutputFileOptions();
    options.setSourceLocaleString(sourceLocaleString);
    if (targetLocaleString.length() > 0) {
        options.setTargetLocaleString(targetLocaleString);
    }
    msgBundleHandler.writeToExtractedMsgsFile(msgBundle, options, outputFile0);
}