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.locationtech.geogig.repository.WorkingTree.java

/**
 * Returns true if there are no unstaged changes, false otherwise
 *//*from   w w  w.jav  a  2s  .c  o  m*/
public boolean isClean() {
    Optional<ObjectId> resolved = context.command(ResolveTreeish.class).setTreeish(Ref.STAGE_HEAD).call();
    return getTree().getId().equals(resolved.or(ObjectId.NULL));
}

From source file:brooklyn.event.basic.PortAttributeSensorAndConfigKey.java

@Override
protected Integer convertConfigToSensor(PortRange value, Entity entity) {
    if (value == null)
        return null;
    Collection<? extends Location> locations = entity.getLocations();
    if (!locations.isEmpty()) {
        Maybe<? extends Location> lo = Locations.findUniqueMachineLocation(locations);
        if (!lo.isPresent()) {
            // Try a unique location which isn't a machine provisioner
            Iterator<? extends Location> li = Iterables
                    .filter(locations, Predicates.not(Predicates.instanceOf(MachineProvisioningLocation.class)))
                    .iterator();/*www . j  av a  2 s . c om*/
            if (li.hasNext())
                lo = Maybe.of(li.next());
            if (li.hasNext())
                lo = Maybe.absent();
        }
        // Fall back to selecting the single location
        if (!lo.isPresent() && locations.size() == 1) {
            lo = Maybe.of(locations.iterator().next());
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("Convert config to sensor for {} found locations: {}. Selected: {}",
                    new Object[] { entity, locations, lo });
        }
        if (lo.isPresent()) {
            Location l = lo.get();
            Optional<Boolean> locationRunning = Optional
                    .fromNullable(l.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
            Optional<Boolean> entityRunning = Optional
                    .fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
            Optional<Boolean> locationInstalled = Optional
                    .fromNullable(l.getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
            Optional<Boolean> entityInstalled = Optional
                    .fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
            Optional<Boolean> entityStarted = Optional
                    .fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START));
            boolean skipCheck = locationRunning.or(entityRunning).or(locationInstalled).or(entityInstalled)
                    .or(entityStarted).or(false);
            if (l instanceof PortSupplier) {
                int p = ((PortSupplier) l).obtainPort(value);
                if (p != -1) {
                    LOG.debug("{}: choosing port {} for {}", new Object[] { entity, p, getName() });
                    return p;
                }
                // If we are not skipping install or already started, fail now
                if (!skipCheck) {
                    int rangeSize = Iterables.size(value);
                    if (rangeSize == 0) {
                        LOG.warn("{}: no port available for {} (empty range {})",
                                new Object[] { entity, getName(), value });
                    } else if (rangeSize == 1) {
                        Integer pp = value.iterator().next();
                        if (pp > 1024) {
                            LOG.warn("{}: port {} not available for {}",
                                    new Object[] { entity, pp, getName() });
                        } else {
                            LOG.warn("{}: port {} not available for {} (root may be required?)",
                                    new Object[] { entity, pp, getName() });
                        }
                    } else {
                        LOG.warn("{}: no port available for {} (tried range {})",
                                new Object[] { entity, getName(), value });
                    }
                    return null; // Definitively, no ports available
                }
            }
            // Ports may be available, we just can't tell from the location
            Integer v = (value.isEmpty() ? null : value.iterator().next());
            LOG.debug("{}: choosing port {} (unconfirmed) for {}", new Object[] { entity, v, getName() });
            return v;
        } else {
            LOG.warn(
                    "{}: ports not applicable, or not yet applicable, because has multiple locations {}; ignoring ",
                    new Object[] { entity, locations, getName() });
        }
    } else {
        LOG.warn("{}: ports not applicable, or not yet applicable, bacause has no locations; ignoring {}",
                entity, getName());
    }
    return null;
}

From source file:org.jclouds.abiquo.compute.strategy.CreateGroupBeforeCreatingNodes.java

