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.locationtech.geogig.cli.Logging.java

static void tryConfigureLogging(Platform platform) {
    // instantiate and call ResolveGeogigDir directly to avoid calling getGeogig() and hence get
    // some logging events before having configured logging
    final Optional<URL> geogigDirUrl = new ResolveGeogigDir(platform).call();
    if (!geogigDirUrl.isPresent() || !"file".equalsIgnoreCase(geogigDirUrl.get().getProtocol())) {
        // redirect java.util.logging to SLF4J anyways
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();/*www  . j a  va2 s .  c  om*/
        return;
    }

    final File geogigDir;
    try {
        geogigDir = new File(geogigDirUrl.get().toURI());
    } catch (URISyntaxException e) {
        throw Throwables.propagate(e);
    }

    if (geogigDir.equals(geogigDirLoggingConfiguration)) {
        return;
    }

    if (!geogigDir.exists() || !geogigDir.isDirectory()) {
        return;
    }
    final URL loggingFile = getOrCreateLoggingConfigFile(geogigDir);

    if (loggingFile == null) {
        return;
    }

    try {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.reset();
        /*
         * Set the geogigdir variable for the config file can resolve the default location
         * ${geogigdir}/log/geogig.log
         */
        loggerContext.putProperty("geogigdir", geogigDir.getAbsolutePath());
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(loggerContext);
        configurator.doConfigure(loggingFile);

        // redirect java.util.logging to SLF4J
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
        geogigDirLoggingConfiguration = geogigDir;
    } catch (JoranException e) {
        LOGGER.error("Error configuring logging from file {}. '{}'", loggingFile, e.getMessage(), e);
    }
}

From source file:org.apache.gobblin.data.management.copy.recovery.RecoveryHelper.java

private static String computeGuid(State state, CopyEntity file) throws IOException {
    Optional<Guid> stateGuid = CopySource.getWorkUnitGuid(state);
    if (stateGuid.isPresent()) {
        return Guid.combine(file.guid(), stateGuid.get()).toString();
    }/*from  w  ww .  j  a  va  2 s .  c  o  m*/
    throw new IOException("State does not contain a guid.");
}

From source file:org.opendaylight.yangtools.yang.data.impl.schema.tree.AbstractDataTreeCandidateNode.java

static Collection<DataTreeCandidateNode> deltaChildren(
        @Nullable final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> oldData,
        @Nullable final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> newData) {
    Preconditions.checkArgument(newData != null || oldData != null,
            "No old or new data, modification type should be NONE and deltaChildren() mustn't be called.");
    if (newData == null) {
        return Collections2.transform(oldData.getValue(), AbstractRecursiveCandidateNode::deleteNode);
    }//from w  w w.j  a  v a  2 s .  c  o  m
    if (oldData == null) {
        return Collections2.transform(newData.getValue(), AbstractRecursiveCandidateNode::writeNode);
    }

    /*
     * This is slightly inefficient, as it requires N*F(M)+M*F(N) lookup operations, where
     * F is dependent on the implementation of NormalizedNodeContainer.getChild().
     *
     * We build the return collection by iterating over new data and looking each child up
     * in old data. Based on that we construct replaced/written nodes. We then proceed to
     * iterate over old data and looking up each child in new data.
     */
    final Collection<DataTreeCandidateNode> result = new ArrayList<>();
    for (NormalizedNode<?, ?> child : newData.getValue()) {
        final DataTreeCandidateNode node;
        final Optional<NormalizedNode<?, ?>> maybeOldChild = oldData.getChild(child.getIdentifier());

        if (maybeOldChild.isPresent()) {
            // This does not find children which have not in fact been modified, as doing that
            // reliably would require us running a full equals() on the two nodes.
            node = AbstractRecursiveCandidateNode.replaceNode(maybeOldChild.get(), child);
        } else {
            node = AbstractRecursiveCandidateNode.writeNode(child);
        }

        result.add(node);
    }

    // Process removals next, looking into new data to see if we processed it
    for (NormalizedNode<?, ?> child : oldData.getValue()) {
        if (!newData.getChild(child.getIdentifier()).isPresent()) {
            result.add(AbstractRecursiveCandidateNode.deleteNode(child));
        }
    }

    return result;
}

From source file:org.asciidoctor.asciidoclet.DocletOptions.java

public static boolean validOptions(String[][] options, DocErrorReporter errorReporter,
        StandardAdapter standardDoclet) {
    DocletOptions docletOptions = new DocletOptions(options);

    if (!docletOptions.baseDir().isPresent()) {
        errorReporter.printWarning(/*from  w  w w  .  j a v  a2  s  .  c o  m*/
                BASEDIR + " must be present for includes or file reference features to work properly.");
    }

    Optional<File> attrsFile = docletOptions.attributesFile();
    if (attrsFile.isPresent() && !attrsFile.get().canRead()) {
        errorReporter.printWarning("Cannot read attributes file " + attrsFile.get());
    }

    return standardDoclet.validOptions(options, errorReporter);
}

