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:springfox.documentation.swagger.readers.operation.SwaggerResponseMessageReader.java

protected Set<ResponseMessage> read(OperationContext context) {
    ResolvedType defaultResponse = context.getReturnType();
    Optional<ApiOperation> operationAnnotation = context.findAnnotation(ApiOperation.class);
    Optional<ResolvedType> operationResponse = operationAnnotation
            .transform(resolvedTypeFromOperation(typeResolver, defaultResponse));
    Optional<ResponseHeader[]> defaultResponseHeaders = operationAnnotation.transform(responseHeaders());
    Map<String, Header> defaultHeaders = newHashMap();
    if (defaultResponseHeaders.isPresent()) {
        defaultHeaders.putAll(headers(defaultResponseHeaders.get()));
    }/*ww  w  .  j  a  v a2 s  . co  m*/

    List<ApiResponses> allApiResponses = context.findAllAnnotations(ApiResponses.class);
    Set<ResponseMessage> responseMessages = newHashSet();

    Map<Integer, ApiResponse> seenResponsesByCode = newHashMap();
    for (ApiResponses apiResponses : allApiResponses) {
        ApiResponse[] apiResponseAnnotations = apiResponses.value();
        for (ApiResponse apiResponse : apiResponseAnnotations) {
            if (!seenResponsesByCode.containsKey(apiResponse.code())) {
                seenResponsesByCode.put(apiResponse.code(), apiResponse);
                ModelContext modelContext = returnValue(apiResponse.response(), context.getDocumentationType(),
                        context.getAlternateTypeProvider(), context.getGenericsNamingStrategy(),
                        context.getIgnorableParameterTypes());
                Optional<ModelReference> responseModel = Optional.absent();
                Optional<ResolvedType> type = resolvedType(null, apiResponse);
                if (isSuccessful(apiResponse.code())) {
                    type = type.or(operationResponse);
                }
                if (type.isPresent()) {
                    responseModel = Optional.of(modelRefFactory(modelContext, typeNameExtractor)
                            .apply(context.alternateFor(type.get())));
                }
                Map<String, Header> headers = newHashMap(defaultHeaders);
                headers.putAll(headers(apiResponse.responseHeaders()));

                responseMessages.add(
                        new ResponseMessageBuilder().code(apiResponse.code()).message(apiResponse.message())
                                .responseModel(responseModel.orNull()).headersWithDescription(headers).build());
            }
        }
    }
    if (operationResponse.isPresent()) {
        ModelContext modelContext = returnValue(operationResponse.get(), context.getDocumentationType(),
                context.getAlternateTypeProvider(), context.getGenericsNamingStrategy(),
                context.getIgnorableParameterTypes());
        ResolvedType resolvedType = context.alternateFor(operationResponse.get());

        ModelReference responseModel = modelRefFactory(modelContext, typeNameExtractor).apply(resolvedType);
        context.operationBuilder().responseModel(responseModel);
        ResponseMessage defaultMessage = new ResponseMessageBuilder().code(httpStatusCode(context))
                .message(message(context)).responseModel(responseModel).build();
        if (!responseMessages.contains(defaultMessage) && !"void".equals(responseModel.getType())) {
            responseMessages.add(defaultMessage);
        }
    }
    return responseMessages;
}

From source file:co.cask.cdap.cli.command.system.HelpCommand.java

/**
 * Recursive helper for {@link #categorizeCommands(Iterable, CommandCategory, Predicate)}.
 *///ww  w . j  av  a 2  s .co  m
private void populate(Multimap<String, Command> result, CommandSet<Command> commandSet,
        Optional<String> parentCategory, CommandCategory defaultCategory, Predicate<Command> filter) {

    for (Command childCommand : Iterables.filter(commandSet.getCommands(), filter)) {
        Optional<String> commandCategory = getCategory(childCommand).or(parentCategory);
        result.put(commandCategory.or(defaultCategory.getName()), childCommand);
    }

    for (CommandSet<Command> childCommandSet : commandSet.getCommandSets()) {
        Optional<String> commandCategory = getCategory(childCommandSet).or(parentCategory);
        populate(result, childCommandSet, commandCategory, defaultCategory, filter);
    }
}

From source file:org.jclouds.openstack.keystone.v1_1.suppliers.V1DefaultRegionIdSupplier.java

