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

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

Introduction

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

Prototype

@Beta
public abstract T or(Supplier<? extends T> supplier);

Source Link

Document

Returns the contained instance if it is present; supplier.get() otherwise.

Usage

From source file:org.apache.gobblin.writer.MultiWriterWatermarkManager.java

public MultiWriterWatermarkManager(WatermarkStorage storage, long commitIntervalMillis,
        Optional<Logger> logger) {
    Preconditions.checkArgument(storage != null, "WatermarkStorage cannot be null");
    _watermarkAwareWriters = new ConcurrentLinkedQueue<>();
    _watermarkStorage = storage;/*from  ww w .jav a 2s  .c  om*/
    _commitIntervalMillis = commitIntervalMillis;
    _logger = logger.or(LoggerFactory.getLogger(MultiWriterWatermarkManager.class));
    _watermarkCommitThreadPool = new ScheduledThreadPoolExecutor(1,
            ExecutorsUtils.newThreadFactory(logger, Optional.of("WatermarkManager-%d")));
    _retrievalStatus = new RetrievalStatus();
    _commitStatus = new CommitStatus();
}

From source file:org.opendaylight.netconf.tcp.osgi.NetconfTCPActivator.java

@Override
public void start(BundleContext context) {
    final Optional<InetSocketAddress> maybeAddress = NetconfConfigUtil.extractNetconfServerAddress(context,
            InfixProp.tcp);//  www  .j  av  a  2  s  . co m
    if (maybeAddress.isPresent() == false) {
        LOG.warn("Netconf tcp server is not configured. Using default value {}",
                NetconfConfigUtil.DEFAULT_TCP_SERVER_ADRESS);
    }

    InetSocketAddress address = maybeAddress.or(NetconfConfigUtil.DEFAULT_TCP_SERVER_ADRESS);

    if (address.getAddress().isAnyLocalAddress()) {
        LOG.warn(
                "Unprotected netconf TCP address is configured to ANY local address. This is a security risk. Consider changing {} to 127.0.0.1",
                NetconfConfigUtil.getNetconfServerAddressKey(InfixProp.tcp));
    }
    LOG.info("Starting TCP netconf server at {}", address);
    proxyServer = new ProxyServer(address, NetconfConfigUtil.getNetconfLocalAddress());
}

From source file:lcmc.cluster.service.storage.FileSystemService.java

private Set<String> getCommonFileSystems(final Collection<Host> hosts) {
    Optional<Set<String>> fileSystemsIntersection = Optional.absent();

    for (final Host host : hosts) {
        final Set<String> fileSystems = fileSystemsByHost.get(host);
        fileSystemsIntersection = Tools.getIntersection(Optional.fromNullable(fileSystems),
                fileSystemsIntersection);
    }// www  .ja  va 2  s . c o m
    return fileSystemsIntersection.or(new TreeSet<String>());
}

From source file:org.fcrepo.http.commons.domain.ldp.LdpPreferTag.java

/**
 * Standard constructor./* w w  w  .ja  v  a  2  s  .c  o  m*/
 *
 * @param preferTag the prefer tag
 */
public LdpPreferTag(final PreferTag preferTag) {
    super(preferTag);

    final Optional<String> include = fromNullable(preferTag.getParams().get("include"));
    final Optional<String> omit = fromNullable(preferTag.getParams().get("omit"));
    final Optional<String> received = fromNullable(preferTag.getParams().get("received"));

    final List<String> includes = asList(include.or(" ").split(" "));
    final List<String> omits = asList(omit.or(" ").split(" "));

    final boolean minimal = preferTag.getValue().equals("minimal") || received.or("").equals("minimal");

    final boolean preferMinimalContainer = includes.contains(LDP_NAMESPACE + "PreferMinimalContainer")
            || minimal;

    membership = (!preferMinimalContainer && !omits.contains(LDP_NAMESPACE + "PreferMembership"))
            || includes.contains(LDP_NAMESPACE + "PreferMembership");

    containment = (!preferMinimalContainer && !omits.contains(LDP_NAMESPACE + "PreferContainment"))
            || includes.contains(LDP_NAMESPACE + "PreferContainment");

    references = includes.contains(INBOUND_REFERENCES.toString());

    embed = includes.contains(EMBED_CONTAINS.toString());

    managedProperties = includes.contains(SERVER_MANAGED.toString())
            || (!omits.contains(SERVER_MANAGED.toString()) && !minimal);
}

