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

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

Introduction

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

Prototype

public abstract boolean isPresent();

Source Link

Document

Returns true if this holder contains a (non-null) instance.

Usage

From source file:org.apache.gobblin.util.io.MeteredInputStream.java

/**
 * Find the lowest {@link MeteredInputStream} in a chain of {@link FilterInputStream}s.
 *//*from   w  w w .  j  a v  a2 s.  c  o  m*/
public static Optional<MeteredInputStream> findWrappedMeteredInputStream(InputStream is) {
    if (is instanceof FilterInputStream) {
        try {
            Optional<MeteredInputStream> meteredInputStream = findWrappedMeteredInputStream(
                    FilterStreamUnpacker.unpackFilterInputStream((FilterInputStream) is));
            if (meteredInputStream.isPresent()) {
                return meteredInputStream;
            }
        } catch (IllegalAccessException iae) {
            log.warn("Cannot unpack input stream due to SecurityManager.", iae);
            // Do nothing, we can't unpack the FilterInputStream due to security restrictions
        }
    }
    if (is instanceof MeteredInputStream) {
        return Optional.of((MeteredInputStream) is);
    }
    return Optional.absent();
}

From source file:de.azapps.mirakel.helper.WidgetHelper.java

@NonNull
public static ListMirakel getList(final Context context, final int widgetId) {
    final int listId = getSettings(context).getInt(getKey(widgetId, "list_id"), 0);
    final Optional<ListMirakel> list = ListMirakel.get(listId);
    if (!list.isPresent()) {
        return SpecialList.firstSpecialSafe();
    } else {/*from w  ww  . j ava  2s  .c  o  m*/
        return list.get();
    }
}

From source file:org.apache.gobblin.util.io.MeteredOutputStream.java

/**
 * Find the lowest {@link MeteredOutputStream} in a chain of {@link FilterOutputStream}s.
 *//*w ww. j a v  a 2s  .com*/
public static Optional<MeteredOutputStream> findWrappedMeteredOutputStream(OutputStream os) {
    if (os instanceof FilterOutputStream) {
        try {
            Optional<MeteredOutputStream> meteredOutputStream = findWrappedMeteredOutputStream(
                    FilterStreamUnpacker.unpackFilterOutputStream((FilterOutputStream) os));
            if (meteredOutputStream.isPresent()) {
                return meteredOutputStream;
            }
        } catch (IllegalAccessException iae) {
            log.warn("Cannot unpack input stream due to SecurityManager.", iae);
            // Do nothing, we can't unpack the FilterInputStream due to security restrictions
        }
    }
    if (os instanceof MeteredOutputStream) {
        return Optional.of((MeteredOutputStream) os);
    }
    return Optional.absent();
}

From source file:com.epam.reportportal.utils.properties.PropertiesLoader.java

/**
 * Try to load properties from file situated in the class path, and then
 * reload existing parameters from environment variables
 *
 * @return/*  ww w.  j  a  v a  2 s . c  om*/
 * @throws IOException
 */
private static Properties loadProperties() throws IOException {
    Properties props = new Properties();
    Optional<URL> propertyFile = getResource(INNER_PATH);
    if (propertyFile.isPresent()) {
        props.load(Resources.asByteSource(propertyFile.get()).openBufferedStream());
    }
    reloadFromSystemProperties(props);
    reloadFromEnvVariables(props);
    reloadFromSoapUI(props);
    validateProperties(props);
    reloadProperties(props);
    setProxyProperties(props);
    return props;
}

From source file:org.opendaylight.netconf.util.messages.NetconfHelloMessage.java

public static NetconfHelloMessage createClientHello(Iterable<String> capabilities,
        Optional<NetconfHelloMessageAdditionalHeader> additionalHeaderOptional)
        throws NetconfDocumentedException {
    Document doc = createHelloMessageDoc(capabilities);
    return additionalHeaderOptional.isPresent() ? new NetconfHelloMessage(doc, additionalHeaderOptional.get())
            : new NetconfHelloMessage(doc);
}

