Example usage for com.google.common.base Optional orNull

List of usage examples for com.google.common.base Optional orNull

Introduction

In this page you can find the example usage for com.google.common.base Optional orNull.

Prototype

@Nullable
public abstract T orNull();

Source Link

Document

Returns the contained instance if it is present; null otherwise.

Usage

From source file:org.locationtech.geogig.plumbing.diff.FeatureDiff.java

/**
 * //w  w  w.  j a  va2 s .c om
 * @param path the full path to the feature, including its name
 * @param newRevFeature the new version of the feature
 * @param oldRevFeature the old version of the feature
 * @param newRevFeatureType the new version of the feature type
 * @param oldRevFeatureType the old version of the feature type
 * @param all - true if all attributes should be added regardless of change
 */
public FeatureDiff(String path, @Nullable RevFeature newRevFeature, @Nullable RevFeature oldRevFeature,
        @Nullable RevFeatureType newRevFeatureType, @Nullable RevFeatureType oldRevFeatureType, boolean all) {

    this.path = path;
    this.newRevFeature = newRevFeature;
    this.oldRevFeature = oldRevFeature;
    this.newFeatureType = newRevFeatureType;
    this.oldFeatureType = oldRevFeatureType;
    diffs = new HashMap<PropertyDescriptor, AttributeDiff>();

    if (newRevFeature == null) {
        Preconditions.checkArgument(oldRevFeature != null, "A feature must be provided");
        Preconditions.checkArgument(oldRevFeatureType != null, "Old feature type must be provided.");

        ImmutableList<PropertyDescriptor> oldAttributes = oldRevFeatureType.descriptors();

        for (int i = 0; i < oldAttributes.size(); i++) {
            Optional<Object> oldValue = oldRevFeature.get(i);
            PropertyDescriptor descriptor = oldAttributes.get(i);
            if (Geometry.class.isAssignableFrom(descriptor.getType().getBinding())) {
                diffs.put(descriptor, new GeometryAttributeDiff((Geometry) oldValue.orNull(), (Geometry) null));
            } else {
                diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue.orNull(), null));
            }
        }
    } else if (oldRevFeature == null) {
        Preconditions.checkArgument(newRevFeatureType != null, "New feature type must be provided.");

        ImmutableList<PropertyDescriptor> newAttributes = newRevFeatureType.descriptors();

        for (int i = 0; i < newAttributes.size(); i++) {
            Optional<Object> newValue = newRevFeature.get(i);
            PropertyDescriptor descriptor = newAttributes.get(i);
            if (Geometry.class.isAssignableFrom(descriptor.getType().getBinding())) {
                diffs.put(descriptor, new GeometryAttributeDiff((Geometry) null, (Geometry) newValue.orNull()));
            } else {
                diffs.put(newAttributes.get(i), new GenericAttributeDiffImpl(null, newValue.orNull()));
            }
        }
    } else {
        ImmutableList<PropertyDescriptor> oldAttributes = oldRevFeatureType.descriptors();
        ImmutableList<PropertyDescriptor> newAttributes = newRevFeatureType.descriptors();
        BitSet updatedAttributes = new BitSet(newRevFeature.size());
        for (int i = 0; i < oldAttributes.size(); i++) {
            Optional<Object> oldValue = oldRevFeature.get(i);
            int idx = newAttributes.indexOf(oldAttributes.get(i));
            if (idx != -1) {
                Optional<Object> newValue = newRevFeature.get(idx);
                if (!oldValue.equals(newValue) || all) {
                    if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) {
                        diffs.put(oldAttributes.get(i), new GeometryAttributeDiff((Geometry) oldValue.orNull(),
                                (Geometry) newValue.orNull()));
                    } else {
                        diffs.put(oldAttributes.get(i),
                                new GenericAttributeDiffImpl(oldValue.orNull(), newValue.orNull()));
                    }
                }
                updatedAttributes.set(idx);
            } else {
                if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) {
                    diffs.put(oldAttributes.get(i),
                            new GeometryAttributeDiff((Geometry) oldValue.orNull(), (Geometry) null));
                } else {
                    diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue.orNull(), null));
                }
            }
        }
        updatedAttributes.flip(0, newRevFeature.size());
        for (int i = updatedAttributes.nextSetBit(0); i >= 0; i = updatedAttributes.nextSetBit(i + 1)) {
            PropertyDescriptor descriptor = newAttributes.get(i);
            if (Geometry.class.isAssignableFrom(descriptor.getType().getBinding())) {
                diffs.put(descriptor,
                        new GeometryAttributeDiff((Geometry) null, (Geometry) newRevFeature.get(i).orNull()));
            } else {
                diffs.put(descriptor, new GenericAttributeDiffImpl(null, newRevFeature.get(i).orNull()));
            }
        }
    }

}

