Example usage for com.google.common.base Functions constant

List of usage examples for com.google.common.base Functions constant

Introduction

In this page you can find the example usage for com.google.common.base Functions constant.

Prototype

public static <E> Function<Object, E> constant(@Nullable E value) 

Source Link

Document

Creates a function that returns value for any input.

Usage

From source file:org.sosy_lab.cpachecker.cpa.invariants.formula.ReplaceVisitor.java

/**
 * Creates a new replace visitor for replacing occurrences of the first given
 * formula by the second given formula in visited formulae.
 *
 * @param pToReplace the formula to be replaced.
 * @param pReplacement the replacement formula.
 *//*from   w  ww . ja v a 2 s  . c o m*/
public ReplaceVisitor(BooleanFormula<T> pToReplace, BooleanFormula<T> pReplacement) {
    this(Predicates.<NumeralFormula<T>>alwaysFalse(), Functions.<NumeralFormula<T>>identity(),
            pToReplace == null ? Predicates.<BooleanFormula<T>>alwaysFalse()
                    : Predicates.<BooleanFormula<T>>equalTo(pToReplace),
            Functions.constant(pReplacement));
}

From source file:com.palantir.atlasdb.cli.command.SweepCommand.java

@Override
public int execute(final AtlasDbServices services) {
    SweepTaskRunner sweepRunner = services.getSweepTaskRunner();

    if (!((namespace != null) ^ (table != null) ^ sweepAllTables)) {
        System.err.println("Specify one of --namespace, --table, or --all options.");
        return 1;
    }//from   w  w  w  .  j a  va2s  . co  m
    if ((namespace != null) && (row != null)) {
        System.err.println("Cannot specify a start row (" + row
                + ") when sweeping multiple tables (in namespace " + namespace + ")");
        return 1;
    }

    Map<TableReference, Optional<byte[]>> tableToStartRow = Maps.newHashMap();

    if ((table != null)) {
        Optional<byte[]> startRow = Optional.of(new byte[0]);
        if (row != null) {
            startRow = Optional.of(decodeStartRow(row));
        }
        tableToStartRow.put(TableReference.createUnsafe(table), startRow);
    } else if (namespace != null) {
        Set<TableReference> tablesInNamespace = services.getKeyValueService().getAllTableNames().stream()
                .filter(tableRef -> tableRef.getNamespace().getName().equals(namespace))
                .collect(Collectors.toSet());
        for (TableReference table : tablesInNamespace) {
            tableToStartRow.put(table, Optional.of(new byte[0]));
        }
    } else if (sweepAllTables) {
        tableToStartRow.putAll(Maps.asMap(Sets.difference(services.getKeyValueService().getAllTableNames(),
                AtlasDbConstants.hiddenTables), Functions.constant(Optional.of(new byte[0]))));
    }

    for (Map.Entry<TableReference, Optional<byte[]>> entry : tableToStartRow.entrySet()) {
        final TableReference table = entry.getKey();
        Optional<byte[]> startRow = entry.getValue();

        final AtomicLong cellsExamined = new AtomicLong();
        final AtomicLong cellsDeleted = new AtomicLong();

        while (startRow.isPresent()) {
            Stopwatch watch = Stopwatch.createStarted();
            SweepResults results = sweepRunner.run(table, batchSize, startRow.get());
            System.out.println(String.format(
                    "Swept from %s to %s in table %s in %d ms, examined %d unique cells, deleted %d cells.",
                    encodeStartRow(startRow), encodeEndRow(results.getNextStartRow()), table,
                    watch.elapsed(TimeUnit.MILLISECONDS), results.getCellsExamined(),
                    results.getCellsDeleted()));
            startRow = results.getNextStartRow();
            cellsDeleted.addAndGet(results.getCellsDeleted());
            cellsExamined.addAndGet(results.getCellsExamined());
            maybeSleep();
        }

        services.getTransactionManager().runTaskWithRetry((TxTask) t -> {
            SweepPriorityTable priorityTable = SweepTableFactory.of().getSweepPriorityTable(t);
            SweepPriorityTable.SweepPriorityRow row1 = SweepPriorityTable.SweepPriorityRow
                    .of(table.getQualifiedName());
            priorityTable.putWriteCount(row1, 0L);
            priorityTable.putCellsDeleted(row1, cellsDeleted.get());
            priorityTable.putCellsExamined(row1, cellsExamined.get());
            priorityTable.putLastSweepTime(row1, System.currentTimeMillis());

            System.out
                    .println(String.format("Finished sweeping %s, examined %d unique cells, deleted %d cells.",
                            table, cellsExamined.get(), cellsDeleted.get()));

            if (cellsDeleted.get() > 0) {
                Stopwatch watch = Stopwatch.createStarted();
                services.getKeyValueService().compactInternally(table);
                System.out.println(String.format("Finished performing compactInternally on %s in %d ms.", table,
                        watch.elapsed(TimeUnit.MILLISECONDS)));
            }
            return null;
        });
    }
    return 0;
}

