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:com.google.gitiles.LogServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    GitilesView view = ViewFilter.getView(req);
    Repository repo = ServletUtils.getRepository(req);
    RevWalk walk = null;/* w  w w.j a va  2 s .  c  o m*/
    try {
        try {
            walk = newWalk(repo, view);
        } catch (IncorrectObjectTypeException e) {
            res.setStatus(SC_NOT_FOUND);
            return;
        }

        Optional<ObjectId> start = getStart(view.getParameters(), walk.getObjectReader());
        if (start == null) {
            res.setStatus(SC_NOT_FOUND);
            return;
        }

        Map<String, Object> data = Maps.newHashMapWithExpectedSize(5);

        if (!view.getRevision().nameIsId()) {
            List<Map<String, Object>> tags = Lists.newArrayListWithExpectedSize(1);
            for (RevObject o : RevisionServlet.listObjects(walk, view.getRevision().getId())) {
                if (o instanceof RevTag) {
                    tags.add(new TagSoyData(linkifier, req).toSoyData((RevTag) o));
                }
            }
            if (!tags.isEmpty()) {
                data.put("tags", tags);
            }
        }

        Paginator paginator = new Paginator(walk, limit, start.orNull());
        Map<AnyObjectId, Set<Ref>> refsById = repo.getAllRefsByPeeledObjectId();
        List<Map<String, Object>> entries = Lists.newArrayListWithCapacity(limit);
        for (RevCommit c : paginator) {
            entries.add(new CommitSoyData(null, req, repo, walk, view, refsById).toSoyData(c, KeySet.SHORTLOG));
        }

        String title = "Log - ";
        if (view.getOldRevision() != Revision.NULL) {
            title += view.getRevisionRange();
        } else {
            title += view.getRevision().getName();
        }

        data.put("title", title);
        data.put("entries", entries);
        ObjectId next = paginator.getNextStart();
        if (next != null) {
            data.put("nextUrl", copyAndCanonicalize(view).replaceParam(START_PARAM, next.name()).toUrl());
        }
        ObjectId prev = paginator.getPreviousStart();
        if (prev != null) {
            GitilesView.Builder prevView = copyAndCanonicalize(view);
            if (!prevView.getRevision().getId().equals(prev)) {
                prevView.replaceParam(START_PARAM, prev.name());
            }
            data.put("previousUrl", prevView.toUrl());
        }

        render(req, res, "gitiles.logDetail", data);
    } catch (RevWalkException e) {
        log.warn("Error in rev walk", e);
        res.setStatus(SC_INTERNAL_SERVER_ERROR);
        return;
    } finally {
        if (walk != null) {
            walk.release();
        }
    }
}

From source file:org.locationtech.geogig.storage.bdbje.JEObjectDatabase.java

@Nullable
private Transaction newTransaction() {
    final boolean transactional = objectDb.getConfig().getTransactional();
    if (transactional) {
        TransactionConfig txConfig = new TransactionConfig();
        txConfig.setReadUncommitted(true);
        Optional<String> durability = configDB.get(OBJECT_DURABILITY_CONFIG_KEY);
        if (!durability.isPresent()) {
            durability = configDB.getGlobal(OBJECT_DURABILITY_CONFIG_KEY);
        }/*w ww.  j  av  a 2s . c o  m*/
        if ("safe".equals(durability.orNull())) {
            txConfig.setDurability(Durability.COMMIT_SYNC);
        } else {
            txConfig.setDurability(Durability.COMMIT_WRITE_NO_SYNC);
        }
        Transaction transaction = env.beginTransaction(null, txConfig);
        return transaction;
    }
    return null;
}

From source file:org.n52.sos.ds.hibernate.util.procedure.HibernateProcedureConverter.java

/**
 * Create procedure description from XML text stored in ValidProcedureTime
 * table/*from  w w  w  .  j  av a  2  s .  c o  m*/
 *
 * @param procedure
 *            Hibernate procedure entity
 * @param vpt
 *            Hibernate ValidProcedureTime entity
 * @param version
 *            Requested SOS version
 * @param session
 *            Hibernate session
 *
 * @return created SosProcedureDescription
 *
 * @throws OwsExceptionReport
 *             If an error occurs
 */