From source file:com.on_site.frizzle.debug.LoggingFunction.java

@Override
public Scriptable construct(Context cx, Scriptable scope, Object[] args) {
    Optional<Scriptable> value = null;
    try {//from   w ww  .java 2  s  .com
        value = Optional.fromNullable(func.construct(cx, scope, args));
        return LoggingMixin.instrument(Scriptable.class, "new " + name + "()", value);
    } finally {
        if (value == null) {
            LoggingMixin.log("new {0}({1}) => abrupt", name, printableArgs(args));
        } else {
            LoggingMixin.log("new {0}({1}) => {2}", name, printableArgs(args), value.orNull());
        }
    }
}

From source file:org.locationtech.geogig.osm.internal.OSMUnmapOp.java

@Override
protected RevTree _call() {

    Optional<OSMMappingLogEntry> entry = command(ReadOSMMappingLogEntry.class).setPath(path).call();
    if (entry.isPresent()) {
        Optional<Mapping> opt = command(ReadOSMMapping.class).setEntry(entry.get()).call();
        if (opt.isPresent()) {
            mapping = opt.get();//from  www  .  j  a va  2 s .com
        }
    }

    Iterator<NodeRef> iter = command(LsTreeOp.class).setReference(path).setStrategy(Strategy.FEATURES_ONLY)
            .call();

    FeatureMapFlusher flusher = new FeatureMapFlusher(workingTree());
    while (iter.hasNext()) {
        NodeRef node = iter.next();
        RevFeature revFeature = command(RevObjectParse.class).setObjectId(node.objectId())
                .call(RevFeature.class).get();
        RevFeatureType revFeatureType = command(RevObjectParse.class).setObjectId(node.getMetadataId())
                .call(RevFeatureType.class).get();
        List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors();
        ImmutableList<Optional<Object>> values = revFeature.getValues();
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                (SimpleFeatureType) revFeatureType.type());
        String id = null;
        for (int i = 0; i < descriptors.size(); i++) {
            PropertyDescriptor descriptor = descriptors.get(i);
            if (descriptor.getName().getLocalPart().equals("id")) {
                id = values.get(i).get().toString();
            }
            Optional<Object> value = values.get(i);
            featureBuilder.set(descriptor.getName(), value.orNull());
        }
        Preconditions.checkNotNull(id, "No 'id' attribute found");
        SimpleFeature feature = featureBuilder.buildFeature(id);
        unmapFeature(feature, flusher);

    }

    flusher.flushAll();

    // The above code will unmap all added or modified elements, but not deleted ones.
    // We now process the deletions, by comparing the current state of the mapped tree
    // with its state just after the mapping was created.

    if (entry.isPresent()) {
        Iterator<DiffEntry> diffs = command(DiffTree.class).setPathFilter(path)
                .setNewTree(workingTree().getTree().getId()).setOldTree(entry.get().getPostMappingId()).call();

        while (diffs.hasNext()) {
            DiffEntry diff = diffs.next();
            if (diff.changeType().equals(DiffEntry.ChangeType.REMOVED)) {

                ObjectId featureId = diff.getOldObject().getNode().getObjectId();
                RevFeature revFeature = command(RevObjectParse.class).setObjectId(featureId)
                        .call(RevFeature.class).get();
                RevFeatureType revFeatureType = command(RevObjectParse.class)
                        .setObjectId(diff.getOldObject().getMetadataId()).call(RevFeatureType.class).get();
                List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors();
                ImmutableList<Optional<Object>> values = revFeature.getValues();
                SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                        (SimpleFeatureType) revFeatureType.type());
                String id = null;
                for (int i = 0; i < descriptors.size(); i++) {
                    PropertyDescriptor descriptor = descriptors.get(i);
                    if (descriptor.getName().getLocalPart().equals("id")) {
                        id = values.get(i).get().toString();
                    }
                    Optional<Object> value = values.get(i);
                    featureBuilder.set(descriptor.getName(), value.orNull());
                }
                Preconditions.checkNotNull(id, "No 'id' attribute found");
                SimpleFeature feature = featureBuilder.buildFeature(id);
                Class<?> clazz = feature.getDefaultGeometryProperty().getType().getBinding();
                String deletePath = clazz.equals(Point.class) ? OSMUtils.NODE_TYPE_NAME
                        : OSMUtils.WAY_TYPE_NAME;
                workingTree().delete(deletePath, id);
            }
        }
    }

    return workingTree().getTree();

}