@Override
public Map<?, ListenableFuture<Void>> execute(final String group, int count, Template template,
        Set<NodeMetadata> goodNodes, Map<NodeMetadata, Exception> badNodes,
        Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {
    // Get the zone where the template will be deployed
    Integer locationId = Integer.valueOf(template.getHardware().getLocation().getId());
    VirtualDatacenter vdc = cloudService.getVirtualDatacenter(locationId);

    // Check if it already exists a group with the given name
    Iterable<VirtualAppliance> existingGroups = vdc.listVirtualAppliances();
    Optional<VirtualAppliance> vapp = tryFind(existingGroups, new Predicate<VirtualAppliance>() {
        @Override//  ww w. j a  v  a 2  s.  co  m
        public boolean apply(VirtualAppliance input) {
            return input.getName().equals(group);
        }
    });

    // Create the group if still does not exist
    VirtualAppliance newVapp = null;
    if (!vapp.isPresent()) {
        logger.debug(">> Creating group %s", group);
        newVapp = VirtualAppliance.builder(context, vdc).name(group).build();
        newVapp.save();
        logger.debug("<< group(%s) created", newVapp.getId());
    } else {
        logger.debug(">> Using existing group(%s)", vapp.get().getId());
    }

    VirtualApplianceCachingTemplate abiquoTemplate = VirtualApplianceCachingTemplate //
            .from(template) //
            .withVirtualDatacenter(vdc) //
            .withVirtualAppliance(vapp.or(newVapp)) //
            .build();

    return super.execute(group, count, abiquoTemplate, goodNodes, badNodes, customizationResponses);
}

From source file:com.mycelium.wallet.activity.main.NoticeFragment.java

private void showPinResetWarning() {
    Optional<Integer> resetPinRemainingBlocksCount = _mbwManager.getResetPinRemainingBlocksCount();

    if (!resetPinRemainingBlocksCount.isPresent()) {
        recheckNotice();//  w  w  w .  java2 s . c o m
        return;
    }

    if (resetPinRemainingBlocksCount.get() == 0) {
        // delay is done
        _mbwManager.showClearPinDialog(this.getActivity(), Optional.<Runnable>of(new Runnable() {
            @Override
            public void run() {
                recheckNotice();
            }
        }));
        return;
    }

    // delay is still remaining, provide option to abort
    String remaining = Utils.formatBlockcountAsApproxDuration(this.getActivity(),
            resetPinRemainingBlocksCount.or(1));
    new AlertDialog.Builder(this.getActivity())
            .setMessage(String.format(this.getActivity().getString(R.string.pin_forgotten_abort_pin_reset),
                    remaining))
            .setTitle(this.getActivity().getString(R.string.pin_forgotten_reset_pin_dialog_title))
            .setPositiveButton(this.getActivity().getString(R.string.yes),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            _mbwManager.getMetadataStorage().clearResetPinStartBlockheight();
                            recheckNotice();
                        }
                    })
            .setNegativeButton(this.getActivity().getString(R.string.no),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // nothing to do here
                        }
                    })
            .show();
}

From source file:org.sosy_lab.cpachecker.cpa.interval.IntervalAnalysisTransferRelation.java

/**
 * This method handles the statement edge which leads the function to the last node of its CFA (not same as a return edge).
 *
 * @param element the analysis element/*from  w  w  w .  j ava2 s.c  o m*/
 * @param expression the expression
 * @param CReturnStatementEdge the CFA edge corresponding to this statement
 * @return the successor elements
 */
private IntervalAnalysisState handleExitFromFunction(IntervalAnalysisState element,
        Optional<CExpression> expression, CReturnStatementEdge returnEdge, CFAEdge edge)
        throws UnrecognizedCCodeException {

    CExpression exp = expression.or(CIntegerLiteralExpression.ZERO); // 0 is the default in C

    ExpressionValueVisitor visitor = new ExpressionValueVisitor(element,
            returnEdge.getPredecessor().getFunctionName(), edge);

    // assign the value of the function return to a new variable
    return handleAssignmentToVariable(RETURN_VARIABLE_BASE_NAME, exp, visitor);
}

