List of usage examples for com.google.common.base Functions constant
public static <E> Function<Object, E> constant(@Nullable E value)
From source file:io.prestosql.sql.planner.iterative.rule.test.PlanBuilder.java
public TopNNode topN(long count, List<Symbol> orderBy, PlanNode source) { return new TopNNode(idAllocator.getNextId(), source, count, new OrderingScheme(orderBy, Maps.toMap(orderBy, Functions.constant(SortOrder.ASC_NULLS_FIRST))), TopNNode.Step.SINGLE);/*from www . j a v a2 s .c o m*/ }
From source file:brooklyn.entity.waratek.cloudvm.JavaVirtualMachineImpl.java
@Override protected void connectSensors() { super.connectSensors(); jmxMxBeanFeed = JavaAppUtils.getMxBeanSensorsBuilder(this) .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP) .objectName(WaratekUtils.VIRTUAL_MACHINE_MX_BEAN).attributeName("Vendor") .onException(Functions.constant(Boolean.FALSE)).onSuccess(Functions.constant(Boolean.TRUE))) .build();/* www .j av a 2 s . com*/ jvcFeed = FunctionFeed.builder().entity(this).period(Duration.TEN_SECONDS) .poll(new FunctionPollConfig<Integer, Integer>(STOPPED_JVCS).callable(new Callable<Integer>() { @Override public Integer call() throws Exception { return Iterables.size(getAvailableJvcs()); } }).onFailureOrException(Functions.constant(0))) .poll(new FunctionPollConfig<Integer, Integer>(RUNNING_JVCS).callable(new Callable<Integer>() { @Override public Integer call() throws Exception { return getRunningJvcs(); } }).onFailureOrException(Functions.constant(0))) .poll(new FunctionPollConfig<Integer, Integer>(PAUSED_JVCS).callable(new Callable<Integer>() { @Override public Integer call() throws Exception { return getPausedJvcs(); } }).onFailureOrException(Functions.constant(0))).build(); }
From source file:org.apache.aurora.scheduler.state.SchedulerCoreImpl.java
@Override public void addInstances(final IJobKey jobKey, final ImmutableSet<Integer> instanceIds, final ITaskConfig config) throws ScheduleException { storage.write(new MutateWork.NoResult<ScheduleException>() { @Override//ww w . ja v a 2 s .co m protected void execute(MutableStoreProvider storeProvider) throws ScheduleException { validateTaskLimits(config, instanceIds.size()); ImmutableSet<IScheduledTask> tasks = storeProvider.getTaskStore() .fetchTasks(Query.jobScoped(jobKey).active()); Set<Integer> existingInstanceIds = FluentIterable.from(tasks) .transform(Tasks.SCHEDULED_TO_INSTANCE_ID).toSet(); if (!Sets.intersection(existingInstanceIds, instanceIds).isEmpty()) { throw new ScheduleException("Instance ID collision detected."); } stateManager.insertPendingTasks(Maps.asMap(instanceIds, Functions.constant(config))); } }); }
From source file:org.apache.brooklyn.entity.chef.KnifeConvergeTaskFactory.java
public KnifeConvergeTaskFactory<RET> knifeRunList(String runList) { this.runList = Functions.constant(runList); return self(); }
From source file:com.facebook.buck.artifact_cache.TwoLevelArtifactCacheDecorator.java
private ListenableFuture<Boolean> attemptTwoLevelStore(final ArtifactInfo info, final BorrowablePath output) { return Futures.transformAsync(Futures.immediateFuture(null), (AsyncFunction<Void, Boolean>) input -> { long fileSize = projectFilesystem.getFileSize(output.getPath()); if (!performTwoLevelStores || fileSize < minimumTwoLevelStoredArtifactSize || (maximumTwoLevelStoredArtifactSize.isPresent() && fileSize > maximumTwoLevelStoredArtifactSize.get())) { return Futures.immediateFuture(false); }//from www . j ava 2 s.com long hashComputationStart = System.currentTimeMillis(); String hashCode = projectFilesystem.computeSha1(output.getPath()) + "2c00"; long hashComputationEnd = System.currentTimeMillis(); secondLevelHashComputationTimeMs.addSample(hashComputationEnd - hashComputationStart); ImmutableMap<String, String> metadataWithCacheKey = ImmutableMap.<String, String>builder() .putAll(info.getMetadata()).put(METADATA_KEY, hashCode).build(); return Futures .transform(Futures.allAsList( delegate.store( ArtifactInfo.builder().setRuleKeys(info.getRuleKeys()) .setMetadata(metadataWithCacheKey).build(), BorrowablePath.notBorrowablePath(emptyFilePath)), delegate.store(ArtifactInfo.builder().addRuleKeys(new RuleKey(hashCode)).build(), output)), Functions.constant(true)); }); }
From source file:com.twitter.aurora.scheduler.state.SchedulerCoreImpl.java
@Override public void addInstances(final IJobKey jobKey, final ImmutableSet<Integer> instanceIds, final ITaskConfig config) throws ScheduleException { runJobFilters(jobKey, config, instanceIds.size(), true); storage.write(new MutateWork.NoResult<ScheduleException>() { @Override/*w w w .j a v a 2 s .c om*/ protected void execute(MutableStoreProvider storeProvider) throws ScheduleException { ImmutableSet<IScheduledTask> tasks = storeProvider.getTaskStore() .fetchTasks(Query.jobScoped(jobKey).active()); Set<Integer> existingInstanceIds = FluentIterable.from(tasks) .transform(Tasks.SCHEDULED_TO_INSTANCE_ID).toSet(); if (!Sets.intersection(existingInstanceIds, instanceIds).isEmpty()) { throw new ScheduleException("Instance ID collision detected."); } stateManager.insertPendingTasks(Maps.asMap(instanceIds, Functions.constant(config))); } }); }
From source file:net.automatalib.util.automata.fsa.DFAs.java
/** * Calculates the complement (negation) of a DFA, and stores the result in a given mutable DFA. * <p>//from w ww . j ava 2 s .c om * Note that unlike {@link MutableDFA#flipAcceptance()}, undefined transitions are treated as * leading to a rejecting sink state (and are thus turned into an accepting sink). * * @param dfa the DFA to complement * @param inputs the input symbols to consider * @param out a mutable DFA for storing the result * @return {@code out}, for convenience */ public static <I, S, A extends MutableDFA<S, I>> A complement(DFA<?, I> dfa, Collection<? extends I> inputs, A out) { AutomatonLowLevelCopy.copy(AutomatonCopyMethod.DFS, dfa, inputs, out, NEGATE, Functions.constant((Void) null)); MutableDFAs.complete(out, inputs, false, true); return out; }
From source file:edu.umn.msi.tropix.proteomics.scaffold.impl.ScaffoldJobProcessorImpl.java
@Override protected void doPreprocessing() { getStagingDirectory().makeDirectory(INPUT_PATH); getStagingDirectory().makeDirectory(OUTPUT_PATH); getStagingDirectory().makeDirectory(DB_PATH); final String inputAbsPath = Directories.buildAbsolutePath(getStagingDirectory(), INPUT_PATH); final String dbAbsPath = Directories.buildAbsolutePath(getStagingDirectory(), DB_PATH); addFullPathToScaffoldInputFiles(inputAbsPath, dbAbsPath, scaffoldInput); addFullPathToScaffoldOutputFiles(Directories.buildAbsolutePath(getStagingDirectory(), OUTPUT_PATH), scaffoldInput);//from www. ja v a 2 s . c om // InputContexts.putIntoOutputContexts(downloadContexts, getInputContexts(scaffoldInput)); // Iterator<OutputContext> iIter = getInputContexts(scaffoldInput).iterator(); final Iterator<InputContext> oIter = downloadContexts.iterator(); for (final String inputPath : getInputPaths(scaffoldInput)) { final InputContext inputContext = oIter.next(); final OutputContext outputContext = getStagingDirectory().getOutputContext(inputPath); if (inputPath.endsWith(".omx")) { FileInputStream tempFileInputStream = null; final File tempFile = TEMP_FILE_SUPPLIER.get(); try { inputContext.get(tempFile); tempFileInputStream = FILE_UTILS.getFileInputStream(tempFile); if (IO_UTILS.isZippedStream(tempFileInputStream)) { ZIP_UTILS.unzipToContexts(tempFile, Functions.constant(outputContext)); } else { InputContexts.forFile(tempFile).get(outputContext); } } finally { FILE_UTILS.deleteQuietly(tempFile); IO_UTILS.closeQuietly(tempFileInputStream); } } else { inputContext.get(outputContext); } } SCAFFOLD_WRITER.serialize(scaffoldInput, getStagingDirectory().getOutputContext(XML_DRIVER_PATH)); final List<String> arguments = new LinkedList<String>(); arguments.add("-f"); if (quiteMode) { arguments.add("-q"); } if (keyPath != null) { arguments.add("-keypath"); arguments.add(keyPath); } arguments.add(Directories.buildAbsolutePath(getStagingDirectory(), XML_DRIVER_PATH)); this.getJobDescription().getJobDescriptionType().setArgument(arguments.toArray(new String[] {})); initializeOutputTracker(); }
From source file:com.netflix.metacat.main.services.search.ElasticSearchMetacatRefresh.java
@SuppressWarnings("checkstyle:methodname") private ListenableFuture<Void> _processPartitions(final List<QualifiedName> qNames) { final List<QualifiedName> excludeQualifiedNames = config.getElasticSearchRefreshExcludeQualifiedNames(); final List<String> tables = elasticSearchUtil.getTableIdsByCatalogs(ElasticSearchDoc.Type.table.name(), qNames, excludeQualifiedNames); final List<ListenableFuture<ListenableFuture<Void>>> futures = tables.stream() .map(s -> service.submit(() -> { final QualifiedName tableName = QualifiedName.fromString(s, false); final List<ListenableFuture<Void>> indexFutures = Lists.newArrayList(); int offset = 0; int count; Sort sort;/*from w w w .ja va2s .c om*/ if ("s3".equals(tableName.getCatalogName()) || "aegisthus".equals(tableName.getCatalogName())) { sort = new Sort("id", SortOrder.ASC); } else { sort = new Sort("part_id", SortOrder.ASC); } final Pageable pageable = new Pageable(10000, offset); do { final List<PartitionDto> partitionDtos = partitionService.list(tableName, null, null, sort, pageable, true, true, true); count = partitionDtos.size(); if (!partitionDtos.isEmpty()) { final List<List<PartitionDto>> partitionedPartitionDtos = Lists.partition(partitionDtos, 1000); partitionedPartitionDtos.forEach(subPartitionsDtos -> indexFutures .add(indexPartitionDtos(tableName, subPartitionsDtos))); offset = offset + count; pageable.setOffset(offset); } } while (count == 10000); return Futures.transform(Futures.successfulAsList(indexFutures), Functions.constant((Void) null)); })).collect(Collectors.toList()); final ListenableFuture<Void> processPartitionsFuture = Futures .transformAsync(Futures.successfulAsList(futures), input -> { final List<ListenableFuture<Void>> inputFuturesWithoutNulls = input.stream().filter(NOT_NULL) .collect(Collectors.toList()); return Futures.transform(Futures.successfulAsList(inputFuturesWithoutNulls), Functions.constant(null)); }); return Futures.transformAsync(processPartitionsFuture, input -> { elasticSearchUtil.refresh(); final List<ListenableFuture<Void>> cleanUpFutures = tables.stream() .map(s -> service.submit( () -> partitionsCleanUp(QualifiedName.fromString(s, false), excludeQualifiedNames))) .collect(Collectors.toList()); return Futures.transform(Futures.successfulAsList(cleanUpFutures), Functions.constant(null)); }); }
From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java
@Override public void connectSensors() { // TODO If we are not "mesos.task.managed", then we are just guessing at the appId. We may get // it wrong. If it's wrong then our uri will always give 404. We should not mark the task as // "serviceUp=false", and we should not clear the TASK_ID (which was correctly set in // MesosFramework.scanTasks, which is where this task came from in the first place). // The new behaviour of showing it as healthy (and not clearing the taskId, which caused // another instance to be automatically added!) is better than it was, but it definitely // needs more attention. final boolean managed = Boolean.TRUE.equals(sensors().get(MANAGED)); String uri = Urls.mergePaths(getFramework().sensors().get(MarathonFramework.FRAMEWORK_URL), "/v2/apps", sensors().get(APPLICATION_ID), "tasks"); HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(2000, TimeUnit.MILLISECONDS) .baseUri(uri)/* w w w. j a v a2 s . c om*/ .credentialsIfNotNull( config().get(MesosCluster.MESOS_USERNAME), config().get(MesosCluster.MESOS_PASSWORD)) .header("Accept", "application/json") .poll(new HttpPollConfig<Boolean>(SERVICE_UP).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, Boolean>() { @Override public Boolean apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); return tasks.size() == 1; } })) .onFailureOrException(Functions.constant(managed ? Boolean.FALSE : true))) .poll(new HttpPollConfig<Long>(TASK_STARTED_AT).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, Long>() { @Override public Long apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement startedAt = each.getAsJsonObject().get("startedAt"); if (startedAt != null && !startedAt.isJsonNull()) { return Time.parseDate(startedAt.getAsString()).getTime(); } } return null; } })) .onFailureOrException(Functions.<Long>constant(-1L))) .poll(new HttpPollConfig<Long>(TASK_STAGED_AT).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, Long>() { @Override public Long apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement stagedAt = each.getAsJsonObject().get("stagedAt"); if (stagedAt != null && !stagedAt.isJsonNull()) { return Time.parseDate(stagedAt.getAsString()).getTime(); } } return null; } })) .onFailureOrException(Functions.<Long>constant(-1L))) .poll(new HttpPollConfig<String>(Attributes.HOSTNAME).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, String>() { @Override public String apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement host = each.getAsJsonObject().get("host"); if (host != null && !host.isJsonNull()) { return host.getAsString(); } } return null; } })) .onFailureOrException(Functions.<String>constant(null))) .poll(new HttpPollConfig<String>(TASK_ID).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, String>() { @Override public String apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement id = each.getAsJsonObject().get("id"); if (id != null && !id.isJsonNull()) { return id.getAsString(); } } return null; } })) .onFailureOrException( (Function) Functions.<Object>constant(managed ? null : FeedConfig.UNCHANGED))) .poll(new HttpPollConfig<String>(Attributes.ADDRESS).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, String>() { @Override public String apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement host = each.getAsJsonObject().get("host"); if (host != null && !host.isJsonNull()) { try { return InetAddress.getByName(host.getAsString()) .getHostAddress(); } catch (UnknownHostException uhe) { Exceptions.propagate(uhe); } } } return null; } })) .onFailureOrException(Functions.<String>constant(null))); httpFeed = httpFeedBuilder.build(); }