From source file:org.geogig.osm.internal.OSMUnmapOp.java

@Override
protected RevTree _call() {

    Optional<OSMMappingLogEntry> entry = command(ReadOSMMappingLogEntry.class).setPath(path).call();
    if (entry.isPresent()) {
        Optional<Mapping> opt = command(ReadOSMMapping.class).setEntry(entry.get()).call();
        if (opt.isPresent()) {
            mapping = opt.get();//from  w w w .  j a  va2s . com
        }
    }

    Iterator<NodeRef> iter = command(LsTreeOp.class).setReference(path).setStrategy(Strategy.FEATURES_ONLY)
            .call();

    FeatureMapFlusher flusher = new FeatureMapFlusher(repository());
    while (iter.hasNext()) {
        NodeRef node = iter.next();
        RevFeature revFeature = command(RevObjectParse.class).setObjectId(node.getObjectId())
                .call(RevFeature.class).get();
        RevFeatureType revFeatureType = command(RevObjectParse.class).setObjectId(node.getMetadataId())
                .call(RevFeatureType.class).get();
        List<PropertyDescriptor> descriptors = revFeatureType.descriptors();
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                (SimpleFeatureType) revFeatureType.type());
        String id = null;
        for (int i = 0; i < descriptors.size(); i++) {
            PropertyDescriptor descriptor = descriptors.get(i);
            if (descriptor.getName().getLocalPart().equals("id")) {
                id = revFeature.get(i).get().toString();
            }
            Optional<Object> value = revFeature.get(i);
            featureBuilder.set(descriptor.getName(), value.orNull());
        }
        Preconditions.checkNotNull(id, "No 'id' attribute found");
        SimpleFeature feature = featureBuilder.buildFeature(id);
        unmapFeature(feature, flusher);

    }

    flusher.flushAll();

    // The above code will unmap all added or modified elements, but not deleted ones.
    // We now process the deletions, by comparing the current state of the mapped tree
    // with its state just after the mapping was created.

    if (entry.isPresent()) {
        try (AutoCloseableIterator<DiffEntry> diffs = command(DiffTree.class).setPathFilter(path)
                .setNewTree(workingTree().getTree().getId()).setOldTree(entry.get().getPostMappingId())
                .call()) {

            while (diffs.hasNext()) {
                DiffEntry diff = diffs.next();
                if (diff.changeType().equals(DiffEntry.ChangeType.REMOVED)) {

                    ObjectId featureId = diff.getOldObject().getNode().getObjectId();
                    RevFeature revFeature = command(RevObjectParse.class).setObjectId(featureId)
                            .call(RevFeature.class).get();
                    RevFeatureType revFeatureType = command(RevObjectParse.class)
                            .setObjectId(diff.getOldObject().getMetadataId()).call(RevFeatureType.class).get();
                    List<PropertyDescriptor> descriptors = revFeatureType.descriptors();
                    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                            (SimpleFeatureType) revFeatureType.type());
                    String id = null;
                    for (int i = 0; i < descriptors.size(); i++) {
                        PropertyDescriptor descriptor = descriptors.get(i);
                        if (descriptor.getName().getLocalPart().equals("id")) {
                            id = revFeature.get(i).get().toString();
                        }
                        Optional<Object> value = revFeature.get(i);
                        featureBuilder.set(descriptor.getName(), value.orNull());
                    }
                    Preconditions.checkNotNull(id, "No 'id' attribute found");
                    SimpleFeature feature = featureBuilder.buildFeature(id);
                    Class<?> clazz = feature.getDefaultGeometryProperty().getType().getBinding();
                    String deletePath = clazz.equals(Point.class) ? OSMUtils.NODE_TYPE_NAME
                            : OSMUtils.WAY_TYPE_NAME;
                    workingTree().delete(deletePath, id);
                }
            }
        }
    }

    return workingTree().getTree();

}