From source file:net.pterodactylus.sonitus.io.OggVorbisIdentifier.java

/**
 * Tries to parse the given stream as Ogg Vorbis file and returns a {@link
 * Metadata} describing the stream.//w ww .ja  va  2s .c  o m
 *
 * @param inputStream
 *       The input stream to identify as Ogg Vorbis
 * @return The identified metadata, or {@link Optional#absent()} if the stream
 *         could not be identified
 * @throws IOException
 *       if an I/O error occurs
 */
public static Optional<Metadata> identify(InputStream inputStream) throws IOException {

    /* stuff needed to decode Ogg. */
    Packet packet = new Packet();
    Page page = new Page();
    StreamState streamState = new StreamState();
    SyncState syncState = new SyncState();

    /* stuff needed to decode Vorbis. */
    Comment comment = new Comment();
    Info info = new Info();

    /* initialize jorbis. */
    syncState.init();
    int bufferSize = BUFFER_SIZE;
    int index = syncState.buffer(bufferSize);
    byte[] buffer = syncState.data;

    boolean streamStateInitialized = false;
    int packetsRead = 0;

    /* read until we have read the three packets required to decode the header. */
    while (packetsRead < 3) {
        int read = inputStream.read(buffer, index, bufferSize);
        syncState.wrote(read);
        switch (syncState.pageout(page)) {
        case -1:
            return Optional.absent();
        case 1:
            if (!streamStateInitialized) {
                /* init stream state. */
                streamState.init(page.serialno());
                streamState.reset();
                info.init();
                comment.init();
                streamStateInitialized = true;
            }
            if (streamState.pagein(page) == -1) {
                return Optional.absent();
            }
            switch (streamState.packetout(packet)) {
            case -1:
                return Optional.absent();
            case 1:
                info.synthesis_headerin(comment, packet);
                packetsRead++;
            default:
                /* continue. */
            }

        default:
            /* continue. */
        }
        index = syncState.buffer(bufferSize);
        buffer = syncState.data;
    }

    FormatMetadata formatMetadata = new FormatMetadata(info.channels, info.rate, "Vorbis");
    ContentMetadata contentMetadata = new ContentMetadata("");
    for (int c = 0; c < comment.comments; ++c) {
        String field = comment.getComment(c);
        Optional<String> extractedField = extractField(field, "ARTIST");
        if (extractedField.isPresent()) {
            contentMetadata = contentMetadata.artist(extractedField.get());
            continue;
        }
        extractedField = extractField(field, "TITLE");
        if (extractedField.isPresent()) {
            contentMetadata = contentMetadata.name(extractedField.get());
            continue;
        }
    }
    return Optional.of(new Metadata(formatMetadata, contentMetadata));
}

From source file:org.sonar.server.computation.qualitygate.ConditionEvaluator.java

@CheckForNull
private static Comparable parseMeasureFromVariation(Condition condition, Measure measure) {
    Optional<Double> periodValue = getPeriodValue(measure, condition.getPeriod());
    if (periodValue.isPresent()) {
        switch (condition.getMetric().getType().getValueType()) {
        case BOOLEAN:
            return periodValue.get().intValue() == 1;
        case INT:
            return periodValue.get().intValue();
        case LONG:
            return periodValue.get().longValue();
        case DOUBLE:
            return periodValue.get();
        case NO_VALUE:
        case STRING:
        case LEVEL:
        default://from w ww. ja  va 2 s. c  o m
            throw new IllegalArgumentException(
                    "Period conditions are not supported for metric type " + condition.getMetric().getType());
        }
    }
    return null;
}

From source file:com.facebook.buck.step.StepFailedException.java

