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.mayocat.rest.resources.AbstractImageResource.java

public Response downloadThumbnail(String tenantSlug, String slug, String extension, Integer x, Integer y,
        Integer width, Integer height, ServletContext servletContext, Optional<ImageOptions> imageOptions) {
    if (!IMAGE_EXTENSIONS.contains(extension)) {
        // Refuse to treat a request with image options for a non-image attachment
        return Response.status(Response.Status.BAD_REQUEST).entity("Not an image").build();
    }/* www. j av  a  2  s.c om*/

    String fileName = slug + "." + extension;
    Attachment file;

    if (tenantSlug == null) {
        file = this.attachmentStore.get().findBySlugAndExtension(slug, extension);
    } else {
        file = this.attachmentStore.get().findByTenantAndSlugAndExtension(tenantSlug, slug, extension);
    }

    if (file == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    try {
        Rectangle boundaries = new Rectangle(x, y, width, height);

        if (imageOptions.isPresent()) {
            Optional<Dimension> newDimension = imageService.newDimension(boundaries,
                    imageOptions.get().getWidth(), imageOptions.get().getHeight());

            Dimension dimensions = newDimension.or(
                    new Dimension(imageOptions.get().getWidth().or(-1), imageOptions.get().getHeight().or(-1)));

            return Response
                    .ok(imageService.getImage(file, dimensions, boundaries),
                            servletContext.getMimeType(fileName))
                    .header("Content-disposition", "inline; filename*=utf-8''" + fileName).build();
        } else {
            return Response.ok(imageService.getImage(file, boundaries), servletContext.getMimeType(fileName))
                    .header("Content-disposition", "inline; filename*=utf-8''" + fileName).build();
        }
    } catch (IOException e) {
        this.logger.warn("Failed to scale image for attachment [{slug}]", slug);
        return Response.serverError().entity("Failed to scale image").build();
    }
}

From source file:net.sourceforge.jwbf.core.contentRep.SimpleArticle.java

private Date tryParse(String editTimestamp) {
    Optional<Date> parsedDate = //
            TimeConverter.from(editTimestamp, TimeConverter.YYYYMMDD_T_HHMMSS_Z);
    return parsedDate.or(TimeConverter.from(editTimestamp, "MM/dd/yy' 'HH:mm:ss")).get();
}

From source file:com.intuit.wasabi.authorization.impl.DefaultAuthorization.java

private UserInfo.Username parseUsername(Optional<String> authHeader) {
    if (!authHeader.isPresent()) {
        throw new AuthenticationException("Null Authentication Header is not supported");
    }/*from  w  w  w . j  a  v a2  s.c  om*/

    if (!authHeader.or(SPACE).contains(BASIC)) {
        throw new AuthenticationException("Only Basic Authentication is supported");
    }

    final String encodedUserPassword = authHeader.get().substring(authHeader.get().lastIndexOf(SPACE));
    LOGGER.trace("Base64 decoded username and password is: {}", encodedUserPassword);
    String usernameAndPassword;
    try {
        usernameAndPassword = new String(Base64.decodeBase64(encodedUserPassword.getBytes()));
    } catch (Exception e) {
        throw new AuthenticationException("error parsing username and password", e);
    }

    //Split username and password tokens
    String[] fields = usernameAndPassword.split(COLON);

    if (fields.length > 2) {
        throw new AuthenticationException("More than one username and password provided, or one contains ':'");
    } else if (fields.length < 2) {
        throw new AuthenticationException("Username or password are empty.");
    }

    if (StringUtils.isBlank(fields[0]) || StringUtils.isBlank(fields[1])) {
        throw new AuthenticationException("Username or password are empty.");
    }

    return UserInfo.Username.valueOf(fields[0]);
}

From source file:org.apache.brooklyn.feed.shell.ShellFeed.java

@Override
protected void preStart() {
    SetMultimap<ShellPollIdentifier, ShellPollConfig<?>> polls = getConfig(POLLS);

    for (final ShellPollIdentifier pollInfo : polls.keySet()) {
        Set<ShellPollConfig<?>> configs = polls.get(pollInfo);
        long minPeriod = Integer.MAX_VALUE;
        Set<AttributePollHandler<? super SshPollValue>> handlers = Sets.newLinkedHashSet();

        for (ShellPollConfig<?> config : configs) {
            handlers.add(new AttributePollHandler<SshPollValue>(config, entity, this));
            if (config.getPeriod() > 0)
                minPeriod = Math.min(minPeriod, config.getPeriod());
        }//w  w w .j a va  2 s  .c o m

        final ProcessTaskFactory<?> taskFactory = newTaskFactory(pollInfo.command, pollInfo.env, pollInfo.dir,
                pollInfo.input, pollInfo.context, pollInfo.timeout);
        final ExecutionContext executionContext = ((EntityInternal) entity).getManagementSupport()
                .getExecutionContext();

        getPoller().scheduleAtFixedRate(new Callable<SshPollValue>() {
            @Override
            public SshPollValue call() throws Exception {
                ProcessTaskWrapper<?> taskWrapper = taskFactory.newTask();
                executionContext.submit(taskWrapper);
                taskWrapper.block();
                Optional<Integer> exitCode = Optional.fromNullable(taskWrapper.getExitCode());
                return new SshPollValue(null, exitCode.or(-1), taskWrapper.getStdout(),
                        taskWrapper.getStderr());
            }
        }, new DelegatingPollHandler<SshPollValue>(handlers), minPeriod);
    }
}

From source file:com.pinterest.teletraan.resource.Groups.java

@GET
@Path("/{groupName: [a-zA-Z0-9\\-_]+}/healthchecks")
public List<HealthCheckBean> getHealthChecks(@PathParam("groupName") String groupName,
        @QueryParam("pageIndex") Optional<Integer> pageIndex,
        @QueryParam("pageSize") Optional<Integer> pageSize) throws Exception {
    return healthCheckHandler.getHealthChecksByGroup(groupName, pageIndex.or(1), pageSize.or(DEFAULT_SIZE));
}

From source file:com.pinterest.teletraan.resource.Groups.java

@GET
@Path("/{groupName: [a-zA-Z0-9\\-_]+}/configs/history")
public List<ConfigHistoryBean> getConfigHistory(@PathParam("groupName") String groupName,
        @QueryParam("pageIndex") Optional<Integer> pageIndex,
        @QueryParam("pageSize") Optional<Integer> pageSize) throws Exception {
    return configHistoryHandler.getConfigHistoryByName(groupName, pageIndex.or(1), pageSize.or(DEFAULT_SIZE));
}

From source file:com.github.autermann.wps.streaming.StreamingExecutor.java

@Override
public OutputMessage execute(InputMessage input, Iterable<OutputMessage> dependencies) throws StreamingError {
    try {//from  www . j  a v a  2  s  .co  m
        ProcessInputs inputs = resolve(dependencies, input);
        Optional<ProcessOutputs> outputs = execute(inputs);
        OutputMessage output = new OutputMessage();
        addProvenance(output, dependencies);
        output.addRelatedMessage(RelationshipType.Reply, input);
        output.setPayload(outputs.or(ProcessOutputs.none()));
        output.setProcessID(this.id);
        if (outputs.isPresent()) {
            this.callback.receive(output);
        }
        return output;
    } catch (StreamingError ex) {
        this.callback.receive(ex.toMessage(input));
        throw ex;
    }
}

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

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

    for (final Host host : hosts) {
        final Set<String> mountPoints = mountPointsByHost.get(host);
        mountPointsIntersection = Tools.getIntersection(Optional.fromNullable(mountPoints),
                mountPointsIntersection);
    }/* ww w  .  j  av a2  s  .  c o  m*/
    return mountPointsIntersection.or(new TreeSet<String>());
}

