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.api.plumbing.merge.MergeFeaturesOp.java

@SuppressWarnings("unchecked")
private Feature merge(RevFeature featureA, RevFeature featureB, RevFeature ancestor,
        RevFeatureType featureType) {/*from  ww w .  ja va  2  s . c o  m*/

    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder((SimpleFeatureType) featureType.type());
    ImmutableList<Optional<Object>> valuesA = featureA.getValues();
    ImmutableList<Optional<Object>> valuesB = featureB.getValues();
    ImmutableList<Optional<Object>> valuesAncestor = ancestor.getValues();
    ImmutableList<PropertyDescriptor> descriptors = featureType.sortedDescriptors();
    for (int i = 0; i < descriptors.size(); i++) {
        PropertyDescriptor descriptor = descriptors.get(i);
        boolean isGeom = Geometry.class.isAssignableFrom(descriptor.getType().getBinding());
        Name name = descriptor.getName();
        Optional<Object> valueAncestor = valuesAncestor.get(i);
        Optional<Object> valueA = valuesA.get(i);
        Optional<Object> valueB = valuesB.get(i);
        if (!valueA.equals(valueAncestor)) {
            Optional<Object> merged = valueA;
            if (isGeom && !valueB.equals(valueAncestor)) { // true merge is only done with
                                                           // geometries
                GeometryAttributeDiff diffB = new GeometryAttributeDiff(
                        Optional.fromNullable((Geometry) valueAncestor.orNull()),
                        Optional.fromNullable((Geometry) valueB.orNull()));
                merged = (Optional<Object>) diffB.applyOn(valueA);
            }
            featureBuilder.set(name, merged.orNull());
        } else {
            featureBuilder.set(name, valueB.orNull());
        }
    }
    return featureBuilder.buildFeature(nodeRefA.name());

}

From source file:org.jclouds.googlecomputeengine.functions.internal.BaseWithZoneToPagedIterable.java

@Override
public PagedIterable<T> apply(ListPage<T> input) {
    if (input.nextMarker() == null)
        return PagedIterables.of(input);

    Optional<Object> project = tryFind(request.getCaller().get().getArgs(), instanceOf(String.class));

    Optional<Object> zone = tryFind(request.getInvocation().getArgs(), instanceOf(String.class));

    Optional<Object> listOptions = tryFind(request.getInvocation().getArgs(), instanceOf(ListOptions.class));

    assert project.isPresent() : String.format(
            "programming error, method %s should have a string param for the " + "project",
            request.getCaller().get().getInvokable());

    assert zone.isPresent() : String.format(
            "programming error, method %s should have a string param for the " + "zone",
            request.getCaller().get().getInvokable());

    return PagedIterables.advance(input,
            fetchNextPage(project.get().toString(), zone.get().toString(), (ListOptions) listOptions.orNull()));
}

From source file:org.locationtech.geogig.osm.cli.commands.OSMHistoryImport.java

/**
 * @param primitive//w w w.java  2  s . c om
 * @param thisChangePointCache
 * @return
 */