public SosProcedureDescription createSosProcedureDescriptionFromValidProcedureTime(Procedure procedure,
        String requestedDescriptionFormat, ValidProcedureTime vpt, String version, Locale i18n, Session session)
        throws OwsExceptionReport {
    if (vpt != null) {
        checkOutputFormatWithDescriptionFormat(procedure.getIdentifier(), vpt, requestedDescriptionFormat,
                getFormat(vpt));
    } else {
        checkOutputFormatWithDescriptionFormat(procedure.getIdentifier(), procedure, requestedDescriptionFormat,
                getFormat(procedure));
    }
    Optional<SosProcedureDescription> description = create(procedure, requestedDescriptionFormat, vpt, i18n,
            session);
    if (description.isPresent()) {
        addHumanReadableName(description.get(), procedure);
        enrich(description.get(), procedure, version, requestedDescriptionFormat, getValidTime(vpt), null, i18n,
                session);
        if (!requestedDescriptionFormat.equals(description.get().getDescriptionFormat())) {
            SosProcedureDescription converted = convert(description.get().getDescriptionFormat(),
                    requestedDescriptionFormat, description.get());
            converted.setDescriptionFormat(requestedDescriptionFormat);
            return converted;
        }
    }
    return description.orNull();
}

From source file:com.android.tools.idea.npw.TemplateParameterStep2.java

@Override
public void init() {
    super.init();
    if (mySourceProviders.length > 0) {
        myState.put(AddAndroidActivityPath.KEY_SOURCE_PROVIDER, mySourceProviders[0]);
        myState.put(AddAndroidActivityPath.KEY_SOURCE_PROVIDER_NAME, mySourceProviders[0].getName());
    }//from w w  w  .  j a  va2 s  .  c  o  m
    register(AddAndroidActivityPath.KEY_SELECTED_TEMPLATE, (JComponent) myTemplateDescription.getParent(),
            new ComponentBinding<TemplateEntry, JComponent>() {
                @Override
                public void setValue(@Nullable TemplateEntry newValue, @NotNull JComponent component) {
                    setSelectedTemplate(newValue);
                }
            });
    register(KEY_DESCRIPTION, myFooterSeparator, new ComponentBinding<String, JSeparator>() {
        @Override
        public void setValue(@Nullable String newValue, @NotNull JSeparator component) {
            component.setVisible(!StringUtil.isEmpty(newValue));
        }
    });
    register(KEY_TEMPLATE_ICON, myTemplateIcon, new ComponentBinding<File, JLabel>() {
        @Override
        public void setValue(@Nullable File newValue, @NotNull JLabel component) {
            Optional<Icon> thumbnail = newValue == null ? Optional.absent()
                    : myThumbnailsCache.getUnchecked(newValue);
            Icon icon = thumbnail.orNull();
            component.setIcon(icon);
            component.setVisible(icon != null);
        }
    });
    registerValueDeriver(KEY_TEMPLATE_ICON, new ValueDeriver<File>() {
        @Nullable
        @Override
        public File deriveValue(@NotNull ScopedStateStore state, @Nullable Key changedKey,
                @Nullable File currentValue) {
            return getTemplateIconPath(state.get(AddAndroidActivityPath.KEY_SELECTED_TEMPLATE));
        }
    });
    registerValueDeriver(AddAndroidActivityPath.KEY_SOURCE_PROVIDER_NAME, new ValueDeriver<String>() {
        @Nullable
        @Override
        public String deriveValue(@NotNull ScopedStateStore state, @Nullable Key changedKey,
                @Nullable String currentValue) {
            SourceProvider sourceProvider = state.get(AddAndroidActivityPath.KEY_SOURCE_PROVIDER);
            return sourceProvider == null ? null : sourceProvider.getName();
        }
    });
}

From source file:com.android.camera.one.v2.OneCameraZslImpl.java