From source file:clocker.mesos.entity.MesosSlaveImpl.java

@Override
public void connectSensors() {
    super.connectSensors();

    final String id = sensors().get(MESOS_SLAVE_ID);

    HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(30, TimeUnit.SECONDS)
            .baseUri(getMesosCluster().sensors().get(Attributes.MAIN_URI))
            .credentialsIfNotNull(config().get(MesosCluster.MESOS_USERNAME),
                    config().get(MesosCluster.MESOS_PASSWORD))
            .poll(HttpPollConfig.forSensor(MEMORY_AVAILABLE).suburl("/master/state.json")
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                            Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() {
                                @Override
                                public boolean apply(JsonElement input) {
                                    return input.getAsJsonObject().get("id").getAsString().equals(id);
                                }//from   w w  w. j  a  v  a  2 s.c om
                            }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("resources", "mem"),
                            JsonFunctions.castM(Long.class)))
                    .onFailureOrException(Functions.constant(-1L)))
            .poll(HttpPollConfig.forSensor(CPU_AVAILABLE).suburl("/master/state.json")
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                            Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() {
                                @Override
                                public boolean apply(JsonElement input) {
                                    return input.getAsJsonObject().get("id").getAsString().equals(id);
                                }
                            }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("resources", "cpus"),
                            JsonFunctions.castM(Double.class)))
                    .onFailureOrException(Functions.constant(-1d)))
            .poll(HttpPollConfig.forSensor(DISK_AVAILABLE).suburl("/master/state.json")
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                            Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() {
                                @Override
                                public boolean apply(JsonElement input) {
                                    return input.getAsJsonObject().get("id").getAsString().equals(id);
                                }
                            }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("resources", "disk"),
                            JsonFunctions.castM(Long.class)))
                    .onFailureOrException(Functions.constant(-1L)))
            .poll(HttpPollConfig.forSensor(MEMORY_USED).suburl("/master/state.json")
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                            Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() {
                                @Override
                                public boolean apply(JsonElement input) {
                                    return input.getAsJsonObject().get("id").getAsString().equals(id);
                                }
                            }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("used_resources", "mem"),
                            JsonFunctions.castM(Long.class)))
                    .onFailureOrException(Functions.constant(-1L)))
            .poll(HttpPollConfig.forSensor(CPU_USED).suburl("/master/state.json")
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                            Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() {
                                @Override
                                public boolean apply(JsonElement input) {
                                    return input.getAsJsonObject().get("id").getAsString().equals(id);
                                }
                            }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("used_resources", "cpus"),
                            JsonFunctions.castM(Double.class)))
                    .onFailureOrException(Functions.constant(-1d)))
            .poll(HttpPollConfig.forSensor(DISK_USED).suburl("/master/state.json")
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                            Functions.compose(MesosUtils.selectM(new Predicate<JsonElement>() {
                                @Override
                                public boolean apply(JsonElement input) {
                                    return input.getAsJsonObject().get("id").getAsString().equals(id);
                                }
                            }), JsonFunctions.walk("slaves")), JsonFunctions.walkM("used_resources", "disk"),
                            JsonFunctions.castM(Long.class)))
                    .onFailureOrException(Functions.constant(-1L)));
    httpFeed = httpFeedBuilder.build();
}

From source file:org.apache.brooklyn.core.sensor.ssh.SshCommandSensor.java