/**
 * returns {@link Endpoint#isV1Default()} or first endpoint for service
 *//*from   w w  w.  ja  va  2  s.  c o  m*/
@Override
public String get() {
    Auth authResponse = auth.get();
    Iterable<Endpoint> endpointsForService = authResponse.getServiceCatalog().get(apiType);
    Optional<Endpoint> defaultEndpoint = tryFind(endpointsForService, new Predicate<Endpoint>() {
        @Override
        public boolean apply(Endpoint in) {
            return in.isV1Default();
        }
    });
    return endpointToRegion.apply(defaultEndpoint.or(Iterables.get(endpointsForService, 0)));
}

From source file:com.voxelplugineering.voxelsniper.brush.effect.OldLinearBlendBrush.java

@Override
public ExecutionResult run(Player player, BrushVars args) {
    boolean excludeFluid = true;
    if (args.has(BrushKeys.EXCLUDE_FLUID)) {
        excludeFluid = args.get(BrushKeys.EXCLUDE_FLUID, Boolean.class).get();
    }//from w  w w. j  a  va 2 s.  c  o  m

    Optional<Shape> s = args.get(BrushKeys.SHAPE, Shape.class);
    if (!s.isPresent()) {
        player.sendMessage("You must have at least one shape brush before your blend brush.");
        return ExecutionResult.abortExecution();
    }

    Optional<Material> m = args.get(BrushKeys.MATERIAL, Material.class);
    if (!m.isPresent()) {
        player.sendMessage("You must select a material.");
        return ExecutionResult.abortExecution();
    }

    Optional<String> kernalShape = args.get(BrushKeys.KERNEL, String.class);
    Optional<Double> kernalSize = args.get(BrushKeys.KERNEL_SIZE, Double.class);
    double size = kernalSize.or(2.0);
    String kernelString = kernalShape.or("voxel");
    Optional<Shape> se = PrimativeShapeFactory.createShape(kernelString, size);
    if (!se.isPresent()) {
        se = Optional.<Shape>of(new CuboidShape(5, 5, 5, new Vector3i(2, 2, 2)));
    }

    Optional<Block> l = args.get(BrushKeys.TARGET_BLOCK, Block.class);
    MaterialShape ms = new ComplexMaterialShape(s.get(), m.get());

    World world = player.getWorld();
    Location loc = l.get().getLocation();
    Shape shape = s.get();
    Shape structElem = se.get();
    double maxX = Math.max(structElem.getWidth() - structElem.getOrigin().getX() - 1,
            structElem.getOrigin().getX());
    double maxY = Math.max(structElem.getHeight() - structElem.getOrigin().getY() - 1,
            structElem.getOrigin().getY());
    double maxZ = Math.max(structElem.getLength() - structElem.getOrigin().getZ() - 1,
            structElem.getOrigin().getZ());
    double maxDistance = Math.sqrt(maxX * maxX + maxY * maxY + maxZ * maxZ);

    // Extract the location in the world to x0, y0 and z0.
    for (int x = 0; x < ms.getWidth(); x++) {
        int x0 = loc.getFlooredX() + x - shape.getOrigin().getX();
        for (int y = 0; y < ms.getHeight(); y++) {
            int y0 = loc.getFlooredY() + y - shape.getOrigin().getY();
            for (int z = 0; z < ms.getLength(); z++) {
                int z0 = loc.getFlooredZ() + z - shape.getOrigin().getZ();
                if (!shape.get(x, y, z, false)) {
                    continue;
                }
                // Represents a histogram of material occurrences hit by the
                // structuring element.
                Map<Material, Double> mats = Maps.newHashMapWithExpectedSize(10);

                for (int a = 0; a < structElem.getWidth(); a++) {
                    for (int b = 0; b < structElem.getHeight(); b++) {
                        for (int c = 0; c < structElem.getLength(); c++) {
                            if (!structElem.get(a, b, c, false)) {
                                continue;
                            }
                            int a0 = a - structElem.getOrigin().getX();
                            int b0 = b - structElem.getOrigin().getY();
                            int c0 = c - structElem.getOrigin().getZ();

                            // TODO: Use world bounds instead of
                            // hardcoded magical values from Minecraft.
                            int clampedY = Maths.clamp(y0 + b0, 0, 255);
                            Material mat = world.getBlock(x0 + a0, clampedY, z0 + c0).get().getMaterial();
                            if (mats.containsKey(mat)) {
                                mats.put(mat,
                                        mats.get(mat) + maxDistance - Math.sqrt(a0 * a0 + b0 * b0 + c0 * c0));
                            } else {
                                mats.put(mat, maxDistance - Math.sqrt(a0 * a0 + b0 * b0 + c0 * c0));
                            }
                        }
                    }
                }
                // Select the material which occured the most.
                double n = 0;
                Material winner = null;
                for (Map.Entry<Material, Double> e : mats.entrySet()) {
                    System.out.println(e.getKey().getName() + ": " + e.getValue());
                    if (e.getValue() > n && !(excludeFluid && e.getKey().isLiquid())) {
                        winner = e.getKey();
                        n = e.getValue();
                    }
                }

                // If multiple materials occurred the most, the tie check
                // will become true.
                boolean tie = false;
                for (Map.Entry<Material, Double> e : mats.entrySet()) {
                    if (e.getValue() == n && !(excludeFluid && e.getKey().isLiquid())
                            && !e.getKey().equals(winner)) {
                        tie = true;
                    }
                }

                // If a tie is found, no change is made.
                if (!tie) {
                    ms.setMaterial(x, y, z, false, winner);
                }
            }
        }
    }
    new ShapeChangeQueue(player, loc, ms).flush();
    return ExecutionResult.continueExecution();
}