private void savePicture(Image image, final PhotoCaptureParameters captureParams, CaptureSession session,
        CaptureResult result) {//from  ww w . j  a va 2 s  . co  m
    int heading = captureParams.heading;
    int degrees = CameraUtil.getJpegRotation(captureParams.orientation, mCharacteristics);

    ExifInterface exif = new ExifInterface();
    // TODO: Add more exif tags here.

    Size size = getImageSizeForOrientation(image.getWidth(), image.getHeight(), degrees);

    exif.setTag(exif.buildTag(ExifInterface.TAG_PIXEL_X_DIMENSION, size.getWidth()));
    exif.setTag(exif.buildTag(ExifInterface.TAG_PIXEL_Y_DIMENSION, size.getHeight()));

    exif.setTag(exif.buildTag(ExifInterface.TAG_ORIENTATION, ExifInterface.Orientation.TOP_LEFT));

    // Set GPS heading direction based on sensor, if location is on.
    if (heading >= 0) {
        ExifTag directionRefTag = exif.buildTag(ExifInterface.TAG_GPS_IMG_DIRECTION_REF,
                ExifInterface.GpsTrackRef.MAGNETIC_DIRECTION);
        ExifTag directionTag = exif.buildTag(ExifInterface.TAG_GPS_IMG_DIRECTION, new Rational(heading, 1));
        exif.setTag(directionRefTag);
        exif.setTag(directionTag);
    }
    new ExifUtil(exif).populateExif(Optional.<TaskImageContainer.TaskImage>absent(),
            Optional.of((CaptureResultProxy) new AndroidCaptureResultProxy(result)),
            Optional.<Location>absent());
    ListenableFuture<Optional<Uri>> futureUri = session.saveAndFinish(acquireJpegBytes(image, degrees),
            size.getWidth(), size.getHeight(), 0, exif);
    Futures.addCallback(futureUri, new FutureCallback<Optional<Uri>>() {
        @Override
        public void onSuccess(Optional<Uri> uriOptional) {
            captureParams.callback.onPictureSaved(uriOptional.orNull());
        }

        @Override
        public void onFailure(Throwable throwable) {
            captureParams.callback.onPictureSaved(null);
        }
    });
}

From source file:org.geogit.api.plumbing.diff.DiffTreeWalk.java

public Iterator<DiffEntry> get() {

    RevTree oldTree = this.fromRootTree;
    RevTree newTree = this.toRootTree;

    Optional<NodeRef> oldObjectRef = getFilteredObjectRef(fromRootTree);
    Optional<NodeRef> newObjectRef = getFilteredObjectRef(toRootTree);
    boolean pathFiltering = !pathFilter.isEmpty();
    if (pathFiltering && pathFilter.size() == 1) {
        if (Objects.equal(oldObjectRef, newObjectRef)) {
            // filter didn't match anything
            return Iterators.emptyIterator();
        }//ww w . j a  va 2  s  .c o m

        TYPE oldObjectType = oldObjectRef.isPresent() ? oldObjectRef.get().getType() : null;
        TYPE newObjectType = newObjectRef.isPresent() ? newObjectRef.get().getType() : null;

        checkState(
                oldObjectType == null || newObjectType == null || Objects.equal(oldObjectType, newObjectType));

        final TYPE type = oldObjectType == null ? newObjectType : oldObjectType;
        switch (type) {
        case FEATURE:
            return Iterators.singletonIterator(new DiffEntry(oldObjectRef.orNull(), newObjectRef.orNull()));
        case TREE:
            if (oldObjectRef.isPresent()) {
                oldTree = objectDb.getTree(oldObjectRef.get().objectId());
            } else {
                oldTree = null;
            }
            if (newObjectRef.isPresent()) {
                newTree = objectDb.getTree(newObjectRef.get().objectId());
            } else {
                newTree = null;
            }
            break;
        default:
            throw new IllegalStateException("Only FEATURE or TREE objects expected at this stage: " + type);
        }

    }

    NodeRef oldRef, newRef;

    oldRef = oldObjectRef.orNull();
    newRef = newObjectRef.orNull();

    // TODO: pass pathFilter to TreeDiffEntryIterator so it ignores inner trees where the path
    // is guaranteed not to be present
    Iterator<DiffEntry> iterator = new TreeDiffEntryIterator(oldRef, newRef, oldTree, newTree, reportTrees,
            recursive, objectDb);

    // boolean comparingTree = (oldRef == null ? newRef : oldRef).getType().equals(TYPE.TREE);
    // if (reportTrees && comparingTree && !Objects.equal(oldRef, newRef)) {
    // DiffEntry self = new DiffEntry(oldRef, newRef);
    // iterator = Iterators.concat(Iterators.singletonIterator(self), iterator);
    // }

    if (pathFiltering) {
        iterator = Iterators.filter(iterator, new Predicate<DiffEntry>() {
            @Override
            public boolean apply(@Nullable DiffEntry input) {
                String oldPath = input.oldPath();
                String newPath = input.newPath();
                for (String path : pathFilter) {
                    boolean apply = (oldPath != null && oldPath.startsWith(path))
                            || (newPath != null && newPath.startsWith(path));
                    if (apply) {
                        return true;
                    }
                }
                return false;
            }
        });
    }
    return iterator;
}

