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.opendaylight.bgpcep.bgp.topology.provider.AbstractReachabilityTopologyBuilder.java

private static <T extends DataObject> T read(final ReadTransaction t, final InstanceIdentifier<T> id) {
    final Optional<T> o;
    try {//w  w w  . ja va 2 s  .  c  o  m
        o = t.read(LogicalDatastoreType.OPERATIONAL, id).get();
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Failed to read {}, assuming non-existent", id, e);
        return null;
    }

    return o.orNull();
}

From source file:org.geogit.storage.text.TextValueSerializer.java

/**
 * Returns a string representation of the passed field value
 * /*  ww  w  .  j  a  v a 2 s. co  m*/
 * @param opt
 */
public static String asString(Optional<Object> opt) {
    final FieldType type = FieldType.forValue(opt);
    if (serializers.containsKey(type)) {
        return serializers.get(type).toString(opt.orNull());
    } else {
        throw new IllegalArgumentException("The specified type is not supported: " + type);
    }
}

From source file:org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.java

public static Pcrpt createPcRtpMessage(final Lsp lsp, final Optional<Srp> srp, final Path path) {
    final PcrptBuilder rptBuilder = new PcrptBuilder();
    final PcrptMessageBuilder msgBuilder = new PcrptMessageBuilder();
    final ReportsBuilder reportBuilder = new ReportsBuilder();
    reportBuilder.setLsp(lsp);//from  w ww  .j  a  va2 s . co m
    reportBuilder.setSrp(srp.orNull());
    reportBuilder.setPath(path);
    msgBuilder.setReports(Lists.newArrayList(reportBuilder.build()));
    rptBuilder.setPcrptMessage(msgBuilder.build());
    return rptBuilder.build();
}

From source file:org.openqa.selenium.remote.server.rest.Responses.java

/**
 * Creates a response object for a failed command execution.
 *
 * @param sessionId ID of the session that executed the command.
 * @param reason the failure reason.//  w w  w .  ja  v a  2  s.  c om
 * @param screenshot a base64 png screenshot to include with the failure.
 * @return the new response object.
 */
public static Response failure(SessionId sessionId, Throwable reason, Optional<String> screenshot) {
    Response response = new Response();
    response.setSessionId(sessionId != null ? sessionId.toString() : null);
    response.setStatus(ERROR_CODES.toStatusCode(reason));
    response.setState(ERROR_CODES.toState(response.getStatus()));

    if (reason != null) {
        JsonObject json = new BeanToJsonConverter().convertObject(reason).getAsJsonObject();
        json.addProperty("screen", screenshot.orNull());
        response.setValue(json);
    }
    return response;
}

From source file:io.crate.analyze.relations.RelationNormalizer.java

/**
 * "Merge" OrderBy of child & parent relations.
 * <p/>//  w  ww. j a va 2s. co m
 * examples:
 * <pre>
 *      childOrderBy: col1, col2
 *      parentOrderBy: col2, col3, col4
 *
 *      merged OrderBy returned: col2, col3, col4
 * </pre>
 * <p/>
 * <pre>
 *      childOrderBy: col1, col2
 *      parentOrderBy:
 *
 *      merged OrderBy returned: col1, col2
 * </pre>
 *
 * @param childOrderBy  The OrderBy of the relation being processed
 * @param parentOrderBy The OrderBy of the parent relation (outer select,  union, etc.)
 * @return The merged orderBy
 */
@Nullable
private static OrderBy tryReplace(Optional<OrderBy> childOrderBy, Optional<OrderBy> parentOrderBy) {
    if (parentOrderBy.isPresent()) {
        return parentOrderBy.get();
    }
    return childOrderBy.orNull();
}

From source file:com.textocat.textokit.commons.cas.AnnotationUtils.java

public static <A extends Annotation> A findByCoveredText(JCas jCas, Class<A> annoClass,
        final String coveredText) {
    Optional<A> findRes = Iterables.tryFind(jCas.getAnnotationIndex(annoClass), new Predicate<A>() {
        @Override//w w  w . ja v a2  s.c om
        public boolean apply(A input) {
            return Objects.equals(input.getCoveredText(), coveredText);
        }
    });
    return findRes.orNull();
}

From source file:org.eclipse.tracecompass.tmf.remote.core.proxy.RemoteSystemProxy.java

/**
 * Return a remote connection using OSGI service.
 *
 * @param remoteServicesId//from ww w  .  j a v a  2  s . c om
 *            ID of remote service
 * @param name
 *            name of connection
 * @return the corresponding remote connection or null
 */
