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.sonar.server.computation.task.projectanalysis.component.BranchPersisterImpl.java

public void persist(DbSession dbSession) {
    Branch branch = analysisMetadataHolder.getBranch();
    String branchUuid = treeRootHolder.getRoot().getUuid();

    com.google.common.base.Optional<ComponentDto> branchComponentDtoOpt = dbClient.componentDao()
            .selectByUuid(dbSession, branchUuid);

    ComponentDto branchComponentDto;//from  ww w . ja v  a  2  s.co  m
    if (branch.isMain()) {
        checkState(branchComponentDtoOpt.isPresent(), "Project has been deleted by end-user during analysis");
        branchComponentDto = branchComponentDtoOpt.get();

    } else {
        // inserts new row in table projects if it's the first time branch is analyzed
        branchComponentDto = branchComponentDtoOpt.or(() -> insertIntoProjectsTable(dbSession, branchUuid));

    }
    // insert or update in table project_branches
    dbClient.branchDao().upsert(dbSession, toBranchDto(branchComponentDto, branch));
}

From source file:pl.project13.jgit.DescribeCommand.java

/**
 * <pre>--dirty[=mark]</pre>
 * Describe the working tree. It means describe HEAD and appends mark (<pre>-dirty</pre> by default) if the
 * working tree is dirty./*from   w  w  w.  j a va2  s .c  o  m*/
 *
 * @param dirtyMarker the marker name to be appended to the describe output when the workspace is dirty
 * @return itself, to allow fluent configuration
 */
@NotNull
public DescribeCommand dirty(@Nullable String dirtyMarker) {
    Optional<String> option = Optional.fromNullable(dirtyMarker);
    log("--dirty = \"%s\"", option.or(""));
    this.dirtyOption = option;
    return this;
}

From source file:com.addthis.hydra.job.spawn.resources.ListenResource.java

@GET
@Path("/batch")
@Produces(MediaType.APPLICATION_JSON)/*from  w w  w . j a v  a 2s  .  c  om*/
public Response getListenBatch(@QueryParam("timeout") Optional<Integer> timeoutParameter,
        @QueryParam("batchtime") Optional<Integer> batchtimeParameter,
        @QueryParam("clientId") Optional<String> clientIdParameter) {
    Response response;
    String clientId = (clientIdParameter.isPresent() ? clientIdParameter.get() : "noid");
    int timeout = timeoutParameter.or(pollTimeout);
    int batchTime = batchtimeParameter.or(batchInterval);
    Spawn.ClientEventListener listener = spawn.getClientEventListener(clientId);
    try {
        Spawn.ClientEvent nextEvent = listener.events.poll(timeout, TimeUnit.MILLISECONDS);
        if (nextEvent != null) {
            long mark = System.currentTimeMillis();
            JSONArray payload = new JSONArray();
            payload.put(encodeJson(nextEvent));
            for (int i = 50; i > 0; i--) {
                nextEvent = listener.events.poll(batchTime, TimeUnit.MILLISECONDS);
                if (nextEvent != null) {
                    JSONObject json = encodeJson(nextEvent);
                    payload.put(json);
                }
                if (System.currentTimeMillis() - mark > batchTime) {
                    break;
                }
            }
            response = Response.ok(payload.toString()).build();
        } else {
            response = Response.notModified().build();
        }
    } catch (InterruptedException ex) {
        response = Response.notModified().build();
    } catch (Exception ex) {
        log.warn("", ex);
        response = Response.serverError().build();
    }
    return response;
}

From source file:gobblin.runtime.instance.DefaultGobblinInstanceDriverImpl.java

public DefaultGobblinInstanceDriverImpl(String instanceName, Configurable sysConfig, JobCatalog jobCatalog,
        JobSpecScheduler jobScheduler, JobExecutionLauncher jobLauncher,
        Optional<MetricContext> baseMetricContext, Optional<Logger> log,
        SharedResourcesBroker<GobblinScopeTypes> instanceBroker) {
    Preconditions.checkNotNull(jobCatalog);
    Preconditions.checkNotNull(jobScheduler);
    Preconditions.checkNotNull(jobLauncher);
    Preconditions.checkNotNull(sysConfig);

    _instanceName = instanceName;/*from  w  w w .  j  a  v  a2  s.c  o m*/
    _log = log.or(LoggerFactory.getLogger(getClass()));
    _metricCtx = baseMetricContext.or(constructMetricContext(sysConfig, _log));
    _instrumentationEnabled = null != _metricCtx && GobblinMetrics.isEnabled(sysConfig.getConfig());
    _jobCatalog = jobCatalog;
    _jobScheduler = jobScheduler;
    _jobLauncher = jobLauncher;
    _sysConfig = sysConfig;
    _instanceCfg = ConfigAccessor.createFromGlobalConfig(_sysConfig.getConfig());
    _callbacksDispatcher = new JobLifecycleListenersList(_jobCatalog, _jobScheduler, _log);
    _instanceBroker = instanceBroker;

    _metrics = new StandardMetrics(this);
}

From source file:com.spotify.reaper.resources.ClusterResource.java