From source file:org.geogit.osm.history.cli.OSMHistoryImport.java

/**
 * @param primitive/*from w w w.j  a v  a2s  .co  m*/
 * @param thisChangePointCache
 * @return
 */
private Geometry parseGeometry(GeoGIT geogit, Primitive primitive, Map<Long, Coordinate> thisChangePointCache) {

    if (primitive instanceof Relation) {
        return null;
    }

    if (primitive instanceof Node) {
        Optional<Point> location = ((Node) primitive).getLocation();
        return location.orNull();
    }

    final Way way = (Way) primitive;
    final ImmutableList<Long> nodes = way.getNodes();

    StagingArea index = geogit.getRepository().getIndex();

    FeatureBuilder featureBuilder = new FeatureBuilder(NODE_REV_TYPE);
    List<Coordinate> coordinates = Lists.newArrayList(nodes.size());
    FindTreeChild findTreeChild = geogit.command(FindTreeChild.class);
    findTreeChild.setIndex(true);
    ObjectId rootTreeId = geogit.command(ResolveTreeish.class).setTreeish(Ref.HEAD).call().get();
    if (!rootTreeId.isNull()) {
        RevTree headTree = geogit.command(RevObjectParse.class).setObjectId(rootTreeId).call(RevTree.class)
                .get();
        findTreeChild.setParent(headTree);
    }
    for (Long nodeId : nodes) {
        Coordinate coord = thisChangePointCache.get(nodeId);
        if (coord == null) {
            String fid = String.valueOf(nodeId);
            String path = NodeRef.appendChild(NODE_TYPE_NAME, fid);
            Optional<org.geogit.api.Node> ref = index.findStaged(path);
            if (!ref.isPresent()) {
                Optional<NodeRef> nodeRef = findTreeChild.setChildPath(path).call();
                if (nodeRef.isPresent()) {
                    ref = Optional.of(nodeRef.get().getNode());
                } else {
                    ref = Optional.absent();
                }
            }
            if (ref.isPresent()) {
                org.geogit.api.Node nodeRef = ref.get();

                RevFeature revFeature = index.getDatabase().getFeature(nodeRef.getObjectId());
                String id = NodeRef.nodeFromPath(nodeRef.getName());
                Feature feature = featureBuilder.build(id, revFeature);

                Point p = (Point) ((SimpleFeature) feature).getAttribute("location");
                if (p != null) {
                    coord = p.getCoordinate();
                    thisChangePointCache.put(Long.valueOf(nodeId), coord);
                }
            }
        }
        if (coord != null) {
            coordinates.add(coord);
        }
    }
    if (coordinates.size() < 2) {
        return null;
    }
    return GEOMF.createLineString(coordinates.toArray(new Coordinate[coordinates.size()]));
}

From source file:org.locationtech.geogig.porcelain.RemoteListOp.java

/**
 * Executes the remote-list operation./*from   w  w w.  j  a  va  2s  .  c  o m*/
 * 
 * @return {@code List<Remote>} of all remotes found in the config database, may be empty.
 */
@Override
protected ImmutableList<Remote> _call() {
    ConfigDatabase config = configDatabase();
    List<String> remotes = config.getAllSubsections("remote");
    List<Remote> allRemotes = new ArrayList<Remote>();
    for (String remoteName : remotes) {
        String remoteSection = "remote." + remoteName;
        Optional<String> remoteFetchURL = config.get(remoteSection + ".url");
        Optional<String> remoteFetch = config.get(remoteSection + ".fetch");
        Optional<String> remoteMapped = config.get(remoteSection + ".mapped");
        Optional<String> remoteMappedBranch = config.get(remoteSection + ".mappedBranch");
        Optional<String> remoteUserName = config.get(remoteSection + ".username");
        Optional<String> remotePassword = config.get(remoteSection + ".password");
        if (remoteFetchURL.isPresent() && remoteFetch.isPresent()) {
            Optional<String> remotePushURL = config.get(remoteSection + ".pushurl");
            allRemotes.add(new Remote(remoteName, remoteFetchURL.get(), remotePushURL.or(remoteFetchURL.get()),
                    remoteFetch.get(), remoteMapped.or("false").equals("true"), remoteMappedBranch.orNull(),
                    remoteUserName.orNull(), remotePassword.orNull()));
        }
    }
    return ImmutableList.copyOf(allRemotes);
}