From source file:com.facebook.buck.cxx.DefaultCxxPlatform.java

private SourcePath getSourcePath(String section, String field, Path def) {
    Optional<Path> path = delegate.getPath(section, field);
    return new PathSourcePath(path.or(def));
}

From source file:org.jclouds.functions.ExpandProperties.java

private boolean resolveProperties(Map<String, String> properties, Map<String, String> variables) {
    boolean anyReplacementDone = false;
    for (Map.Entry<String, String> entry : properties.entrySet()) {
        String key = entry.getKey();
        StringBuffer sb = new StringBuffer();
        Matcher m = VAR.matcher(entry.getValue());
        while (m.find()) {
            String match = m.group();
            // Remove the ${} from the matched variable
            String var = match.substring(2, match.length() - 1);
            // Avoid recursive properties. Only get he value if the variable
            // is different than the current key
            Optional<String> value = var.equals(key) ? Optional.<String>absent()
                    : Optional.fromNullable(variables.get(var));
            // Replace by the value or leave the original value
            m.appendReplacement(sb, value.or("\\" + match));
            if (value.isPresent()) {
                anyReplacementDone = true;
            }//from w w  w . java2 s  .  c  o  m
        }
        m.appendTail(sb);
        properties.put(key, sb.toString());
    }
    return anyReplacementDone;
}

From source file:com.facebook.buck.cxx.DefaultCxxPlatform.java

private LinkerType getLinkerType() {
    Optional<LinkerType> type = delegate.getEnum("cxx", "ld_type", LinkerType.class);
    return type.or(getLinkerTypeForPlatform());
}

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

public DescribeResult(@NotNull String tagName, boolean dirty, @NotNull Optional<String> dirtyMarker) {
    this.tagName = Optional.of(tagName);
    this.dirty = dirty;
    this.dirtyMarker = dirtyMarker.or("");
}

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

@GET
@Path("/names")
public List<String> get(@QueryParam("nameFilter") Optional<String> nameFilter,
        @QueryParam("pageIndex") Optional<Integer> pageIndex,
        @QueryParam("pageSize") Optional<Integer> pageSize) throws Exception {
    return environDAO.getAllEnvNames(nameFilter.or(""), pageIndex.or(DEFAULT_INDEX), pageSize.or(DEFAULT_SIZE));
}

From source file:gobblin.runtime.locks.FileBasedJobLockFactory.java

/** Constructs a new factory
 * @throws IOException *//*from w  ww  . j  a  va  2  s.c om*/
public FileBasedJobLockFactory(FileSystem fs, String lockFileDir, Optional<Logger> log) throws IOException {
    this.fs = fs;
    this.lockFileDir = new Path(lockFileDir);
    this.log = log.or(LoggerFactory.getLogger(getClass().getName() + "-" + lockFileDir));
    this.deleteLockDirOnClose = !this.fs.exists(this.lockFileDir);
    if (deleteLockDirOnClose) {
        createLockDir(this.fs, this.lockFileDir);
    }
}