public static @Nullable IRemoteConnection getRemoteConnection(final String remoteServicesId,
        final String name) {
    IRemoteServicesManager manager = Activator.getService(IRemoteServicesManager.class);
    if (manager == null) {
        return null;
    }
    FluentIterable<IRemoteConnection> connections = FluentIterable.from(manager.getAllRemoteConnections());
    Optional<IRemoteConnection> ret = connections.firstMatch(new Predicate<IRemoteConnection>() {
        @Override
        public boolean apply(@Nullable IRemoteConnection input) {
            return ((input != null) && input.getConnectionType().getId().equals(remoteServicesId.toString())
                    && input.getName().equals(name.toString()));
        }
    });
    return ret.orNull();
}

From source file:org.apache.abdera2.common.templates.Operation.java

private static String toString(Object val, Context context, boolean reserved, boolean explode,
        String explodeDelim, String explodePfx, int len) {
    if (val == null)
        return null;
    String exp = explode && explodeDelim != null ? explodeDelim : ",";
    if (val.getClass().isArray()) {
        if (val instanceof byte[]) {
            return UrlEncoding.encode((byte[]) val);
        } else if (val instanceof char[]) {
            String chars = (String) trim(new String((char[]) val), len);
            return !reserved
                    ? UrlEncoding.encode(normalize(chars),
                            context.isIri() ? CharUtils.Profile.IUNRESERVED : CharUtils.Profile.UNRESERVED)
                    : UrlEncoding.encode(normalize(chars),
                            context.isIri() ? CharUtils.Profile.RESERVEDANDIUNRESERVED
                                    : CharUtils.Profile.RESERVEDANDUNRESERVED);
        } else if (val instanceof short[]) {
            StringBuilder buf = new StringBuilder();
            for (short obj : (short[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof int[]) {
            StringBuilder buf = new StringBuilder();
            for (int obj : (int[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof long[]) {
            StringBuilder buf = new StringBuilder();
            for (long obj : (long[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof double[]) {
            StringBuilder buf = new StringBuilder();
            for (double obj : (double[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof float[]) {
            StringBuilder buf = new StringBuilder();
            for (float obj : (float[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof boolean[]) {
            StringBuilder buf = new StringBuilder();
            for (boolean obj : (boolean[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else {//from   www .  j av  a2s . c  om
            StringBuilder buf = new StringBuilder();
            for (Object obj : (Object[]) val) {
                appendif(buf.length() > 0, buf, exp);
                appendif(explode && explodePfx != null, buf, explodePfx);
                buf.append(toString(obj, context, reserved, false, null, null, len));
            }
            return buf.toString();
        }
    } else if (val instanceof InputStream) {
        try {
            if (len > -1) {
                byte[] buf = new byte[len];
                int r = ((InputStream) val).read(buf);
                return r > 0 ? UrlEncoding.encode(buf, 0, r) : "";
            } else
                return UrlEncoding.encode((InputStream) val);
        } catch (IOException e) {
            throw ExceptionHelper.propogate(e);
        }
    } else if (val instanceof Readable) {
        try {
            if (len > -1) {
                CharBuffer buf = CharBuffer.allocate(len);
                int r = ((Readable) val).read(buf);
                buf.limit(r);
                buf.position(0);
                val = buf;
            }
            return !reserved
                    ? UrlEncoding.encode((Readable) val, "UTF-8",
                            context.isIri() ? CharUtils.Profile.IUNRESERVED : CharUtils.Profile.UNRESERVED)
                    : UrlEncoding.encode((Readable) val, "UTF-8",
                            context.isIri() ? CharUtils.Profile.RESERVEDANDIUNRESERVED
                                    : CharUtils.Profile.RESERVEDANDUNRESERVED);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else if (val instanceof CharSequence) {
        val = trim(normalize((CharSequence) val), len);
        return encode((CharSequence) val, context.isIri(), reserved);
    } else if (val instanceof Byte) {
        return UrlEncoding.encode(((Byte) val).byteValue());
    } else if (val instanceof Context) {
        StringBuilder buf = new StringBuilder();
        Context ctx = (Context) val;
        for (String name : ctx) {
            String _val = toString(ctx.resolve(name), context, reserved, false, null, null, len);
            appendif(buf.length() > 0, buf, exp);
            buf.append(name).append(explode ? '=' : ',').append(_val);
        }
        return buf.toString();
    } else if (val instanceof Iterable) {
        StringBuilder buf = new StringBuilder();
        for (Object obj : (Iterable<Object>) val) {
            appendif(buf.length() > 0, buf, exp);
            appendif(explode && explodePfx != null, buf, explodePfx);
            buf.append(toString(obj, context, reserved, false, null, null, len));
        }
        return buf.toString();
    } else if (val instanceof Iterator) {
        StringBuilder buf = new StringBuilder();
        Iterator<Object> i = (Iterator<Object>) val;
        while (i.hasNext()) {
            Object obj = i.next();
            appendif(buf.length() > 0, buf, exp);
            appendif(explode && explodePfx != null, buf, explodePfx);
            buf.append(toString(obj, context, reserved, false, null, null, len));
        }
        return buf.toString();
    } else if (val instanceof Enumeration) {
        StringBuilder buf = new StringBuilder();
        Enumeration<Object> i = (Enumeration<Object>) val;
        while (i.hasMoreElements()) {
            Object obj = i.nextElement();
            appendif(buf.length() > 0, buf, exp);
            appendif(explode && explodePfx != null, buf, explodePfx);
            buf.append(toString(obj, context, reserved, false, null, null, len));
        }
        return buf.toString();
    } else if (val instanceof Map) {
        StringBuilder buf = new StringBuilder();
        Map<Object, Object> map = (Map<Object, Object>) val;
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            String _key = toString(entry.getKey(), context, reserved, false, null, null, len);
            String _val = toString(entry.getValue(), context, reserved, false, null, null, len);
            appendif(buf.length() > 0, buf, exp);
            buf.append(_key).append(explode ? '=' : ',').append(_val);
        }
        return buf.toString();
    } else if (val instanceof Supplier) {
        return toString(((Supplier<?>) val).get(), context, reserved, explode, explodeDelim, explodePfx, len);
    } else if (val instanceof Optional) {
        Optional<?> o = (Optional<?>) val;
        return toString(o.orNull(), context, reserved, explode, explodeDelim, explodePfx, len);
    } else if (val instanceof Multimap) {
        Multimap<?, ?> mm = (Multimap<?, ?>) val;
        return toString(mm.asMap(), context, reserved, explode, explodeDelim, explodePfx, len);
    } else if (val instanceof Callable) {
        Callable<Object> callable = (Callable<Object>) val;
        try {
            return toString(callable.call(), context, reserved, explode, explodeDelim, explodePfx, len);
        } catch (Exception e) {
            throw ExceptionHelper.propogate(e);
        }
    } else if (val instanceof Reference) {
        Reference<Object> ref = (Reference<Object>) val;
        return toString(ref.get(), context, reserved, explode, explodeDelim, explodePfx, len);
    } else if (val instanceof Future) {
        try {
            Future<Object> future = (Future<Object>) val;
            return toString(future.get(), context, reserved, explode, explodeDelim, explodePfx, len);
        } catch (Throwable e) {
            throw ExceptionHelper.propogate(e);
        }
    } else {
        if (val != null)
            val = normalize(val.toString());
        return encode(val != null ? val.toString() : null, context.isIri(), reserved);
    }
}

From source file:io.brooklyn.ambari.EtcHostsManager.java

/**
 * Scans the entities, determines the IP address and hostname for each entity, and returns a map that connects from
 * IP address to fully-qualified domain name.
 *
 * @param entities entities to search for name/IP information.
 * @param addressSensor the sensor containing the IP address for each entity.
 * @return a map with an entry for each entity, mapping its IP address to its fully-qualified domain name.
 *//*w  ww  . j a  va  2  s .  co  m*/
public static Map<String, String> gatherIpHostnameMapping(Iterable<? extends Entity> entities,
        AttributeSensor<String> addressSensor) {
    Map<String, String> mapping = Maps.newHashMap();
    for (Entity e : entities) {
        Optional<String> name = Optional.fromNullable(e.getAttribute(AmbariNode.FQDN))
                .or(Optional.fromNullable(Machines.findSubnetOrPublicHostname(e).orNull()));
        Maybe<String> ip = Maybe.fromNullable(e.getAttribute(addressSensor));
        if (name.isPresent() && ip.isPresentAndNonNull()) {
            mapping.put(ip.get(), name.get());
        } else {
            LOG.debug("No hostname or ip found for {}: hostname={}, ip={}",
                    new Object[] { e, name.orNull(), ip.orNull() });
        }
    }
    LOG.debug("Generated host mapping: " + Joiner.on(", ").withKeyValueSeparator("=").join(mapping));
    return mapping;
}

From source file:org.geogit.storage.datastream.DataStreamValueSerializer.java

/**
 * Writes the passed attribute value in the specified data stream
 * // ww  w  . j av a 2 s. c om
 * @param opt
 * @param data
 */
public static void write(Optional<Object> opt, DataOutput data) throws IOException {
    FieldType type = FieldType.forValue(opt);
    if (serializers.containsKey(type)) {
        serializers.get(type).write(opt.orNull(), data);
    } else {
        throw new IllegalArgumentException("The specified type (" + type + ") is not supported");
    }
}