private Response viewCluster(String clusterName, Optional<Integer> limit, Optional<URI> createdURI) {
    Optional<Cluster> cluster = context.storage.getCluster(clusterName);

    if (!cluster.isPresent()) {
        return Response.status(Response.Status.NOT_FOUND)
                .entity("cluster with name \"" + clusterName + "\" not found").build();
    } else {/* ww  w. j a  va 2  s. co m*/
        ClusterStatus view = new ClusterStatus(cluster.get(),
                context.storage.getClusterRunStatuses(clusterName, limit.or(Integer.MAX_VALUE)),
                context.storage.getClusterScheduleStatuses(clusterName));
        if (createdURI.isPresent()) {
            return Response.created(createdURI.get()).entity(view).build();
        } else {
            return Response.ok().entity(view).build();
        }
    }
}

From source file:org.geogit.api.porcelain.RemoteRemoveOp.java

/**
 * Executes the remote-remove operation.
 * // w w w .  j  a  va 2 s . c  o  m
 * @return the {@link Remote} that was removed, or {@link Optional#absent()} if the remote
 *         didn't exist.
 */
@Override
public Remote call() {
    if (name == null || name.isEmpty()) {
        throw new RemoteException(StatusCode.MISSING_NAME);
    }
    List<String> allRemotes = config.getAllSubsections("remote");
    if (!allRemotes.contains(name)) {
        throw new RemoteException(StatusCode.REMOTE_NOT_FOUND);
    }

    Remote remote = null;
    String remoteSection = "remote." + name;
    Optional<String> remoteFetchURL = config.get(remoteSection + ".url");
    Optional<String> remoteFetch = config.get(remoteSection + ".fetch");
    Optional<String> remotePushURL = Optional.absent();
    Optional<String> remoteMapped = config.get(remoteSection + ".mapped");
    Optional<String> remoteMappedBranch = config.get(remoteSection + ".mappedBranch");
    if (remoteFetchURL.isPresent() && remoteFetch.isPresent()) {
        remotePushURL = config.get(remoteSection + ".pushurl");
    }

    remote = new Remote(name, remoteFetchURL.or(""), remotePushURL.or(remoteFetchURL.or("")),
            remoteFetch.or(""), remoteMapped.or("false").equals("true"), remoteMappedBranch.orNull());

    config.removeSection(remoteSection);

    // Remove refs
    final ImmutableSet<Ref> localRemoteRefs = command(LsRemote.class).retrieveLocalRefs(true)
            .setRemote(Suppliers.ofInstance(Optional.of(remote))).call();

    for (Ref localRef : localRemoteRefs) {
        command(UpdateRef.class).setDelete(true).setName(localRef.getName()).call();
    }

    return remote;
}

From source file:co.paralleluniverse.fibers.dropwizard.MyDropwizardApp.java

@GET
@Path("/fluent")
@Timed//from ww w. j  a va  2s  .  c  o m
public Integer fluentAPI(@QueryParam("id") Optional<Integer> id)
        throws InterruptedException, SuspendExecution, IOException {
    try (Handle h = jdbi.open()) {
        h.execute("create table if not exists fluentAPI (id int primary key, name varchar(100))");
        for (int i = 0; i < 100; i++)
            h.execute("insert into fluentAPI (id, name) values (?, ?)", i, "stranger " + i);
        int size = h.createQuery("select name from fluentAPI where id < :id order by id").bind("id", id.or(50))
                .map(StringMapper.FIRST).list().size();
        h.execute("drop table fluentAPI");
        return size;
    }
}

From source file:org.jclouds.route53.domain.ResourceRecordSet.java

private ResourceRecordSet(String name, String type, Optional<Integer> ttl, List<String> values,
        Optional<AliasTarget> aliasTarget) {
    this.name = checkNotNull(name, "name");
    this.type = checkNotNull(type, "type of %s", name);
    this.ttl = checkNotNull(ttl, "ttl for %s", name);
    checkArgument(ttl.or(0) >= 0, "ttl of %s must be unsigned", name);
    this.values = checkNotNull(values, "values for %s", name);
    this.aliasTarget = checkNotNull(aliasTarget, "aliasTarget for %s", aliasTarget);
}

From source file:org.apache.james.transport.mailets.StripAttachment.java

private File outputFile(Part part, Optional<String> fileName) throws MessagingException, IOException {
    Optional<String> maybePartFileName = Optional.fromNullable(part.getFileName());
    return createTempFile(fileName.or(maybePartFileName).orNull());
}

From source file:org.restcomm.media.control.mgcp.command.CreateConnectionCommand.java

private String loadSecondEndpointId(Parameters<MgcpParameterType> parameters) throws MgcpCommandException {
    Optional<String> secondEndpointId = parameters.getString(MgcpParameterType.SECOND_ENDPOINT);
    if (secondEndpointId.isPresent()) {
        if (secondEndpointId.get().indexOf(WILDCARD_ALL) != -1) {
            throw new MgcpCommandException(MgcpResponseCode.WILDCARD_TOO_COMPLICATED);
        }/*from   w  ww .j a va2  s . c o  m*/
    }
    return secondEndpointId.or("");
}