static StepFailedException createForFailingStepWithExitCode(Step step, ExecutionContext context, int exitCode,
        Optional<BuildTarget> buildTarget) {
    String nameOrDescription = context.getVerbosity().shouldPrintCommand() ? step.getDescription(context)
            : step.getShortName();/*from  ww w .ja v  a  2  s  .  com*/
    String message;
    if (buildTarget.isPresent()) {
        message = String.format("%s failed with exit code %d:\n%s", buildTarget.get().getFullyQualifiedName(),
                exitCode, nameOrDescription);
    } else {
        message = String.format("Failed with exit code %d:\n%s", exitCode, nameOrDescription);
    }
    return new StepFailedException(message, step, exitCode);
}

From source file:org.eclipse.recommenders.utils.rcp.CompilerBindings.java

/**
 * TODO nested anonymous types are not resolved correctly. JDT uses line numbers for inner types instead of $1,..,$n
 *//*w  w  w . j  a  va 2 s.c o m*/
public static Optional<ITypeName> toTypeName(@Nullable TypeBinding binding) {
    // XXX generics fail
    if (binding == null) {
        return absent();
    }
    //
    final boolean boundParameterizedType = binding.isBoundParameterizedType();
    final boolean parameterizedType = binding.isParameterizedType();

    // if (binding.isBoundParameterizedType()) {
    // return null;
    // }

    if (binding.isArrayType()) {
        final int dimensions = binding.dimensions();
        final TypeBinding leafComponentType = binding.leafComponentType();
        final String arrayDimensions = StringUtils.repeat("[", dimensions);
        final Optional<ITypeName> typeName = toTypeName(leafComponentType);
        if (!typeName.isPresent()) {
            return absent();
        }
        final ITypeName res = VmTypeName.get(arrayDimensions + typeName.get().getIdentifier());
        return fromNullable(res);
    }
    // TODO: handling of generics is bogus!
    if (binding instanceof TypeVariableBinding) {
        final TypeVariableBinding generic = (TypeVariableBinding) binding;
        if (generic.declaringElement instanceof TypeBinding) {
            // XXX: for this?
            binding = (TypeBinding) generic.declaringElement;
        } else if (generic.superclass != null) {
            // example Tuple<T1 extends List, T2 extends Number) --> for
            // generic.superclass (T2)=Number
            // we replace the generic by its superclass
            binding = generic.superclass;
        }
    }

    String signature = String.valueOf(binding.genericTypeSignature());
    // if (binding instanceof BinaryTypeBinding) {
    // signature = StringUtils.substringBeforeLast(signature, ";");
    // }

    if (signature.length() == 1) {
        // no handling needed. primitives always look the same.
    } else if (signature.endsWith(";")) {
        signature = StringUtils.substringBeforeLast(signature, ";");
    } else {
        signature = "L" + SignatureUtil.stripSignatureToFQN(signature);
    }
    final ITypeName res = VmTypeName.get(signature);
    return fromNullable(res);
}

From source file:com.twitter.common.thrift.Util.java

/**
 * Maps a {@link ServiceInstance} to an {@link InetSocketAddress} given the {@code endpointName}.
 *
 * @param optionalEndpointName the name of the end-point on the service's additional end-points,
 *      if not set, maps to the primary service end-point
 *//*from   w  ww  . j  a  v a  2 s  . com*/
public static Function<ServiceInstance, InetSocketAddress> getAddress(
        final Optional<String> optionalEndpointName) {
    if (!optionalEndpointName.isPresent()) {
        return GET_ADDRESS;
    }

    final String endpointName = optionalEndpointName.get();
    return getAddress(new Function<ServiceInstance, Endpoint>() {
        @Override
        public Endpoint apply(@Nullable ServiceInstance serviceInstance) {
            Map<String, Endpoint> endpoints = serviceInstance.getAdditionalEndpoints();
            Preconditions.checkArgument(endpoints.containsKey(endpointName), "Did not find end-point %s on %s",
                    endpointName, serviceInstance);
            return endpoints.get(endpointName);
        }
    });
}