From source file:org.locationtech.geogig.web.api.commands.Blame.java

/**
 * Runs the command and builds the appropriate response.
 * //from   w ww .  j a  v  a  2s  .  co m
 * @param context - the context to use for this command
 */
@Override
protected void runInternal(CommandContext context) {
    final Context geogig = this.getRepositoryContext(context);

    Optional<ObjectId> commit = Optional.absent();
    if (branchOrCommit != null) {
        commit = geogig.command(RevParse.class).setRefSpec(branchOrCommit).call();
        if (!commit.isPresent()) {
            throw new CommandSpecException("Could not resolve branch or commit");
        }
    }
    if (path == null) {
        throw new CommandSpecException("Blame requires the path of a feature.");
    }

    try {
        final BlameReport report = geogig.command(BlameOp.class).setPath(path).setCommit(commit.orNull())
                .call();

        context.setResponseContent(new CommandResponse() {
            @Override
            public void write(ResponseWriter out) throws Exception {
                out.start();
                out.writeBlameReport(report);
                out.finish();
            }
        });
    } catch (BlameException e) {
        switch (e.statusCode) {
        case PATH_NOT_FEATURE:
            throw new CommandSpecException("The supplied path does not resolve to a feature");
        case FEATURE_NOT_FOUND:
            throw new CommandSpecException("The supplied path does not exist");
        }
    }
}

From source file:org.locationtech.geogig.geotools.plumbing.ExportOp.java

/**
 * Executes the export operation using the parameters that have been specified.
 * //  www  .j a v  a2  s  .  c o m
 * @return a FeatureCollection with the specified features
 */
@Override
protected SimpleFeatureStore _call() {
    final ObjectDatabase database = objectDatabase();
    if (filterFeatureTypeId != null) {
        RevObject filterType = database.getIfPresent(filterFeatureTypeId);
        checkArgument(filterType instanceof RevFeatureType, "Provided filter feature type is does not exist");
    }

    final SimpleFeatureStore targetStore = getTargetStore();

    final String refspec = resolveRefSpec();
    final String treePath = refspec.substring(refspec.indexOf(':') + 1);
    final RevTree rootTree = resolveRootTree(refspec);
    final NodeRef typeTreeRef = resolTypeTreeRef(refspec, treePath, rootTree);

    final ObjectId defaultMetadataId = typeTreeRef.getMetadataId();

    final RevTree typeTree = database.getTree(typeTreeRef.objectId());

    final ProgressListener progressListener = getProgressListener();

    progressListener.started();
    progressListener
            .setDescription("Exporting from " + path + " to " + targetStore.getName().getLocalPart() + "... ");

    final Iterator<SimpleFeature> filtered;
    {
        final Iterator<SimpleFeature> plainFeatures = getFeatures(typeTree, database,

                defaultMetadataId, progressListener);

        Iterator<SimpleFeature> adaptedFeatures = adaptToArguments(plainFeatures, defaultMetadataId);

        Iterator<Optional<Feature>> transformed = Iterators.transform(adaptedFeatures, ExportOp.this.function);

        Iterator<SimpleFeature> result = Iterators
                .filter(Iterators.transform(transformed, new Function<Optional<Feature>, SimpleFeature>() {
                    @Override
                    public SimpleFeature apply(Optional<Feature> input) {
                        return (SimpleFeature) input.orNull();
                    }
                }), Predicates.notNull());

        // check the resulting schema has something to contribute
        PeekingIterator<SimpleFeature> peekingIt = Iterators.peekingIterator(result);
        if (peekingIt.hasNext()) {
            Function<AttributeDescriptor, String> toString = new Function<AttributeDescriptor, String>() {
                @Override
                public String apply(AttributeDescriptor input) {
                    return input.getLocalName();
                }
            };
            SimpleFeature peek = peekingIt.peek();
            Set<String> sourceAtts = new HashSet<String>(
                    Lists.transform(peek.getFeatureType().getAttributeDescriptors(), toString));
            Set<String> targetAtts = new HashSet<String>(
                    Lists.transform(targetStore.getSchema().getAttributeDescriptors(), toString));
            if (Sets.intersection(sourceAtts, targetAtts).isEmpty()) {
                throw new GeoToolsOpException(StatusCode.UNABLE_TO_ADD,
                        "No common attributes between source and target feature types");
            }
        }

        filtered = peekingIt;
    }
    FeatureCollection<SimpleFeatureType, SimpleFeature> asFeatureCollection = new BaseFeatureCollection<SimpleFeatureType, SimpleFeature>() {

        @Override
        public FeatureIterator<SimpleFeature> features() {

            return new DelegateFeatureIterator<SimpleFeature>(filtered);
        }
    };

    // add the feature collection to the feature store
    final Transaction transaction;
    if (transactional) {
        transaction = new DefaultTransaction("create");
    } else {
        transaction = Transaction.AUTO_COMMIT;
    }
    try {
        targetStore.setTransaction(transaction);
        try {
            targetStore.addFeatures(asFeatureCollection);
            transaction.commit();
        } catch (final Exception e) {
            if (transactional) {
                transaction.rollback();
            }
            Throwables.propagateIfInstanceOf(e, GeoToolsOpException.class);
            throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
        } finally {
            transaction.close();
        }
    } catch (IOException e) {
        throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
    }

    progressListener.complete();

    return targetStore;

}