From source file:org.apache.brooklyn.entity.software.base.AbstractSoftwareProcessDriver.java

/**
 * Start the entity.//w w w.j  a  va  2 s.  co m
 * <p>
 * This installs, configures and launches the application process. However,
 * users can also call the {@link #install()}, {@link #customize()} and
 * {@link #launch()} steps independently. The {@link #postLaunch()} will
 * be called after the {@link #launch()} metheod is executed, but the
 * process may not be completely initialised at this stage, so care is
 * required when implementing these stages.
 * <p>
 * The {@link BrooklynConfigKeys#ENTITY_STARTED} key can be set on the location
 * or the entity to skip the startup process if the entity is already running,
 * according to the {@link #isRunning()} method. To force the startup to be
 * skipped, {@link BrooklynConfigKeys#SKIP_ENTITY_START} can be set on the entity.
 * The {@link BrooklynConfigKeys#SKIP_ENTITY_INSTALLATION} key can also be used to
 * skip the {@link #setup()}, {@link #copyInstallResources()} and
 * {@link #install()} methods if set on the entity or location. 
 *
 * @see #stop()
 */
@Override
public void start() {
    boolean skipStart = false;
    Optional<Boolean> locationRunning = Optional
            .fromNullable(getLocation().getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
    Optional<Boolean> entityRunning = Optional
            .fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START_IF_RUNNING));
    Optional<Boolean> entityStarted = Optional
            .fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_START));
    if (locationRunning.or(entityRunning).or(false)) {
        skipStart = isRunning();
    } else {
        skipStart = entityStarted.or(false);
    }
    if (!skipStart) {
        DynamicTasks.queue("install", new Runnable() {
            public void run() {

                Optional<Boolean> locationInstalled = Optional
                        .fromNullable(getLocation().getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
                Optional<Boolean> entityInstalled = Optional
                        .fromNullable(entity.getConfig(BrooklynConfigKeys.SKIP_ENTITY_INSTALLATION));
                boolean skipInstall = locationInstalled.or(entityInstalled).or(false);
                if (!skipInstall) {
                    DynamicTasks.queue("copy-pre-install-resources", new Runnable() {
                        public void run() {
                            waitForConfigKey(BrooklynConfigKeys.PRE_INSTALL_RESOURCES_LATCH);
                            copyPreInstallResources();
                        }
                    });

                    DynamicTasks.queue("pre-install", new Runnable() {
                        public void run() {
                            preInstall();
                        }
                    });

                    DynamicTasks.queue("pre-install-command", new Runnable() {
                        public void run() {
                            runPreInstallCommand();
                        }
                    });
                    DynamicTasks.queue("setup", new Runnable() {
                        public void run() {
                            waitForConfigKey(BrooklynConfigKeys.SETUP_LATCH);
                            setup();
                        }
                    });

                    DynamicTasks.queue("copy-install-resources", new Runnable() {
                        public void run() {
                            waitForConfigKey(BrooklynConfigKeys.INSTALL_RESOURCES_LATCH);
                            copyInstallResources();
                        }
                    });

                    DynamicTasks.queue("install (main)", new Runnable() {
                        public void run() {
                            waitForConfigKey(BrooklynConfigKeys.INSTALL_LATCH);
                            install();
                        }
                    });
                }

                DynamicTasks.queue("post-install-command", new Runnable() {
                    public void run() {
                        runPostInstallCommand();
                    }
                });
            }
        });

        DynamicTasks.queue("customize", new Runnable() {
            public void run() {
                waitForConfigKey(BrooklynConfigKeys.CUSTOMIZE_LATCH);
                customize();
            }
        });

        DynamicTasks.queue("launch", new Runnable() {
            public void run() {
                DynamicTasks.queue("copy-runtime-resources", new Runnable() {
                    public void run() {
                        waitForConfigKey(BrooklynConfigKeys.RUNTIME_RESOURCES_LATCH);
                        copyRuntimeResources();
                    }
                });

                DynamicTasks.queue("pre-launch-command", new Runnable() {
                    public void run() {
                        runPreLaunchCommand();
                    }
                });

                DynamicTasks.queue("launch (main)", new Runnable() {
                    public void run() {
                        waitForConfigKey(BrooklynConfigKeys.LAUNCH_LATCH);
                        launch();
                    }
                });

                DynamicTasks.queue("post-launch-command", new Runnable() {
                    public void run() {
                        runPostLaunchCommand();
                    }
                });
            }
        });
    }

    DynamicTasks.queue("post-launch", new Runnable() {
        public void run() {
            postLaunch();
        }
    });
}