From source file:com.android.tools.idea.wizard.TemplateParameterStep2.java

@Override
public void init() {
    super.init();
    if (mySourceProviders.length > 0) {
        myState.put(AddAndroidActivityPath.KEY_SOURCE_PROVIDER, mySourceProviders[0]);
        myState.put(AddAndroidActivityPath.KEY_SOURCE_PROVIDER_NAME, mySourceProviders[0].getName());
    }//from w  ww.  j  a v  a  2 s  .  c  om
    register(AddAndroidActivityPath.KEY_SELECTED_TEMPLATE, (JComponent) myTemplateDescription.getParent(),
            new ComponentBinding<TemplateEntry, JComponent>() {
                @Override
                public void setValue(@Nullable TemplateEntry newValue, @NotNull JComponent component) {
                    setSelectedTemplate(newValue);
                }
            });
    register(KEY_DESCRIPTION, myFooterSeparator, new ComponentBinding<String, JSeparator>() {
        @Override
        public void setValue(@Nullable String newValue, @NotNull JSeparator component) {
            component.setVisible(!StringUtil.isEmpty(newValue));
        }
    });
    register(KEY_TEMPLATE_ICON, myTemplateIcon, new ComponentBinding<File, JLabel>() {
        @Override
        public void setValue(@Nullable File newValue, @NotNull JLabel component) {
            Optional<Icon> thumbnail = newValue == null ? Optional.<Icon>absent()
                    : myThumbnailsCache.getUnchecked(newValue);
            Icon icon = thumbnail.orNull();
            component.setIcon(icon);
            component.setVisible(icon != null);
        }
    });
    registerValueDeriver(KEY_TEMPLATE_ICON, new ValueDeriver<File>() {
        @Nullable
        @Override
        public File deriveValue(@NotNull ScopedStateStore state, @Nullable Key changedKey,
                @Nullable File currentValue) {
            return getTemplateIconPath(state.get(AddAndroidActivityPath.KEY_SELECTED_TEMPLATE));
        }
    });
    registerValueDeriver(AddAndroidActivityPath.KEY_SOURCE_PROVIDER_NAME, new ValueDeriver<String>() {
        @Nullable
        @Override
        public String deriveValue(@NotNull ScopedStateStore state, @Nullable Key changedKey,
                @Nullable String currentValue) {
            SourceProvider sourceProvider = state.get(AddAndroidActivityPath.KEY_SOURCE_PROVIDER);
            return sourceProvider == null ? null : sourceProvider.getName();
        }
    });
}

From source file:com.twitter.nodes.Node.java

/**
 * Convert a node to a future "safely". This will mask all possible failures in the wrapped node,
 * including:/*w w w.j av  a  2s. c  o  m*/
 * - non-NullableNode returning a null value
 * - exception thrown inside node
 * - any of node's further dependency's failure
 * all of them will turn into Future.value(null).
 * <p>
 * If you do not want to mask failures below, you should directly use .apply(). If current node
 * is nullable (inherit from NullableNode, or canEmitNull() returns true), it can return
 * Future.value(null) properly; if current node is not nullable, or there is an exception thrownm
 * this will become a Future exception.
 */