From source file:info.archinnov.achilles.internal.statement.prepared.PreparedStatementBinder.java

public BoundStatementWrapper bindForUpdate(PreparedStatement ps, EntityMeta entityMeta, List<PropertyMeta> pms,
        Object entity, ConsistencyLevel consistencyLevel, Optional<Integer> ttlO) {
    log.trace("Bind prepared statement {} for properties {} update of entity {}", ps.getQueryString(), pms,
            entity);// w  ww  .  j  a  va2  s.c om
    List<Object> values = new ArrayList<>();
    // TTL or default value 0
    values.add(ttlO.or(0));
    for (PropertyMeta pm : pms) {
        Object value = pm.getAndEncodeValueForCassandra(entity);
        values.add(value);
    }
    Object primaryKey = entityMeta.getPrimaryKey(entity);
    values.addAll(bindPrimaryKey(primaryKey, entityMeta.getIdMeta()));
    BoundStatement bs = ps.bind(values.toArray());

    return new BoundStatementWrapper(bs, values.toArray(), getCQLLevel(consistencyLevel));
}

From source file:gobblin.instrumented.qualitychecker.InstrumentedRowLevelPolicyBase.java

protected InstrumentedRowLevelPolicyBase(State state, Type type, Optional<Class<?>> classTag) {
    super(state, type);
    this.instrumentationEnabled = GobblinMetrics.isEnabled(state);
    this.closer = Closer.create();
    this.metricContext = this.closer
            .register(Instrumented.getMetricContext(state, classTag.or(this.getClass())));

    regenerateMetrics();//ww w  .j a  va2  s . c om
}