From source file:org.eclipse.buildship.core.workspace.internal.ProjectNameUpdater.java

private static void ensureProjectNameIsFree(String normalizedProjectName, Set<OmniEclipseProject> allProjects,
        IProgressMonitor monitor) {// w  ww.j a  va2 s. c  om
    Optional<IProject> possibleDuplicate = CorePlugin.workspaceOperations()
            .findProjectByName(normalizedProjectName);
    if (possibleDuplicate.isPresent()) {
        IProject duplicate = possibleDuplicate.get();
        if (isScheduledForRenaming(duplicate, allProjects)) {
            renameTemporarily(duplicate, monitor);
        } else {
            String message = String.format("A project with the name %s already exists.", normalizedProjectName);
            throw new GradlePluginsRuntimeException(message);
        }
    }
}

From source file:org.onos.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils.java

public static Optional<DataSchemaNode> findFirstSchema(final QName qname,
        final Iterable<DataSchemaNode> dataSchemaNode) {
    if (dataSchemaNode != null && qname != null) {
        for (DataSchemaNode dsn : dataSchemaNode) {
            if (qname.isEqualWithoutRevision(dsn.getQName())) {
                return Optional.<DataSchemaNode>of(dsn);
            } else if (dsn instanceof ChoiceSchemaNode) {
                for (ChoiceCaseNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
                    Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
                    if (foundDsn != null && foundDsn.isPresent()) {
                        return foundDsn;
                    }// w  ww .  j  a  va 2  s  . co m
                }
            }
        }
    }
    return Optional.absent();
}

From source file:ninja.Results.java

public static Result created(Optional<String> url) {
    Result result = status(Result.SC_201_CREATED);
    if (url.isPresent()) {
        result.addHeader(Result.LOCATION, url.get());
    }/*from  ww w .ja  v a  2s . c  o  m*/

    return result;
}

From source file:org.opendaylight.protocol.bgp.flowspec.ipv4.FlowspecIpv4NlriParserHelper.java

private static final List<ProtocolIps> createProtocolsIps(final UnkeyedListNode protocolIpsData) {
    final List<ProtocolIps> protocolIps = new ArrayList<>();

    for (final UnkeyedListEntryNode node : protocolIpsData.getValue()) {
        final ProtocolIpsBuilder ipsBuilder = new ProtocolIpsBuilder();
        final Optional<DataContainerChild<? extends PathArgument, ?>> opValue = node
                .getChild(AbstractFlowspecNlriParser.OP_NID);
        if (opValue.isPresent()) {
            ipsBuilder/*from  w  w w . ja  v  a2  s . co m*/
                    .setOp(NumericOneByteOperandParser.INSTANCE.create((Set<String>) opValue.get().getValue()));
        }
        final Optional<DataContainerChild<? extends PathArgument, ?>> valueNode = node
                .getChild(AbstractFlowspecNlriParser.VALUE_NID);
        if (valueNode.isPresent()) {
            ipsBuilder.setValue((Short) valueNode.get().getValue());
        }
        protocolIps.add(ipsBuilder.build());
    }

    return protocolIps;
}

From source file:org.apache.rya.indexing.pcj.fluo.app.query.StatementPatternIdManager.java

/**
 * Remove specified Set of ids from the Fluo table and updates the entry with Column
 * {@link FluoQueryColumns#STATEMENT_PATTERN_IDS}. Also updates the hash of the updated nodeId Set and writes that
 * to the Column {@link FluoQueryColumns#STATEMENT_PATTERN_IDS_HASH}
 *
 * @param tx - Fluo Transaction object for performing atomic operations on Fluo table.
 * @param ids - ids to remove from the StatementPattern nodeId Set
 *///  w  ww  .  j a  v  a  2 s  . c o  m
public static void removeStatementPatternIds(TransactionBase tx, Set<String> ids) {
    checkNotNull(tx);
    checkNotNull(ids);
    Optional<Bytes> val = Optional.fromNullable(tx.get(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS));
    Set<String> storedIds = new HashSet<>();
    if (val.isPresent()) {
        storedIds = Sets.newHashSet(val.get().toString().split(VAR_DELIM));
    }
    storedIds.removeAll(ids);
    String idString = Joiner.on(VAR_DELIM).join(ids);
    tx.set(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS, Bytes.of(idString));
    tx.set(Bytes.of(STATEMENT_PATTERN_ID), STATEMENT_PATTERN_IDS_HASH,
            Bytes.of(Hashing.sha256().hashString(idString).toString()));
}

From source file:org.bin01.db.verifier.DbVerifier.java

public static <T> T loadConfig(Class<T> clazz, Optional<String> path) throws IOException {
    ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
    ConfigurationLoader loader = new ConfigurationLoader();
    if (path.isPresent()) {
        map.putAll(loader.loadPropertiesFrom(path.get()));
    }//ww w  .ja v  a  2 s . c o m
    map.putAll(loader.getSystemProperties());
    return new ConfigurationFactory(map.build()).build(clazz);
}