public final Future<Resp> toFutureSafe() {
    return Node.optional(this).apply().map(new com.twitter.util.Function<Optional<Resp>, Resp>() {
        @Override
        public Resp apply(Optional<Resp> response) {
            return response.orNull();
        }
    });
}

From source file:it.f2informatica.pagination.utils.SafeGetterMethodExecutor.java

private <T> Object _invokeGetter(String fieldName, T entity)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    Optional<Object> result = Optional.absent();
    for (String field : fieldName.split("_")) {
        if (fieldName.endsWith(".") || 0 == field.length()) {
            throw new IllegalArgumentException("Invalid property name '" + fieldName + "'");
        }/*from  ww  w  .  j  a v a 2 s .co m*/

        Method getter = entity.getClass().getMethod("get" + StringUtils.capitalize(field));
        result = Optional.fromNullable(getter.invoke(entity));

        if (!result.isPresent()) {
            break;
        } else if (!field.equals(fieldName)) {
            // If the current field is not equals to the nested
            // field properties, then it will call itself until
            // reach the last property (via Recursive Call).
            // On the other hand, fieldName.substring(field.length() + 1)
            // means that I'm passing the entire nested field path
            // to the next recursive call, except the current property
            // evaluated considering also the 'dot'.
            // For example, if we have "someProperty." (will be excluded)
            return _invokeGetter(fieldName.substring(field.length() + 1), result.get());
        }
    }
    return result.orNull(); // Holds the final result from the last getter method
}

From source file:org.sourcepit.tpmp.resolver.tycho.AbstractTychoTargetPlatformResolver.java

private void handlePluginsAndFeatures(MavenSession session, MavenProject project,
        final DependencyArtifacts platformArtifacts, final Set<String> explodedBundles,
        TargetPlatformResolutionHandler resolutionHandler) {
    // map original rector projects to their versioned id. needed to recognize and re-map reactor artifacts later
    final Map<String, MavenProject> vidToProjectMap = projectFacade.createVidToProjectMap(session);

    for (ArtifactDescriptor artifact : platformArtifacts.getArtifacts(PackagingType.TYPE_ECLIPSE_FEATURE)) {
        final Optional<MavenProject> mavenProject = projectFacade.getMavenProject(vidToProjectMap, artifact);

        final File location = projectFacade.getLocation(artifact, mavenProject);

        if (project.getBasedir().equals(location)) {
            continue;
        }//from  w w w  .  j a  va  2s . c om

        // due to the feature model of Tycho violates the specified behaviour of the "unpack" attribute, we have to
        // parse the feature.xml on our own. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=386851.
        final Document feature = loadFeature(location);
        for (Node pluginNode : XmlUtils.queryNodes(feature, "/feature/plugin")) {
            final Element plugin = (Element) pluginNode;
            if (isUnpack(plugin)) {
                explodedBundles.add(getId(plugin));
            }
        }

        final ArtifactKey key = projectFacade.getArtifactKey(artifact, mavenProject);
        resolutionHandler.handleFeature(key.getId(), key.getVersion(), location, mavenProject.orNull());
    }

    for (ArtifactDescriptor artifact : platformArtifacts.getArtifacts()) {
        // Pre Tycho 0.20.0 source artifacts was typed as "eclipse-repository"... Now source artifacts are
        // eclipse-plugins. Because of we will resolve sources later, ignore it here.
        if (!"sources".equals(artifact.getClassifier())) {
            final Optional<MavenProject> mavenProject = projectFacade.getMavenProject(vidToProjectMap,
                    artifact);
            final File location = projectFacade.getLocation(artifact, mavenProject);
            if (project.getBasedir().equals(location)) {
                continue;
            }

            final ArtifactKey key = projectFacade.getArtifactKey(artifact, mavenProject);
            final String type = key.getType();
            if (PackagingType.TYPE_ECLIPSE_PLUGIN.equals(type)
                    || PackagingType.TYPE_ECLIPSE_TEST_PLUGIN.equals(type)) {
                final boolean explodedBundle = isExplodedBundle(key.getId(), location, explodedBundles);
                resolutionHandler.handlePlugin(key.getId(), key.getVersion(), location, explodedBundle,
                        mavenProject.orNull());
            }
        }
    }
}