From source file:org.geogit.cli.porcelain.Show.java

public void printFormatted(GeogitCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIT geogit = cli.getGeogit();// w ww .j a  v a2 s.  c  o m
    for (String ref : refs) {
        Optional<RevObject> obj = geogit.command(RevObjectParse.class).setRefSpec(ref).call();
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            RevFeatureType ft = geogit.command(ResolveFeatureType.class).setRefSpec(ref).call().get();
            ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
            RevFeature feature = (RevFeature) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.newline().fg(Color.YELLOW).a("ID:  ").reset().a(feature.getId().toString()).newline()
                    .newline();
            ansi.a("ATTRIBUTES  ").newline();
            ansi.a("----------  ").newline();
            ImmutableList<Optional<Object>> values = feature.getValues();
            int i = 0;
            for (Optional<Object> value : values) {
                ansi.fg(Color.YELLOW).a(attribs.get(i).getName() + ": ").reset();
                ansi.a(value.or("[NULL]").toString()).newline();
                i++;
            }
            console.println(ansi.toString());

        } else if (revObject instanceof RevTree) {
            RevTree tree = (RevTree) revObject;
            Optional<RevFeatureType> opt = geogit.command(ResolveFeatureType.class).setRefSpec(ref).call();
            checkParameter(opt.isPresent(), "Refspec must resolve to a commit, tree, feature or feature type");
            RevFeatureType ft = opt.get();
            Ansi ansi = super.newAnsi(console.getTerminal());

            ansi.fg(Color.YELLOW).a("TREE ID:  ").reset().a(tree.getId().toString()).newline();
            ansi.fg(Color.YELLOW).a("SIZE:  ").reset().a(Long.toString(tree.size())).newline();
            ansi.fg(Color.YELLOW).a("NUMBER Of SUBTREES:  ").reset()
                    .a(Integer.toString(tree.numTrees()).toString()).newline();

            printFeatureType(ansi, ft, true);

            console.println(ansi.toString());
        } else if (revObject instanceof RevCommit) {
            RevCommit commit = (RevCommit) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.a(Strings.padEnd("Commit:", 15, ' ')).fg(Color.YELLOW).a(commit.getId().toString()).reset()
                    .newline();
            ansi.a(Strings.padEnd("Author:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Committer:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Author date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogit.getPlatform(), commit.getAuthor().getTimestamp())).reset().a(") ")
                    .a(new Date(commit.getAuthor().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Committer date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogit.getPlatform(), commit.getCommitter().getTimestamp())).reset()
                    .a(") ").a(new Date(commit.getCommitter().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Subject:", 15, ' ')).a(commit.getMessage()).newline();
            console.println(ansi.toString());
        } else if (revObject instanceof RevFeatureType) {
            Ansi ansi = super.newAnsi(console.getTerminal());
            printFeatureType(ansi, (RevFeatureType) revObject, false);
            console.println(ansi.toString());
        } else {
            throw new InvalidParameterException(
                    "Refspec must resolve to a commit, tree, feature or feature type");
        }
        console.println();
    }

}

From source file:com.vino.AppModule.java

@Provides
public AutoStartable mongoConnectionLogger(final @Named("restx.server.id") Optional<String> serverId,
        final @Named("mongo.db") String dbName,
        final @Named(MongoModule.MONGO_CLIENT_NAME) MongoClient client) {
    return new AutoStartable() {
        @Override//from w  w  w .ja  va2 s.com
        public void start() {
            logger.info("{} - connected to Mongo db '{}' @ {}", serverId.or("-"), dbName,
                    client.getAllAddress());
        }
    };
}

From source file:com.qcadoo.mes.deliveriesToMaterialFlow.states.DeliveryStateServiceMF.java

public void createDocumentsForTheReceivedProducts(final StateChangeContext stateChangeContext) {
    final Entity delivery = stateChangeContext.getOwner();

    Entity location = location(delivery);
    if (location == null) {
        return;/*from w  w w.  j ava 2s . c o  m*/
    }

    Entity currency = currency(delivery);

    List<Entity> deliveredProducts = delivery.getHasManyField(DeliveryFields.DELIVERED_PRODUCTS);

    DocumentBuilder documentBuilder = documentManagementService.getDocumentBuilder();
    documentBuilder.receipt(location);
    documentBuilder.setField(DocumentFieldsDTMF.DELIVERY, delivery);
    documentBuilder.setField(DocumentFields.COMPANY, delivery.getField(DeliveryFields.SUPPLIER));
    for (Entity deliveredProduct : deliveredProducts) {

        BigDecimal quantity = deliveredProduct.getDecimalField(DeliveredProductFields.DELIVERED_QUANTITY);
        Optional<BigDecimal> damagedQuantity = Optional
                .fromNullable(deliveredProduct.getDecimalField(DeliveredProductFields.DAMAGED_QUANTITY));

        BigDecimal positionQuantity = quantity.subtract(damagedQuantity.or(BigDecimal.ZERO),
                numberService.getMathContext());
        if (positionQuantity.compareTo(BigDecimal.ZERO) > 0) {
            documentBuilder.addPosition(product(deliveredProduct), positionQuantity,
                    price(deliveredProduct, currency), batch(deliveredProduct),
                    productionDate(deliveredProduct), expirationDate(deliveredProduct));
        }
    }
    documentBuilder.setAccepted().build();
}

From source file:com.arpnetworking.tsdcore.statistics.MeanStatistic.java

/**
 * {@inheritDoc}/*from   w  w  w .j a v a  2  s.  co  m*/
 */
@Override
public Quantity calculateAggregations(final List<AggregatedData> aggregations) {
    double weighted = 0D;
    int count = 0;
    Optional<Unit> unit = Optional.absent();
    for (final AggregatedData aggregation : aggregations) {
        final double populationSize = aggregation.getPopulationSize();
        weighted += aggregation.getValue().getValue() * populationSize;
        count += populationSize;
        unit = unit.or(aggregation.getValue().getUnit());
    }
    return new Quantity.Builder().setValue(weighted / count).setUnit(unit.orNull()).build();
}

From source file:com.pinterest.deployservice.db.DBBuildDAOImpl.java

@Override
public List<BuildBean> get(String scmCommit, String buildName, String scmBranch, Optional<Integer> pageIndex,
        Optional<Integer> pageSize, Long before, Long after) throws Exception {

    if (!StringUtils.isEmpty(scmCommit)) {
        return this.getByCommit7(StringUtils.substring(scmCommit, 0, 7), pageIndex.or(1),
                pageSize.or(DEFAULT_SIZE));
    }/*  w ww  . ja va  2  s .c o  m*/

    if (!StringUtils.isEmpty(buildName)) {
        if (before != null && after != null) {
            return this.getByNameDate(buildName, scmBranch, before, after);
        } else {
            return this.getByName(buildName, scmBranch, pageIndex.or(1), pageSize.or(DEFAULT_SIZE));
        }
    }

    return new ArrayList<>();
}

From source file:org.envirocar.server.rest.pagination.PaginationProviderImpl.java

private Optional<Pagination> getPaginationFromQueryParam() throws BadRequestException {
    Optional<Integer> limit = getQueryParameterValue(RESTConstants.LIMIT).or(getQueryParameterValue("l"));
    Optional<Integer> page = getQueryParameterValue(RESTConstants.PAGE).or(getQueryParameterValue("p"));
    if (limit.isPresent() || page.isPresent()) {
        return Optional.<Pagination>of(new PageBasedPagination(limit.or(DEFAULT_LIMIT), page.or(DEFAULT_PAGE)));
    }//  w  w  w.j  a  va2s.c om
    return Optional.absent();
}