@Override
public void apply(final EntityLocal entity) {
    super.apply(entity);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding SSH sensor {} to {}", name, entity);
    }/*from   w  ww. j a v a  2 s  .  c  o  m*/

    Supplier<Map<String, String>> envSupplier = new Supplier<Map<String, String>>() {
        @Override
        public Map<String, String> get() {
            return MutableMap
                    .copyOf(Strings.toStringMap(entity.getConfig(BrooklynConfigKeys.SHELL_ENVIRONMENT), ""));
        }
    };

    Supplier<String> commandSupplier = new Supplier<String>() {
        @Override
        public String get() {
            return makeCommandExecutingInDirectory(command, executionDir, entity);
        }
    };

    SshPollConfig<T> pollConfig = new SshPollConfig<T>(sensor).period(period).env(envSupplier)
            .command(commandSupplier).checkSuccess(SshValueFunctions.exitStatusEquals(0))
            .onFailureOrException(Functions.constant((T) null))
            .onSuccess(Functions.compose(new Function<String, T>() {
                @Override
                public T apply(String input) {
                    return TypeCoercions.coerce(input, getType(type));
                }
            }, SshValueFunctions.stdout()));

    SshFeed.builder().entity(entity).onlyIfServiceUp().poll(pollConfig).build();
}

From source file:com.eucalyptus.compute.common.internal.tags.Tag.java

@SuppressWarnings("unchecked")
public static Tag withOwner(@Nonnull final OwnerFullName ownerFullName) {
    Preconditions.checkNotNull(ownerFullName, "ownerFullName");
    return new Tag(null, Functions.constant(null), ownerFullName, null, null);
}

From source file:brooklyn.entity.cloudfoundry.webapp.CloudFoundryWebAppImpl.java

/**
 * For connecting the {@link #DISK} sensor.
 * <p>//from   ww w.  j  av  a  2  s  .  c  om
 * Should be called inside {@link #connectSensors()}.
 *
 * @see #disconnectDiskQuotaSensor()
 */
protected void connectDiskQuotaSensor() {
    usedDisk = FunctionFeed.builder().entity(this).period(Duration.seconds(2))
            .poll(new FunctionPollConfig<Integer, Integer>(DISK).onException(Functions.constant(0))
                    .callable(new Callable<Integer>() {
                        public Integer call() {
                            return getDriver().getDisk();
                        }
                    }))
            .build();
}

From source file:com.facebook.buck.distributed.DistBuildFileHashes.java

public DistBuildFileHashes(ActionGraph actionGraph, final SourcePathResolver sourcePathResolver,
        SourcePathRuleFinder ruleFinder, final FileHashCache rootCellFileHashCache,
        final Function<? super Path, Integer> cellIndexer, ListeningExecutorService executorService,
        final int keySeed, final BuckConfig buckConfig) {

    this.remoteFileHashes = CacheBuilder.newBuilder()
            .build(new CacheLoader<ProjectFilesystem, BuildJobStateFileHashes>() {
                @Override/*from w w w. j  av a2s.c o  m*/
                public BuildJobStateFileHashes load(ProjectFilesystem filesystem) throws Exception {
                    BuildJobStateFileHashes fileHashes = new BuildJobStateFileHashes();
                    fileHashes.setCellIndex(cellIndexer.apply(filesystem.getRootPath()));
                    return fileHashes;
                }
            });
    this.fileHashLoaders = CacheBuilder.newBuilder()
            .build(new CacheLoader<ProjectFilesystem, FileHashLoader>() {
                @Override
                public FileHashLoader load(ProjectFilesystem key) throws Exception {
                    return new RecordingFileHashLoader(
                            new StackedFileHashCache(ImmutableList.of(rootCellFileHashCache,
                                    DefaultFileHashCache.createDefaultFileHashCache(key))),
                            key, remoteFileHashes.get(key), new DistBuildConfig(buckConfig));
                }
            });
    this.ruleKeyFactories = createRuleKeyFactories(sourcePathResolver, ruleFinder, fileHashLoaders, keySeed);
    this.ruleKeys = ruleKeyComputation(actionGraph, this.ruleKeyFactories, executorService);
    this.fileHashes = fileHashesComputation(Futures.transform(this.ruleKeys, Functions.constant(null)),
            this.remoteFileHashes, executorService);
}