From source file:org.apache.rya.indexing.pcj.storage.accumulo.PcjTables.java

/**
 * Creates a new PCJ Table in Accumulo and populates it by scanning an
 * instance of Rya for historic matches.
 * <p>//from   ww w  .j a v a 2s. c  o m
 * If any portion of this operation fails along the way, the partially
 * create PCJ table will be left in Accumulo.
 *
 * @param ryaConn - Connects to the Rya that will be scanned. (not null)
 * @param accumuloConn - Connects to the accumulo that hosts the PCJ results. (not null)
 * @param pcjTableName - The name of the PCJ table that will be created. (not null)
 * @param sparql - The SPARQL query whose results will be loaded into the table. (not null)
 * @param resultVariables - The variables that are included in the query's resulting binding sets. (not null)
 * @param pcjVarOrderFactory - An optional factory that indicates the various variable orders
 *   the results will be stored in. If one is not provided, then {@link ShiftVarOrderFactory}
 *   is used by default. (not null)
 * @throws PCJStorageException The PCJ table could not be create or the values from
 *   Rya were not able to be loaded into it.
 */
public void createAndPopulatePcj(final RepositoryConnection ryaConn, final Connector accumuloConn,
        final String pcjTableName, final String sparql, final String[] resultVariables,
        final Optional<PcjVarOrderFactory> pcjVarOrderFactory) throws PCJStorageException {
    checkNotNull(ryaConn);
    checkNotNull(accumuloConn);
    checkNotNull(pcjTableName);
    checkNotNull(sparql);
    checkNotNull(resultVariables);
    checkNotNull(pcjVarOrderFactory);

    // Create the PCJ's variable orders.
    final PcjVarOrderFactory varOrderFactory = pcjVarOrderFactory.or(DEFAULT_VAR_ORDER_FACTORY);
    final Set<VariableOrder> varOrders = varOrderFactory.makeVarOrders(new VariableOrder(resultVariables));

    // Create the PCJ table in Accumulo.
    createPcjTable(accumuloConn, pcjTableName, varOrders, sparql);

    // Load historic matches from Rya into the PCJ table.
    populatePcj(accumuloConn, pcjTableName, ryaConn);
}

From source file:org.mayocat.image.DefaultImageService.java