private Geometry parseGeometry(GeoGIG geogig, 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 = geogig.getRepository().index();

    FeatureBuilder featureBuilder = new FeatureBuilder(NODE_REV_TYPE);
    List<Coordinate> coordinates = Lists.newArrayList(nodes.size());
    FindTreeChild findTreeChild = geogig.command(FindTreeChild.class);
    ObjectId rootTreeId = geogig.command(ResolveTreeish.class).setTreeish(Ref.HEAD).call().get();
    if (!rootTreeId.isNull()) {
        RevTree headTree = geogig.command(RevObjectParse.class).setObjectId(rootTreeId).call(RevTree.class)
                .get();
        findTreeChild.setParent(headTree);
    }
    ObjectDatabase objectDatabase = geogig.getContext().objectDatabase();
    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.locationtech.geogig.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.locationtech.geogig.api.Node nodeRef = ref.get();

                RevFeature revFeature = objectDatabase.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.jclouds.googlecomputeengine.functions.internal.BaseWithRegionToPagedIterable.java

@Override
public PagedIterable<T> apply(ListPage<T> input) {
    if (input.nextMarker() == null)
        return PagedIterables.of(input);

    Optional<Object> project = tryFind(request.getCaller().get().getArgs(), instanceOf(String.class));

    Optional<Object> region = tryFind(request.getInvocation().getArgs(), instanceOf(String.class));

    Optional<Object> listOptions = tryFind(request.getInvocation().getArgs(), instanceOf(ListOptions.class));

    assert project.isPresent() : String.format(
            "programming error, method %s should have a string param for the " + "project",
            request.getCaller().get().getInvokable());

    assert region.isPresent() : String.format(
            "programming error, method %s should have a string param for the " + "region",
            request.getCaller().get().getInvokable());

    return PagedIterables.advance(input, fetchNextPage(project.get().toString(), region.get().toString(),
            (ListOptions) listOptions.orNull()));
}

From source file:com.google.devtools.build.android.PlaceholderIdFieldInitializerBuilder.java

public void addPublicResource(ResourceType type, String name, Optional<Integer> value) {
    SortedMap<String, Optional<Integer>> publicMappings = publicIds.get(type);
    if (publicMappings == null) {
        publicMappings = new TreeMap<>();
        publicIds.put(type, publicMappings);
    }/*from   ww  w.j a  v a  2s.c o  m*/
    Optional<Integer> oldValue = publicMappings.put(name, value);
    // AAPT should issue an error, but do a bit of sanity checking here just in case.
    if (oldValue != null && !oldValue.equals(value)) {
        // Enforce a consistent ordering on the warning message.
        Integer lower = oldValue.orNull();
        Integer higher = value.orNull();
        if (Ordering.natural().compare(oldValue.orNull(), value.orNull()) > 0) {
            lower = higher;
            higher = oldValue.orNull();
        }
        logger.warning(String.format("resource %s/%s has conflicting public identifiers (0x%x vs 0x%x)", type,
                name, lower, higher));
    }
}

From source file:org.opencms.xml.containerpage.CmsFormatterConfiguration.java

/**
 * Selects the best matching formatter for the provided type and width from this configuration.<p>
 *
 * This method first tries to find the formatter for the provided container type.
 * If this fails, it returns the width based formatter that matched the container width.<p>
 *
 * @param containerTypes the container types (comma separated)
 * @param containerWidth the container width
 * @param allowNested if nested containers are allowed
 *
 * @return the matching formatter, or <code>null</code> if none was found
 *//*from  w  w w  . j  a  v a  2  s . c  om*/
public I_CmsFormatterBean getDefaultFormatter(final String containerTypes, final int containerWidth,
        final boolean allowNested) {

    Optional<I_CmsFormatterBean> result = Iterables.tryFind(m_allFormatters,
            new MatchesTypeOrWidth(containerTypes, containerWidth, allowNested));
    return result.orNull();
}

From source file:com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTransferCases2.java

public void optionalMethodsReturnNonNullUnlessAnnotated() {
    // BUG: Diagnostic contains: (Non-null)
    triggerNullnessChecker(Optional.absent());
    // BUG: Diagnostic contains: (Non-null)
    triggerNullnessChecker(Optional.of(""));
    // BUG: Diagnostic contains: (Non-null)
    triggerNullnessChecker(Optional.fromNullable(null));
    // BUG: Diagnostic contains: (Non-null)
    triggerNullnessChecker(Optional.of("Test"));
    Optional<String> myOptional = Optional.absent();
    // BUG: Diagnostic contains: (Non-null)
    triggerNullnessChecker(myOptional.get());
    // BUG: Diagnostic contains: (Non-null)
    triggerNullnessChecker(myOptional.or(""));
    // BUG: Diagnostic contains: (Non-null)
    triggerNullnessChecker(myOptional.asSet());

    // BUG: Diagnostic contains: (Nullable)
    triggerNullnessChecker(myOptional.orNull());
}

From source file:li.klass.fhem.service.intent.DeviceIntentService.java

@Override
protected STATE handleIntent(Intent intent, long updatePeriod, ResultReceiver resultReceiver) {

    if (roomListService.updateRoomDeviceListIfRequired(intent, updatePeriod, this) == REQUIRED) {
        return DONE;
    }//from   w w w  .  ja va 2  s.  c o  m

    String deviceName = intent.getStringExtra(BundleExtraKeys.DEVICE_NAME);
    Optional<FhemDevice> deviceOptional = roomListService.getDeviceForName(deviceName, this);
    if (!deviceOptional.isPresent()) {
        LOG.info("handleIntent() - cannot find device for {}", deviceName);
    }
    FhemDevice device = deviceOptional.orNull();

    Log.d(DeviceIntentService.class.getName(), intent.getAction());
    String action = intent.getAction();

    STATE result = STATE.SUCCESS;
    if (DEVICE_GRAPH.equals(action)) {
        result = graphIntent(intent, device, resultReceiver);
    } else if (DEVICE_TOGGLE_STATE.equals(action)) {
        result = toggleIntent(device);
    } else if (DEVICE_SET_STATE.equals(action)) {
        result = setStateIntent(intent, device);
    } else if (DEVICE_DIM.equals(action)) {
        result = dimIntent(intent, device);
    } else if (DEVICE_SET_DAY_TEMPERATURE.equals(action)) {
        double dayTemperature = intent.getDoubleExtra(BundleExtraKeys.DEVICE_TEMPERATURE, -1);
        fhtService.setDayTemperature((FHTDevice) device, dayTemperature, this);
    } else if (DEVICE_SET_NIGHT_TEMPERATURE.equals(action)) {
        double nightTemperature = intent.getDoubleExtra(BundleExtraKeys.DEVICE_TEMPERATURE, -1);
        fhtService.setNightTemperature((FHTDevice) device, nightTemperature, this);
    } else if (DEVICE_SET_MODE.equals(action)) {
        if (device instanceof FHTDevice) {
            FHTMode mode = (FHTMode) intent.getSerializableExtra(BundleExtraKeys.DEVICE_MODE);
            double desiredTemperature = intent.getDoubleExtra(BundleExtraKeys.DEVICE_TEMPERATURE,
                    FHTDevice.MINIMUM_TEMPERATURE);
            int holiday1 = intent.getIntExtra(BundleExtraKeys.DEVICE_HOLIDAY1, -1);
            int holiday2 = intent.getIntExtra(BundleExtraKeys.DEVICE_HOLIDAY2, -1);

            fhtService.setMode((FHTDevice) device, mode, desiredTemperature, holiday1, holiday2, this);
        } else if (device instanceof HeatingDevice) {
            Enum mode = (Enum) intent.getSerializableExtra(BundleExtraKeys.DEVICE_MODE);
            HeatingDevice heatingDevice = (HeatingDevice) device;

            heatingService.setMode(heatingDevice, mode, this);
        }

    } else if (DEVICE_SET_WEEK_PROFILE.equals(action)) {
        if (!(device instanceof HeatingDevice))
            return ERROR;
        heatingService.setWeekProfileFor((HeatingDevice) device, this);

    } else if (DEVICE_SET_WINDOW_OPEN_TEMPERATURE.equals(action)) {
        if (!(device instanceof WindowOpenTempDevice))
            return SUCCESS;

        double temperature = intent.getDoubleExtra(BundleExtraKeys.DEVICE_TEMPERATURE, -1);
        heatingService.setWindowOpenTemp((WindowOpenTempDevice) device, temperature, this);

    } else if (DEVICE_SET_DESIRED_TEMPERATURE.equals(action)) {
        double temperature = intent.getDoubleExtra(BundleExtraKeys.DEVICE_TEMPERATURE, -1);
        if (device instanceof DesiredTempDevice) {
            heatingService.setDesiredTemperature((DesiredTempDevice) device, temperature, this);
        }

    } else if (DEVICE_SET_COMFORT_TEMPERATURE.equals(action)) {
        double temperature = intent.getDoubleExtra(BundleExtraKeys.DEVICE_TEMPERATURE, -1);
        if (device instanceof DesiredTempDevice) {
            heatingService.setComfortTemperature((ComfortTempDevice) device, temperature, this);
        }

    } else if (DEVICE_SET_ECO_TEMPERATURE.equals(action)) {
        double temperature = intent.getDoubleExtra(BundleExtraKeys.DEVICE_TEMPERATURE, -1);
        if (device instanceof DesiredTempDevice) {
            heatingService.setEcoTemperature((EcoTempDevice) device, temperature, this);
        }

    } else if (DEVICE_RESET_WEEK_PROFILE.equals(action)) {
        if (!(device instanceof HeatingDevice))
            return ERROR;
        heatingService.resetWeekProfile((HeatingDevice) device);

    } else if (DEVICE_REFRESH_VALUES.equals(action)) {
        fhtService.refreshValues((FHTDevice) device, this);

    } else if (DEVICE_RENAME.equals(action)) {
        String newName = intent.getStringExtra(BundleExtraKeys.DEVICE_NEW_NAME);
        deviceService.renameDevice(device, newName, this);
        notificationService.rename(device.getName(), newName, this);

    } else if (DEVICE_DELETE.equals(action)) {
        deviceService.deleteDevice(device, this);

    } else if (DEVICE_MOVE_ROOM.equals(action)) {
        String newRoom = intent.getStringExtra(BundleExtraKeys.DEVICE_NEW_ROOM);
        deviceService.moveDevice(device, newRoom, this);

    } else if (DEVICE_SET_ALIAS.equals(action)) {
        String newAlias = intent.getStringExtra(BundleExtraKeys.DEVICE_NEW_ALIAS);
        deviceService.setAlias(device, newAlias, this);

    } else if (DEVICE_REFRESH_STATE.equals(action)) {
        wolService.requestRefreshState((WOLDevice) device, this);
    } else if (DEVICE_WIDGET_TOGGLE.equals(action)) {
        result = toggleIntent(device);

    } else if (DEVICE_TIMER_MODIFY.equals(action)) {
        processTimerIntent(intent, true);

    } else if (DEVICE_TIMER_NEW.equals(action)) {
        processTimerIntent(intent, false);

    } else if (DEVICE_SET_SUB_STATE.equals(action)) {
        String name = intent.getStringExtra(STATE_NAME);
        String value = intent.getStringExtra(STATE_VALUE);

        genericDeviceService.setSubState(device, name, value, this);

    } else if (GCM_ADD_SELF.equals(action)) {
        gcmSendDeviceService.addSelf((GCMSendDevice) device, this);

    } else if (GCM_REMOVE_ID.equals(action)) {
        String registrationId = intent.getStringExtra(BundleExtraKeys.GCM_REGISTRATION_ID);
        gcmSendDeviceService.removeRegistrationId((GCMSendDevice) device, registrationId, this);

    } else if (RESEND_LAST_FAILED_COMMAND.equals(action)) {

        String lastFailedCommand = commandExecutionService.getLastFailedCommand();
        if ("xmllist".equalsIgnoreCase(lastFailedCommand)) {
            Intent updateIntent = new Intent(Actions.DO_UPDATE);
            updateIntent.putExtra(BundleExtraKeys.DO_REFRESH, true);
            sendBroadcast(updateIntent);
        } else {
            commandExecutionService.resendLastFailedCommand(this);
        }
    }

    Intent redrawWidgetsIntent = new Intent(Actions.REDRAW_ALL_WIDGETS);
    redrawWidgetsIntent.setClass(this, AppWidgetUpdateService.class);
    startService(redrawWidgetsIntent);

    return result;
}

From source file:org.apache.james.mailbox.store.mail.model.impl.MessageParser.java

private MessageAttachment retrieveAttachment(MessageWriter messageWriter, Entity entity) throws IOException {
    Optional<ContentTypeField> contentTypeField = getContentTypeField(entity);
    Optional<String> contentType = contentType(contentTypeField);
    Optional<String> name = name(contentTypeField);
    Optional<Cid> cid = cid(castField(entity.getHeader().getField(CONTENT_ID), ContentIdField.class));
    boolean isInline = isInline(
            castField(entity.getHeader().getField(CONTENT_DISPOSITION), ContentDispositionField.class));

    return MessageAttachment.builder()
            .attachment(Attachment.builder().bytes(getBytes(messageWriter, entity.getBody()))
                    .type(contentType.or(DEFAULT_CONTENT_TYPE)).build())
            .name(name.orNull()).cid(cid.orNull()).isInline(isInline).build();
}

From source file:org.locationtech.geogig.plumbing.remotes.RemoteResolve.java

/**
 * Executes the remote-add operation./*from  w w  w . j a  va  2s  . c o m*/
 * 
 * @return the {@link Remote} that was added.
 */
@Override
protected Optional<Remote> _call() {
    if (name == null || name.isEmpty()) {
        throw new RemoteException(StatusCode.MISSING_NAME);
    }

    Optional<Remote> result = Optional.absent();

    ConfigDatabase config = configDatabase();
    List<String> allRemotes = config.getAllSubsections("remote");
    if (allRemotes.contains(name)) {

        String remoteSection = "remote." + name;
        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");
        Optional<String> remotePushURL = Optional.absent();
        if (remoteFetchURL.isPresent() && remoteFetch.isPresent()) {
            remotePushURL = config.get(remoteSection + ".pushurl");
        }
        Remote remote = new Remote(name, remoteFetchURL.or(""), remotePushURL.or(remoteFetchURL).or(""),
                remoteFetch.or(""), remoteMapped.or("false").equals("true"), remoteMappedBranch.orNull(),
                remoteUserName.orNull(), remotePassword.orNull());
        result = Optional.of(remote);
    }
    return result;
}