From source file:edu.uci.ics.jung.algorithms.shortestpath.DijkstraDistance.java

/**
 * <p>Creates an instance of <code>DijkstraShortestPath</code> for 
 * the specified unweighted graph (that is, all weights 1) which
 * caches results locally./*from   w ww . j  a  v  a2 s.  c o  m*/
 * 
 * @param g     the graph on which distances will be calculated
 */
public DijkstraDistance(Graph<V, E> g) {
    this(g, Functions.constant(1), true);
}

From source file:org.openrdf.sail.solr.SolrIndex.java

protected Function<? super String, ? extends SpatialContext> createSpatialContextMapper(
        Map<String, String> parameters) {
    // this should really be based on the schema
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    SpatialContext geoContext = SpatialContextFactory.makeSpatialContext(parameters, classLoader);
    return Functions.constant(geoContext);
}

From source file:edu.uci.ics.jung.samples.AnimatingAddNodeDemo.java

@Override
public void init() {

    //create a graph
    Graph<Number, Number> ig = Graphs
            .<Number, Number>synchronizedDirectedGraph(new DirectedSparseMultigraph<Number, Number>());

    ObservableGraph<Number, Number> og = new ObservableGraph<Number, Number>(ig);
    og.addGraphEventListener(new GraphEventListener<Number, Number>() {

        public void handleGraphEvent(GraphEvent<Number, Number> evt) {
            System.err.println("got " + evt);

        }/*from www .j  ava 2  s .  c o m*/
    });
    this.g = og;
    //create a graphdraw
    layout = new FRLayout<Number, Number>(g);
    layout.setSize(new Dimension(600, 600));
    Relaxer relaxer = new VisRunner((IterativeContext) layout);
    relaxer.stop();
    relaxer.prerelax();

    Layout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout);

    vv = new VisualizationViewer<Number, Number>(staticLayout, new Dimension(600, 600));

    JRootPane rp = this.getRootPane();
    rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);

    getContentPane().setLayout(new BorderLayout());
    getContentPane().setBackground(java.awt.Color.lightGray);
    getContentPane().setFont(new Font("Serif", Font.PLAIN, 12));

    vv.setGraphMouse(new DefaultModalGraphMouse<Number, Number>());

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
    vv.setForeground(Color.white);

    vv.addComponentListener(new ComponentAdapter() {

        /**
         * @see java.awt.event.ComponentAdapter#componentResized(java.awt.event.ComponentEvent)
         */
        @Override
        public void componentResized(ComponentEvent arg0) {
            super.componentResized(arg0);
            System.err.println("resized");
            layout.setSize(arg0.getComponent().getSize());
        }
    });

    getContentPane().add(vv);
    switchLayout = new JButton("Switch to SpringLayout");
    switchLayout.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            Dimension d = vv.getSize();//new Dimension(600,600);
            if (switchLayout.getText().indexOf("Spring") > 0) {
                switchLayout.setText("Switch to FRLayout");
                layout = new SpringLayout<Number, Number>(g, Functions.constant(EDGE_LENGTH));
                layout.setSize(d);
                Relaxer relaxer = new VisRunner((IterativeContext) layout);
                relaxer.stop();
                relaxer.prerelax();
                StaticLayout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout);
                LayoutTransition<Number, Number> lt = new LayoutTransition<Number, Number>(vv,
                        vv.getGraphLayout(), staticLayout);
                Animator animator = new Animator(lt);
                animator.start();
                vv.repaint();

            } else {
                switchLayout.setText("Switch to SpringLayout");
                layout = new FRLayout<Number, Number>(g, d);
                layout.setSize(d);
                Relaxer relaxer = new VisRunner((IterativeContext) layout);
                relaxer.stop();
                relaxer.prerelax();
                StaticLayout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout);
                LayoutTransition<Number, Number> lt = new LayoutTransition<Number, Number>(vv,
                        vv.getGraphLayout(), staticLayout);
                Animator animator = new Animator(lt);
                animator.start();
                vv.repaint();

            }
        }
    });

    getContentPane().add(switchLayout, BorderLayout.SOUTH);

    timer = new Timer();
}