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.android.camera.one.v2.OneCameraImpl.java

private void saveJpegPicture(byte[] jpegData, final PhotoCaptureParameters captureParams,
        CaptureSession session, CaptureResult result) {
    int heading = captureParams.heading;
    int width = 0;
    int height = 0;
    int rotation = 0;
    ExifInterface exif = null;/*from   w  w  w  . j  a  v  a 2s . c  o  m*/
    try {
        exif = new ExifInterface();
        exif.readExif(jpegData);

        Integer w = exif.getTagIntValue(ExifInterface.TAG_PIXEL_X_DIMENSION);
        width = (w == null) ? width : w;
        Integer h = exif.getTagIntValue(ExifInterface.TAG_PIXEL_Y_DIMENSION);
        height = (h == null) ? height : h;

        // Get image rotation from EXIF.
        rotation = Exif.getOrientation(exif);

        // 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());
    } catch (IOException e) {
        Log.w(TAG, "Could not read exif from gcam jpeg", e);
        exif = null;
    }
    ListenableFuture<Optional<Uri>> futureUri = session.saveAndFinish(jpegData, width, height, rotation, 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:com.eucalyptus.auth.policy.PolicyParser.java

/**
 * The algorithm of decomposing the actions and resources of a statement into authorizations:
 * 1. Group actions into different vendors.
 * 2. Group resources into different resource types.
 * 3. Permute all combinations of action groups and resource groups, matching them by the same
 *    vendors./*from   ww w  .  j av a  2s  . co  m*/
 */
private List<AuthorizationEntity> decomposeStatement(final String effect, final String actionElement,
        final List<String> actions, final String resourceElement, final List<String> resources) {
    // Group actions by vendor
    final SetMultimap<String, String> actionMap = HashMultimap.create();
    for (String action : actions) {
        action = normalize(action);
        final String vendor = checkAction(action);
        actionMap.put(vendor, action);
    }
    // Group resources by type, key is a pair of (optional) account + resource type
    final SetMultimap<Pair<Optional<String>, String>, String> resourceMap = HashMultimap.create();
    for (final String resource : resources) {
        final Ern ern = Ern.parse(resource);
        resourceMap.put(Pair.lopair(Strings.emptyToNull(ern.getNamespace()), ern.getResourceType()),
                ern.getResourceName());
    }
    final boolean notAction = PolicySpec.NOTACTION.equals(actionElement);
    final boolean notResource = PolicySpec.NOTRESOURCE.equals(resourceElement);
    // Permute action and resource groups and construct authorizations.
    final List<AuthorizationEntity> results = Lists.newArrayList();
    for (final Map.Entry<String, Collection<String>> actionSetEntry : actionMap.asMap().entrySet()) {
        final String vendor = actionSetEntry.getKey();
        final Set<String> actionSet = (Set<String>) actionSetEntry.getValue();
        boolean added = false;
        for (final Map.Entry<Pair<Optional<String>, String>, Collection<String>> resourceSetEntry : resourceMap
                .asMap().entrySet()) {
            final Optional<String> accountIdOrName = resourceSetEntry.getKey().getLeft();
            final String type = resourceSetEntry.getKey().getRight();
            final Set<String> resourceSet = (Set<String>) resourceSetEntry.getValue();
            if (PolicySpec.ALL_ACTION.equals(vendor) || PolicySpec.ALL_RESOURCE.equals(type)
                    || PolicySpec.isPermittedResourceVendor(vendor, PolicySpec.vendor(type))) {
                results.add(new AuthorizationEntity(EffectType.valueOf(effect), accountIdOrName.orNull(), type,
                        actionSet, notAction, resourceSet, notResource));
                added = true;
            }
        }
        if (!added) {
            results.add(new AuthorizationEntity(EffectType.valueOf(effect), actionSet, notAction));
        }
    }
    return results;
}

From source file:com.arpnetworking.tsdcore.scripting.lua.LuaExpression.java

private Quantity convertToQuantity(final LuaValue result) throws ScriptingException {
    if (result.isnumber()) {
        // Construct and return a unit-less Quantity
        return new Quantity.Builder().setValue(result.todouble()).build();

    } else if (result.istable()) {
        // Extract and validate the value
        final LuaValue value = result.get("value");
        value.checknumber();//w  w w. j  ava  2 s . c om

        // Extract and validate the optional unit
        final LuaValue unitName = result.get("unit");
        if (!LuaValue.NIL.equals(unitName)) {
            unitName.checkstring();
        }

        // Determine the unit
        final Optional<Unit> unit = LuaValue.NIL.equals(unitName) ? Optional.<Unit>absent()
                : Optional.of(Unit.valueOf(unitName.tojstring()));

        // Construct and return the Quantity
        return new Quantity.Builder().setValue(result.get("value").todouble()).setUnit(unit.orNull()).build();
    } else if (result.isuserdata(LuaQuantity.class)) {
        // Coerce the Java instance
        @SuppressWarnings("unchecked")
        final LuaQuantity quantity = (LuaQuantity) CoerceLuaToJava.coerce(result, LuaQuantity.class);

        // Return the Quantity
        return quantity.getQuantity();
    }

    throw new ScriptingException(String.format("Script returned an unsupported value; result=%s", result));
}

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

@Nullable
private Image getImage(int cell) {
    Object elementAt = myModel.getElementAt(cell);
    if (elementAt == null) {
        return null;
    } else {/*from  w w  w . j a va 2  s. c o  m*/
        try {
            @SuppressWarnings("unchecked")
            Optional<Image> image = myImagesCache.get((E) elementAt);
            return image.orNull();
        } catch (ExecutionException e) {
            Logger.getInstance(getClass()).error(e);
            return null;
        }
    }
}

From source file:org.jclouds.vsphere.compute.config.VSphereComputeServiceAdapter.java

private ResourcePool tryFindResourcePool(Folder folder, String hostname) {
    Iterable<ResourcePool> resourcePools = ImmutableSet.<ResourcePool>of();
    try {/*w w  w.  ja v  a2  s.  c om*/
        ManagedEntity[] resourcePoolEntities = new InventoryNavigator(folder)
                .searchManagedEntities("ResourcePool");
        resourcePools = Iterables.transform(Arrays.asList(resourcePoolEntities),
                new Function<ManagedEntity, ResourcePool>() {
                    public ResourcePool apply(ManagedEntity input) {
                        return (ResourcePool) input;
                    }
                });
        Optional<ResourcePool> optionalResourcePool = Iterables.tryFind(resourcePools,
                VSpherePredicate.isResourcePoolOf(hostname));
        return optionalResourcePool.orNull();
    } catch (Exception e) {
        logger.error("Problem in finding a valid resource pool", e);
    }
    return null;
}

From source file:cloud.sync.solutions.ImportLocationInDatabase.java

@Override
public void applyTo(Problem problem) throws SolutionException {
    checkArgument(isSolutionFor(problem));
    LocationProblems.LocationNotInDatabase locationNotInDatabase = (LocationProblems.LocationNotInDatabase) problem;

    Location existingLocation = locationModelService
            .getByRemoteId(SlashEncodedId.of(locationNotInDatabase.getResource().id()).cloudId());
    if (existingLocation != null) {
        existingLocation.addCloudCredential(locationNotInDatabase.getResource().credential());
        return;// w  w w  .j  ava 2  s.c  o m
    }

    Cloud cloud = locationNotInDatabase.getResource().cloud();
    Optional<Location> parent;
    if (locationNotInDatabase.getResource().parent().isPresent()) {
        parent = Optional.fromNullable(locationModelService.getByRemoteId(
                SlashEncodedId.of(locationNotInDatabase.getResource().parent().get().id()).cloudId()));
        if (!parent.isPresent()) {
            throw new SolutionException(String.format("Could not import %s as parent %s was not found.",
                    locationNotInDatabase.getResource(), locationNotInDatabase.getResource().parent().get()));
        }
    } else {
        parent = Optional.absent();
    }

    Location location = new Location(locationNotInDatabase.getResource().cloudId(),
            locationNotInDatabase.getResource().providerId(), locationNotInDatabase.getResource().swordId(),
            cloud, locationNotInDatabase.getResource().name(), null, parent.orNull(),
            locationNotInDatabase.getResource().locationScope(),
            locationNotInDatabase.getResource().isAssignable());

    this.locationModelService.save(location);
}

From source file:org.locationtech.geogig.plumbing.merge.ReportCommitConflictsOp.java

@Override
protected MergeScenarioReport _call() {

    Preconditions.checkArgument(consumer != null, "No consumer provided.");

    MergeScenarioReport report = new MergeScenarioReport();

    ObjectId parentCommitId = ObjectId.NULL;
    if (commit.getParentIds().size() > 0) {
        parentCommitId = commit.getParentIds().get(0);
    }// w  w w .  j a v a2  s  .  co m
    ObjectId parentTreeId = ObjectId.NULL;
    Repository repository = repository();
    if (repository.commitExists(parentCommitId)) {
        parentTreeId = repository.getCommit(parentCommitId).getTreeId();
    }
    // get changes
    try (AutoCloseableIterator<DiffEntry> diffs = command(DiffTree.class).setOldTree(parentTreeId)
            .setNewTree(commit.getTreeId()).setReportTrees(true).call()) {
        while (diffs.hasNext()) {
            DiffEntry diff = diffs.next();
            String path = diff.oldPath() == null ? diff.newPath() : diff.oldPath();
            Optional<RevObject> obj = command(RevObjectParse.class).setRefSpec(Ref.HEAD + ":" + path).call();
            switch (diff.changeType()) {
            case ADDED:
                if (obj.isPresent()) {
                    TYPE type = command(ResolveObjectType.class).setObjectId(diff.getNewObject().getObjectId())
                            .call();
                    if (TYPE.TREE.equals(type)) {
                        NodeRef headVersion = command(FindTreeChild.class).setChildPath(path)
                                .setParent(repository.getOrCreateHeadTree()).call().get();
                        if (!headVersion.getMetadataId().equals(diff.getNewObject().getMetadataId())) {
                            consumer.conflicted(new Conflict(path, ObjectId.NULL,
                                    diff.getNewObject().getMetadataId(), headVersion.getMetadataId()));
                            report.addConflict();
                        }
                    } else {
                        if (!obj.get().getId().equals(diff.newObjectId())) {
                            consumer.conflicted(
                                    new Conflict(path, ObjectId.NULL, diff.newObjectId(), obj.get().getId()));
                            report.addConflict();
                        }
                    }
                } else {
                    consumer.unconflicted(diff);
                    report.addUnconflicted();
                }
                break;
            case REMOVED:
                if (obj.isPresent()) {
                    if (obj.get().getId().equals(diff.oldObjectId())) {
                        consumer.unconflicted(diff);
                        report.addUnconflicted();
                    } else {
                        consumer.conflicted(
                                new Conflict(path, diff.oldObjectId(), ObjectId.NULL, obj.get().getId()));
                        report.addConflict();
                    }
                }
                break;
            case MODIFIED:
                TYPE type = command(ResolveObjectType.class).setObjectId(diff.getNewObject().getObjectId())
                        .call();
                if (TYPE.TREE.equals(type)) {
                    // TODO:see how to do this. For now, we will pass any change as a conflicted
                    // one
                    if (!diff.isChange()) {
                        consumer.unconflicted(diff);
                        report.addUnconflicted();
                    }
                } else {
                    String refSpec = Ref.HEAD + ":" + path;
                    obj = command(RevObjectParse.class).setRefSpec(refSpec).call();
                    if (!obj.isPresent()) {
                        // git reports this as a conflict but does not mark as conflicted, just
                        // adds
                        // the missing file.
                        // We add it and consider it unconflicted
                        consumer.unconflicted(diff);
                        report.addUnconflicted();
                        break;
                    }
                    RevFeature feature = (RevFeature) obj.get();
                    DepthSearch depthSearch = new DepthSearch(repository.objectDatabase());
                    Optional<NodeRef> noderef = depthSearch.find(this.workingTree().getTree(), path);
                    RevFeatureType featureType = command(RevObjectParse.class)
                            .setObjectId(noderef.get().getMetadataId()).call(RevFeatureType.class).get();
                    ImmutableList<PropertyDescriptor> descriptors = featureType.descriptors();
                    FeatureDiff featureDiff = command(DiffFeature.class)
                            .setOldVersion(Suppliers.ofInstance(diff.getOldObject()))
                            .setNewVersion(Suppliers.ofInstance(diff.getNewObject())).call();
                    Set<Entry<PropertyDescriptor, AttributeDiff>> attrDiffs = featureDiff.getDiffs().entrySet();
                    RevFeature newFeature = command(RevObjectParse.class).setObjectId(diff.newObjectId())
                            .call(RevFeature.class).get();
                    boolean ok = true;
                    for (Iterator<Entry<PropertyDescriptor, AttributeDiff>> iterator = attrDiffs
                            .iterator(); iterator.hasNext() && ok;) {
                        Entry<PropertyDescriptor, AttributeDiff> entry = iterator.next();
                        AttributeDiff attrDiff = entry.getValue();
                        PropertyDescriptor descriptor = entry.getKey();
                        switch (attrDiff.getType()) {
                        case ADDED:
                            if (descriptors.contains(descriptor)) {
                                ok = false;
                            }
                            break;
                        case REMOVED:
                        case MODIFIED:
                            if (!descriptors.contains(descriptor)) {
                                ok = false;
                                break;
                            }
                            for (int i = 0; i < descriptors.size(); i++) {
                                if (descriptors.get(i).equals(descriptor)) {
                                    Optional<Object> value = feature.get(i);
                                    Optional<Object> newValue = newFeature.get(i);
                                    if (!newValue.equals(value)) { // if it's going to end up
                                                                   // setting the same value, it
                                                                   // is
                                                                   // compatible, so no need to
                                                                   // check
                                        if (!attrDiff.canBeAppliedOn(value.orNull())) {
                                            ok = false;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (ok) {
                        consumer.unconflicted(diff);
                        report.addUnconflicted();
                    } else {
                        consumer.conflicted(
                                new Conflict(path, diff.oldObjectId(), diff.newObjectId(), obj.get().getId()));
                        report.addConflict();
                    }
                }

                break;
            }

        }
    }
    consumer.finished();

    return report;

}

From source file:com.qcadoo.mes.orders.hooks.OrderHooks.java

private Optional<String> generateTechnologyNumberFor(final Entity order) {
    OrderType orderType = OrderType.of(order);
    Optional<Entity> maybeTechnologyPrototype = Optional.absent();
    if (OrderType.WITH_PATTERN_TECHNOLOGY == orderType) {
        maybeTechnologyPrototype = Optional
                .fromNullable(order.getBelongsToField(OrderFields.TECHNOLOGY_PROTOTYPE));
    }// w w  w.j av a 2 s . co m
    return Optional.fromNullable(
            technologyServiceO.generateNumberForTechnologyInOrder(order, maybeTechnologyPrototype.orNull()));
}

From source file:springfox.documentation.swagger.readers.operation.SwaggerResponseMessageReader.java

protected Set<ResponseMessage> read(OperationContext context) {
    ResolvedType defaultResponse = context.getReturnType();
    Optional<ApiOperation> operationAnnotation = context.findAnnotation(ApiOperation.class);
    Optional<ResolvedType> operationResponse = operationAnnotation
            .transform(resolvedTypeFromOperation(typeResolver, defaultResponse));
    Optional<ResponseHeader[]> defaultResponseHeaders = operationAnnotation.transform(responseHeaders());
    Map<String, Header> defaultHeaders = newHashMap();
    if (defaultResponseHeaders.isPresent()) {
        defaultHeaders.putAll(headers(defaultResponseHeaders.get()));
    }// w w w.  j av  a 2  s .com

    List<ApiResponses> allApiResponses = context.findAllAnnotations(ApiResponses.class);
    Set<ResponseMessage> responseMessages = newHashSet();

    Map<Integer, ApiResponse> seenResponsesByCode = newHashMap();
    for (ApiResponses apiResponses : allApiResponses) {
        ApiResponse[] apiResponseAnnotations = apiResponses.value();
        for (ApiResponse apiResponse : apiResponseAnnotations) {
            if (!seenResponsesByCode.containsKey(apiResponse.code())) {
                seenResponsesByCode.put(apiResponse.code(), apiResponse);
                ModelContext modelContext = returnValue(apiResponse.response(), context.getDocumentationType(),
                        context.getAlternateTypeProvider(), context.getGenericsNamingStrategy(),
                        context.getIgnorableParameterTypes());
                Optional<ModelReference> responseModel = Optional.absent();
                Optional<ResolvedType> type = resolvedType(null, apiResponse);
                if (isSuccessful(apiResponse.code())) {
                    type = type.or(operationResponse);
                }
                if (type.isPresent()) {
                    responseModel = Optional.of(modelRefFactory(modelContext, typeNameExtractor)
                            .apply(context.alternateFor(type.get())));
                }
                Map<String, Header> headers = newHashMap(defaultHeaders);
                headers.putAll(headers(apiResponse.responseHeaders()));

                responseMessages.add(
                        new ResponseMessageBuilder().code(apiResponse.code()).message(apiResponse.message())
                                .responseModel(responseModel.orNull()).headersWithDescription(headers).build());
            }
        }
    }
    if (operationResponse.isPresent()) {
        ModelContext modelContext = returnValue(operationResponse.get(), context.getDocumentationType(),
                context.getAlternateTypeProvider(), context.getGenericsNamingStrategy(),
                context.getIgnorableParameterTypes());
        ResolvedType resolvedType = context.alternateFor(operationResponse.get());

        ModelReference responseModel = modelRefFactory(modelContext, typeNameExtractor).apply(resolvedType);
        context.operationBuilder().responseModel(responseModel);
        ResponseMessage defaultMessage = new ResponseMessageBuilder().code(httpStatusCode(context))
                .message(message(context)).responseModel(responseModel).build();
        if (!responseMessages.contains(defaultMessage) && !"void".equals(responseModel.getType())) {
            responseMessages.add(defaultMessage);
        }
    }
    return responseMessages;
}

From source file:org.eclipse.buildship.ui.wizard.project.ProjectImportWizardController.java

public ProjectImportWizardController(IWizard projectImportWizard) {
    // assemble configuration object that serves as the data model of the wizard
    Validator<File> projectDirValidator = Validators
            .requiredDirectoryValidator(ProjectWizardMessages.Label_ProjectRootDirectory);
    Validator<GradleDistributionWrapper> gradleDistributionValidator = GradleDistributionValidator
            .gradleDistributionValidator();
    Validator<Boolean> applyWorkingSetsValidator = Validators.nullValidator();
    Validator<List<String>> workingSetsValidator = Validators.nullValidator();

    this.configuration = new ProjectImportConfiguration(projectDirValidator, gradleDistributionValidator,
            applyWorkingSetsValidator, workingSetsValidator);

    // initialize values from the persisted dialog settings
    IDialogSettings dialogSettings = projectImportWizard.getDialogSettings();
    Optional<File> projectDir = FileUtils.getAbsoluteFile(dialogSettings.get(SETTINGS_KEY_PROJECT_DIR));
    Optional<String> gradleDistributionType = Optional
            .fromNullable(Strings.emptyToNull(dialogSettings.get(SETTINGS_KEY_GRADLE_DISTRIBUTION_TYPE)));
    Optional<String> gradleDistributionConfiguration = Optional.fromNullable(
            Strings.emptyToNull(dialogSettings.get(SETTINGS_KEY_GRADLE_DISTRIBUTION_CONFIGURATION)));
    boolean applyWorkingSets = dialogSettings.get(SETTINGS_KEY_APPLY_WORKING_SETS) != null
            && dialogSettings.getBoolean(SETTINGS_KEY_APPLY_WORKING_SETS);
    List<String> workingSets = ImmutableList
            .copyOf(CollectionsUtils.nullToEmpty(dialogSettings.getArray(SETTINGS_KEY_WORKING_SETS)));

    this.configuration.setProjectDir(projectDir.orNull());
    this.configuration.setGradleDistribution(
            createGradleDistribution(gradleDistributionType, gradleDistributionConfiguration));
    this.configuration.setApplyWorkingSets(applyWorkingSets);
    this.configuration.setWorkingSets(workingSets);

    // store the values every time they change
    saveFilePropertyWhenChanged(dialogSettings, SETTINGS_KEY_PROJECT_DIR, this.configuration.getProjectDir());
    saveGradleWrapperPropertyWhenChanged(dialogSettings, this.configuration.getGradleDistribution());
    saveBooleanPropertyWhenChanged(dialogSettings, SETTINGS_KEY_APPLY_WORKING_SETS,
            this.configuration.getApplyWorkingSets());
    saveStringArrayPropertyWhenChanged(dialogSettings, SETTINGS_KEY_WORKING_SETS,
            this.configuration.getWorkingSets());
}