public Optional<Dimension> newDimension(Attachment attachment, Optional<Integer> width,
        Optional<Integer> height) throws IOException {
    int imageWidth = -1;
    int imageHeight = -1;

    if (attachment.getMetadata().containsKey("imageDimensions")) {
        // First, try to exploit stored metadata

        imageWidth = (int) attachment.getMetadata().get("imageDimensions").get("width");
        imageHeight = (int) attachment.getMetadata().get("imageDimensions").get("height");
    } else {/* w w w .java2s  . c  om*/
        // Fallback on loading the image
        LoadedAttachment loadedAttachment = this.attachmentStore.get().findAndLoadById(attachment.getId());
        Image image = loadedAttachment.getData().getObject(loadImage, Image.class);

        imageWidth = image.getWidth(null);
        imageHeight = image.getHeight(null);
    }

    if (imageHeight == height.or(imageHeight) && imageWidth == width.or(imageWidth)) {
        return Optional.absent();
    }

    int requestedWidth = width.or(-1);
    int requestedHeight = height.or(-1);
    int newWidth = imageWidth;
    int newHeight = imageHeight;

    double aspectRatio = (double) imageWidth / (double) imageHeight;

    if (requestedWidth <= 0 || requestedWidth >= imageWidth) {
        // Ignore the requested width. Check the requested height.
        if (requestedHeight > 0 && requestedHeight < imageHeight) {
            // Reduce the height, keeping aspect ratio.
            newWidth = (int) (requestedHeight * aspectRatio);
            newHeight = requestedHeight;
        }
    } else if (requestedHeight <= 0 || requestedHeight >= imageHeight) {
        // Ignore the requested height. Reduce the width, keeping aspect ratio.
        newWidth = requestedWidth;
        newHeight = (int) (requestedWidth / aspectRatio);
    } else {
        // Reduce the width and check if the corresponding height is less than the requested height.
        newWidth = requestedWidth;
        newHeight = (int) (requestedWidth / aspectRatio);
        if (newHeight > requestedHeight) {
            // We have to reduce the height instead and compute the width based on it.
            newWidth = (int) (requestedHeight * aspectRatio);
            newHeight = requestedHeight;
        }
    }

    if (newWidth != imageWidth && newHeight != imageHeight) {
        return Optional.of(new Dimension(newWidth, newHeight));
    } else {
        return Optional.absent();
    }
}

From source file:org.locationtech.geogig.cli.porcelain.Show.java

private void printRaw(GeogigCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();/*from  w  w w  .  j  a v a2  s .  c o  m*/
    for (String ref : refs) {
        Optional<RevObject> obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        if (!obj.isPresent()) {
            ref = getFullRef(ref);
            obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        }
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            if (opt.isPresent()) {
                RevFeatureType ft = opt.get();
                ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
                RevFeature feature = (RevFeature) revObject;
                Ansi ansi = super.newAnsi(console.getTerminal());
                ansi.a(ref).newline();
                ansi.a(feature.getId().toString()).newline();
                ImmutableList<Optional<Object>> values = feature.getValues();
                int i = 0;
                for (Optional<Object> value : values) {
                    PropertyDescriptor attrib = attribs.get(i);
                    ansi.a(attrib.getName()).newline();
                    PropertyType attrType = attrib.getType();
                    String typeName = FieldType.forBinding(attrType.getBinding()).name();
                    if (attrType instanceof GeometryType) {
                        GeometryType gt = (GeometryType) attrType;
                        CoordinateReferenceSystem crs = gt.getCoordinateReferenceSystem();
                        String crsText = CrsTextSerializer.serialize(crs);
                        ansi.a(typeName).a(" ").a(crsText).newline();
                    } else {
                        ansi.a(typeName).newline();
                    }
                    ansi.a(value.or("[NULL]").toString()).newline();
                    i++;
                }
                console.println(ansi.toString());
            } else {
                CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject))
                        .call();
                console.println(s);
            }
        } else {
            CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject)).call();
            console.println(s);
        }
    }
}

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

@GET
@Path("/synchronize")
@Produces(MediaType.APPLICATION_JSON)//www . j av  a  2  s.c  o  m
/** url called via ajax by client to rebalance a job */
public Response synchronizeJob(@QueryParam("id") @DefaultValue("") String id,
        @QueryParam("user") Optional<String> user) {
    emitLogLineForAction(user.or(defaultUser), "job synchronize on " + id);
    if (spawn.synchronizeJobState(id)) {
        return Response.ok("{id:'" + id + "',action:'synchronzied'}").build();
    } else {
        log.warn("[job.synchronize] " + id + " unable to synchronize job");
        return Response.status(Response.Status.NOT_FOUND).header("topic", "Synchronize Error")
                .entity("{error:'unable to synchronize job, check spawn log file for more details'}").build();
    }
}