From source file:com.facebook.buck.rules.CachingBuildEngine.java

/**
 * This method is invoked once all of this rule's dependencies are built.
 * <p>/*w  w  w.  ja  v a 2 s .  c o m*/
 * This method should be executed on a fresh Runnable in BuildContext's ListeningExecutorService,
 * so there is no reason to schedule new work in a new Runnable.
 * <p>
 * All exit paths through this method should resolve {@link #results} before exiting. To
 * that end, this method should never throw an exception, or else Buck will hang waiting for
 * {@link #results} to be resolved.
 *
 * @param shouldTryToFetchFromCache Making requests to Cassandra can be expensive, so we do not
 *      attempt to fetch from the cache if any of the transitive dependencies gets rebuilt.
 */
private BuildResult buildOnceDepsAreBuilt(BuildRule rule, final BuildContext context,
        OnDiskBuildInfo onDiskBuildInfo, BuildInfoRecorder buildInfoRecorder,
        boolean shouldTryToFetchFromCache) {
    // Compute the current RuleKey and compare it to the one stored on disk.
    RuleKey ruleKey = rule.getRuleKey();
    Optional<RuleKey> cachedRuleKey = onDiskBuildInfo.getRuleKey();

    // If the RuleKeys match, then there is nothing to build.
    if (ruleKey.equals(cachedRuleKey.orNull())) {
        context.logBuildInfo("[UNCHANGED %s]", rule.getFullyQualifiedName());
        return new BuildResult(BuildRuleSuccess.Type.MATCHING_RULE_KEY, CacheResult.LOCAL_KEY_UNCHANGED_HIT);
    }

    // Deciding whether we need to rebuild is tricky business. We want to rebuild as little as
    // possible while always being sound.
    //
    // For java_library rules that depend only on their first-order deps,
    // they only need to rebuild themselves if any of the following conditions hold:
    // (1) The definition of the build rule has changed.
    // (2) Any of the input files (which includes resources as well as .java files) have changed.
    // (3) The ABI of any of its dependent java_library rules has changed.
    //
    // For other types of build rules, we have to be more conservative when rebuilding. In those
    // cases, we rebuild if any of the following conditions hold:
    // (1) The definition of the build rule has changed.
    // (2) Any of the input files have changed.
    // (3) Any of the RuleKeys of this rule's deps have changed.
    //
    // Because a RuleKey for a rule will change if any of its transitive deps have changed, that
    // means a change in one of the leaves can result in almost all rules being rebuilt, which is
    // slow. Fortunately, we limit the effects of this when building Java code when checking the ABI
    // of deps instead of the RuleKey for deps.
    AbiRule abiRule = checkIfRuleOrBuildableIsAbiRule(rule);
    if (abiRule != null) {
        RuleKey ruleKeyNoDeps = rule.getRuleKeyWithoutDeps();
        Optional<RuleKey> cachedRuleKeyNoDeps = onDiskBuildInfo.getRuleKeyWithoutDeps();
        if (ruleKeyNoDeps.equals(cachedRuleKeyNoDeps.orNull())) {
            // The RuleKey for the definition of this build rule and its input files has not changed.
            // Therefore, if the ABI of its deps has not changed, there is nothing to rebuild.
            Sha1HashCode abiKeyForDeps = abiRule.getAbiKeyForDeps();
            Optional<Sha1HashCode> cachedAbiKeyForDeps = onDiskBuildInfo
                    .getHash(ABI_KEY_FOR_DEPS_ON_DISK_METADATA);
            if (abiKeyForDeps.equals(cachedAbiKeyForDeps.orNull())) {
                return new BuildResult(BuildRuleSuccess.Type.MATCHING_DEPS_ABI_AND_RULE_KEY_NO_DEPS,
                        CacheResult.LOCAL_KEY_UNCHANGED_HIT);
            }
        }
    }

    CacheResult cacheResult;
    if (shouldTryToFetchFromCache) {
        // Before deciding to build, check the ArtifactCache.
        // The fetched file is now a ZIP file, so it needs to be unzipped.
        cacheResult = tryToFetchArtifactFromBuildCacheAndOverlayOnTopOfProjectFilesystem(rule,
                buildInfoRecorder, context.getArtifactCache(), context.getProjectRoot(), context);
    } else {
        cacheResult = CacheResult.SKIP;
    }

    // Run the steps to build this rule since it was not found in the cache.
    if (cacheResult.isSuccess()) {
        return new BuildResult(BuildRuleSuccess.Type.FETCHED_FROM_CACHE, cacheResult);
    }

    // The only remaining option is to build locally.
    try {
        executeCommandsNowThatDepsAreBuilt(rule, context, onDiskBuildInfo, buildInfoRecorder);
    } catch (Exception e) {
        return new BuildResult(e);
    }

    return new BuildResult(BuildRuleSuccess.Type.BUILT_LOCALLY, cacheResult);
}

From source file:org.apache.beam.runners.dataflow.worker.DataflowWorkUnitClient.java

/**
 * Gets a {@link WorkItem} from the Dataflow service, or returns {@link Optional#absent()} if no
 * work was found.// w  w w  . ja va  2 s  .co  m
 *
 * <p>If work is returned, the calling thread should call reportWorkItemStatus after completing it
 * and before requesting another work item.
 */
@Override
public Optional<WorkItem> getWorkItem() throws IOException {
    List<String> workItemTypes = ImmutableList.of(WORK_ITEM_TYPE_MAP_TASK, WORK_ITEM_TYPE_SEQ_MAP_TASK,
            WORK_ITEM_TYPE_REMOTE_SOURCE_TASK);
    // All remote sources require the "remote_source" capability. Dataflow's
    // custom sources are further tagged with the format "custom_source".
    List<String> capabilities = ImmutableList.<String>of(options.getWorkerId(), CAPABILITY_REMOTE_SOURCE,
            PropertyNames.CUSTOM_SOURCE_FORMAT);

    Optional<WorkItem> workItem = getWorkItemInternal(workItemTypes, capabilities);
    if (!workItem.isPresent()) {
        // Normal case, this means that the response contained no work, i.e. no work is available
        // at this time.
        return Optional.absent();
    }
    if (workItem.isPresent() && workItem.get().getId() == null) {
        logger.warn("Discarding invalid work item {}", workItem.orNull());
        return Optional.absent();
    }

    WorkItem work = workItem.get();

    final String stage;
    if (work.getMapTask() != null) {
        stage = work.getMapTask().getStageName();
        logger.info("Starting MapTask stage {}", stage);
    } else if (work.getSeqMapTask() != null) {
        stage = work.getSeqMapTask().getStageName();
        logger.info("Starting SeqMapTask stage {}", stage);
    } else if (work.getSourceOperationTask() != null) {
        stage = work.getSourceOperationTask().getStageName();
        logger.info("Starting SourceOperationTask stage {}", stage);
    } else {
        stage = null;
    }
    DataflowWorkerLoggingMDC.setStageName(stage);

    stageStartTime.set(DateTime.now());
    DataflowWorkerLoggingMDC.setWorkId(Long.toString(work.getId()));

    return workItem;
}