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:com.netflix.metacat.main.services.search.ElasticSearchMetacatRefresh.java

/**
 * Process the list of databases./*from   w  w w  .j av a  2  s .  com*/
 *
 * @param catalogName   catalog name
 * @param databaseNames database names
 * @return future
 */
@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processDatabases(final QualifiedName catalogName,
        final List<QualifiedName> databaseNames) {
    ListenableFuture<Void> resultFuture = null;
    log.info("Full refresh of catalog {} for databases({}): {}", catalogName, databaseNames.size(),
            databaseNames);
    final List<ListenableFuture<DatabaseDto>> getDatabaseFutures = databaseNames.stream()
            .map(databaseName -> service.submit(() -> {
                DatabaseDto result = null;
                try {
                    result = getDatabase(databaseName);
                } catch (Exception e) {
                    log.error("Failed to retrieve database: {}", databaseName);
                    elasticSearchUtil.log("ElasticSearchMetacatRefresh.getDatabase",
                            ElasticSearchDoc.Type.database.name(), databaseName.toString(), null,
                            e.getMessage(), e, true);
                }
                return result;
            })).collect(Collectors.toList());

    if (getDatabaseFutures != null && !getDatabaseFutures.isEmpty()) {
        resultFuture = Futures.transformAsync(Futures.successfulAsList(getDatabaseFutures), input -> {
            final ListenableFuture<Void> processDatabaseFuture = indexDatabaseDtos(catalogName, input);
            final List<ListenableFuture<Void>> processDatabaseFutures = input.stream().filter(NOT_NULL)
                    .map(databaseDto -> {
                        final List<QualifiedName> tableNames = databaseDto.getTables().stream()
                                .map(s -> QualifiedName.ofTable(databaseDto.getName().getCatalogName(),
                                        databaseDto.getName().getDatabaseName(), s))
                                .collect(Collectors.toList());
                        log.info("Full refresh of database {} for tables({}): {}",
                                databaseDto.getName().toString(), databaseDto.getTables().size(),
                                databaseDto.getTables());
                        return processTables(databaseDto.getName(), tableNames);
                    }).filter(NOT_NULL).collect(Collectors.toList());
            processDatabaseFutures.add(processDatabaseFuture);
            return Futures.transform(Futures.successfulAsList(processDatabaseFutures),
                    Functions.constant(null));
        });
    }

    return resultFuture;
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchMetacatRefresh.java

/**
 * Process the list of tables in batches.
 *
 * @param databaseName database name//from   w  ww.  j  a  va2  s  . co  m
 * @param tableNames   table names
 * @return A future containing the tasks
 */
private ListenableFuture<Void> processTables(final QualifiedName databaseName,
        final List<QualifiedName> tableNames) {
    final List<List<QualifiedName>> tableNamesBatches = Lists.partition(tableNames, 500);
    final List<ListenableFuture<Void>> processTablesBatchFutures = tableNamesBatches.stream()
            .map(subTableNames -> _processTables(databaseName, subTableNames)).collect(Collectors.toList());

    return Futures.transform(Futures.successfulAsList(processTablesBatchFutures), Functions.constant(null));
}

From source file:com.netflix.metacat.main.services.search.ElasticSearchRefresh.java

/**
 * Process the list of databases.//from   ww  w  .j  ava 2 s . com
 *
 * @param catalogName   catalog name
 * @param databaseNames database names
 * @return future
 */
@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processDatabases(final QualifiedName catalogName,
        final List<QualifiedName> databaseNames) {
    ListenableFuture<Void> resultFuture = null;
    log.info("Full refresh of catalog {} for databases({}): {}", catalogName, databaseNames.size(),
            databaseNames);
    final List<ListenableFuture<DatabaseDto>> getDatabaseFutures = databaseNames.stream()
            .map(databaseName -> service.submit(() -> {
                DatabaseDto result = null;
                try {
                    result = getDatabase(databaseName);
                } catch (Exception e) {
                    log.error("Failed to retrieve database: {}", databaseName);
                    elasticSearchUtil.log("ElasticSearchRefresh.getDatabase",
                            ElasticSearchDoc.Type.database.name(), databaseName.toString(), null,
                            e.getMessage(), e, true);
                }
                return result;
            })).collect(Collectors.toList());

    if (getDatabaseFutures != null && !getDatabaseFutures.isEmpty()) {
        resultFuture = Futures.transformAsync(Futures.successfulAsList(getDatabaseFutures), input -> {
            final ListenableFuture<Void> processDatabaseFuture = indexDatabaseDtos(catalogName, input);
            final List<ListenableFuture<Void>> processDatabaseFutures = input.stream().filter(NOT_NULL)
                    .map(databaseDto -> {
                        final List<QualifiedName> tableNames = databaseDto.getTables().stream()
                                .map(s -> QualifiedName.ofTable(databaseDto.getName().getCatalogName(),
                                        databaseDto.getName().getDatabaseName(), s))
                                .collect(Collectors.toList());
                        log.info("Full refresh of database {} for tables({}): {}", databaseDto.getName(),
                                databaseDto.getTables().size(), databaseDto.getTables());
                        return processTables(databaseDto.getName(), tableNames);
                    }).filter(NOT_NULL).collect(Collectors.toList());
            processDatabaseFutures.add(processDatabaseFuture);
            return Futures.transform(Futures.successfulAsList(processDatabaseFutures),
                    Functions.constant(null));
        });
    }

    return resultFuture;
}

From source file:com.android.builder.core.AtlasBuilder.java

@Deprecated
public void oldPackageApk(@NonNull String androidResPkgLocation, @NonNull Set<File> dexFolders,
        @NonNull Collection<File> javaResourcesLocations, @NonNull Collection<File> jniLibsLocations,
        @Nullable File assetsFolder, @NonNull Set<String> abiFilters, boolean jniDebugBuild,
        @Nullable SigningConfig signingConfig, @NonNull File outApkLocation, int minSdkVersion,
        @NonNull Predicate<String> noCompressPredicate)
        throws KeytoolException, PackagerException, SigningException, IOException {
    checkNotNull(androidResPkgLocation, "androidResPkgLocation cannot be null.");
    checkNotNull(outApkLocation, "outApkLocation cannot be null.");

    /*//w w w  . j  a v  a 2  s  .  c  o  m
     * This is because this method is not supposed be be called in an incremental build. So, if
     * an out APK already exists, we delete it.
     */
    if (outApkLocation.exists()) {
        FileUtils.forceDelete(outApkLocation);
    }

    Map<RelativeFile, FileStatus> javaResourceMods = Maps.newHashMap();
    Map<File, FileStatus> javaResourceArchiveMods = Maps.newHashMap();
    for (File resourceLocation : javaResourcesLocations) {
        if (resourceLocation.isFile()) {
            javaResourceArchiveMods.put(resourceLocation, FileStatus.NEW);
        } else {
            Set<RelativeFile> files = RelativeFiles.fromDirectory(resourceLocation,
                    new java.util.function.Predicate<RelativeFile>() {
                        @Override
                        public boolean test(RelativeFile relativeFile) {
                            return relativeFile.getFile().isFile();
                        }
                    });
            javaResourceMods.putAll(Maps.asMap(files, Functions.constant(FileStatus.NEW)));
        }
    }

    NativeLibraryAbiPredicate nativeLibraryPredicate = new NativeLibraryAbiPredicate(abiFilters, jniDebugBuild);
    Map<RelativeFile, FileStatus> jniMods = Maps.newHashMap();
    Map<File, FileStatus> jniArchiveMods = Maps.newHashMap();
    for (File jniLoc : jniLibsLocations) {
        if (jniLoc.isFile()) {
            jniArchiveMods.put(jniLoc, FileStatus.NEW);
        } else {
            Set<RelativeFile> files = RelativeFiles.fromDirectory(jniLoc,
                    RelativeFiles.fromPathPredicate(nativeLibraryPredicate));
            jniMods.putAll(Maps.asMap(files, Functions.constant(FileStatus.NEW)));
        }
    }

    Set<RelativeFile> assets = assetsFolder == null ? Collections.emptySet()
            : RelativeFiles.fromDirectory(assetsFolder, new java.util.function.Predicate<RelativeFile>() {
                @Override
                public boolean test(RelativeFile relativeFile) {
                    return relativeFile.getFile().isFile();
                }
            });

    PrivateKey key = null;
    X509Certificate certificate = null;
    boolean v1SigningEnabled = false;
    boolean v2SigningEnabled = false;

    ApkCreatorFactory.CreationData creationData = new ApkCreatorFactory.CreationData(outApkLocation, key,
            certificate, v1SigningEnabled, v2SigningEnabled, null, // BuiltBy
            "atlas", minSdkVersion, NativeLibrariesPackagingMode.COMPRESSED, noCompressPredicate::apply);
    try (OldPackager packager = new OldPackager(creationData, androidResPkgLocation,
            LoggerWrapper.getLogger(AtlasBuilder.class))) {
        // add dex folder to the apk root.
        if (!dexFolders.isEmpty()) {
            packager.addDexFiles(dexFolders);
        }

        // add the output of the java resource merger
        for (Map.Entry<RelativeFile, FileStatus> resourceUpdate : javaResourceMods.entrySet()) {
            packager.updateResource(resourceUpdate.getKey(), resourceUpdate.getValue());
        }

        for (Map.Entry<File, FileStatus> resourceArchiveUpdate : javaResourceArchiveMods.entrySet()) {
            packager.updateResourceArchive(resourceArchiveUpdate.getKey(), resourceArchiveUpdate.getValue(),
                    new java.util.function.Predicate<String>() {
                        @Override
                        public boolean test(String s) {
                            return false;
                        }
                    });
        }

        for (Map.Entry<RelativeFile, FileStatus> jniLibUpdates : jniMods.entrySet()) {
            packager.updateResource(jniLibUpdates.getKey(), jniLibUpdates.getValue());
        }

        for (Map.Entry<File, FileStatus> resourceArchiveUpdate : jniArchiveMods.entrySet()) {
            packager.updateResourceArchive(resourceArchiveUpdate.getKey(), resourceArchiveUpdate.getValue(),
                    new java.util.function.Predicate<String>() {
                        @Override
                        public boolean test(String s) {
                            return nativeLibraryPredicate.test(s);
                        }
                    });
        }

        for (RelativeFile asset : assets) {
            packager.addFile(asset.getFile(),
                    SdkConstants.FD_ASSETS + "/" + asset.getOsIndependentRelativePath());
        }
    }
}

From source file:clocker.docker.entity.DockerHostImpl.java

@Override
protected void connectServiceUpIsRunning() {
    serviceUpIsRunningFeed = FunctionFeed.builder().entity(this).period(Duration.THIRTY_SECONDS)
            .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_PROCESS_IS_RUNNING).suppressDuplicates(true)
                    .onException(Functions.constant(Boolean.FALSE)).callable(new Callable<Boolean>() {
                        public Boolean call() {
                            return getDriver().isRunning();
                        }/*from  w  ww  . ja  va  2 s . com*/
                    }))
            .build();
}

From source file:auto.json.processor.AutoJsonProcessor.java

private static String wildcardTypeParametersString(TypeElement type) {
    List<? extends TypeParameterElement> typeParameters = type.getTypeParameters();
    if (typeParameters.isEmpty()) {
        return "";
    } else {//  w ww .j a  v a  2s  . c  o m
        return "<"
                + Joiner.on(", ").join(FluentIterable.from(typeParameters).transform(Functions.constant("?")))
                + ">";
    }
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueService.java

@Override
public void dropTables(final Set<String> tablesToDrop) {
    String dropQuery = "DROP TABLE IF EXISTS %s"; // full table name (ks.cf)

    for (String tableName : tablesToDrop) {
        BoundStatement dropStatement = getPreparedStatement(tableName,
                String.format(dropQuery, getFullTableName(tableName)), longRunningQuerySession)
                        .setConsistencyLevel(ConsistencyLevel.ALL).bind();
        try {/*from   ww w  .  ja  v  a 2  s . co  m*/
            ResultSet resultSet = longRunningQuerySession.execute(dropStatement);
            CQLKeyValueServices.logTracedQuery(dropQuery, resultSet, session, cqlStatementCache.NORMAL_QUERY);
        } catch (com.datastax.driver.core.exceptions.UnavailableException e) {
            throw new InsufficientConsistencyException(
                    "Dropping tables requires all Cassandra nodes to be up and available.", e);
        }
    }

    CQLKeyValueServices.waitForSchemaVersionsToCoalesce("dropTables(" + tablesToDrop.size() + " tables)", this);

    put(CassandraConstants.METADATA_TABLE,
            Maps.toMap(Lists.transform(Lists.newArrayList(tablesToDrop), new Function<String, Cell>() {
                @Override
                public Cell apply(String tableName) {
                    return CQLKeyValueServices.getMetadataCell(tableName);
                }
            }), Functions.constant(PtBytes.EMPTY_BYTE_ARRAY)), System.currentTimeMillis());
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java

protected void throwIfWriteAlreadyCommitted(String tableName, Map<Cell, byte[]> writes,
        ConflictHandler conflictHandler, LockRefreshToken commitLocksToken,
        TransactionService transactionService) throws TransactionConflictException {
    if (writes.isEmpty() || conflictHandler == ConflictHandler.IGNORE_ALL) {
        return;//from  w  w w  . j a  va  2  s. co  m
    }
    Set<CellConflict> spanningWrites = Sets.newHashSet();
    Set<CellConflict> dominatingWrites = Sets.newHashSet();
    Map<Cell, Long> keysToLoad = Maps.asMap(writes.keySet(), Functions.constant(Long.MAX_VALUE));
    while (!keysToLoad.isEmpty()) {
        keysToLoad = detectWriteAlreadyCommittedInternal(tableName, keysToLoad, spanningWrites,
                dominatingWrites, transactionService);
    }

    if (conflictHandler == ConflictHandler.RETRY_ON_VALUE_CHANGED) {
        throwIfValueChangedConflict(tableName, writes, spanningWrites, dominatingWrites, commitLocksToken);
    } else if (conflictHandler == ConflictHandler.RETRY_ON_WRITE_WRITE
            || conflictHandler == ConflictHandler.RETRY_ON_WRITE_WRITE_CELL
            || conflictHandler == ConflictHandler.SERIALIZABLE) {
        if (!spanningWrites.isEmpty() || !dominatingWrites.isEmpty()) {
            throw TransactionConflictException.create(tableName, getStartTimestamp(), spanningWrites,
                    dominatingWrites, System.currentTimeMillis() - timeCreated);
        }
    } else {
        throw new IllegalArgumentException("Unknown conflictHandler type: " + conflictHandler);
    }
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraKeyValueService.java

private void internalPutMetadataForTables(final Map<String, byte[]> tableNameToMetadata,
        final boolean possiblyNeedToPerformSettingsChanges) {
    final Map<Cell, byte[]> metadataRequestedForUpdate = Maps
            .newHashMapWithExpectedSize(tableNameToMetadata.size());
    for (Entry<String, byte[]> tableEntry : tableNameToMetadata.entrySet()) {
        metadataRequestedForUpdate.put(getMetadataCell(tableEntry.getKey()), tableEntry.getValue());
    }//from   w w  w. java  2 s.  co  m

    Map<Cell, Long> requestForLatestDbSideMetadata = Maps.transformValues(metadataRequestedForUpdate,
            Functions.constant(Long.MAX_VALUE));

    // technically we're racing other services from here on, during an update period,
    // but the penalty for not caring is just some superfluous schema mutations and a few dead rows in the metadata table.
    Map<Cell, Value> persistedMetadata = get(CassandraConstants.METADATA_TABLE, requestForLatestDbSideMetadata);
    final Map<Cell, byte[]> newMetadata = Maps.newHashMap();
    final Collection<CfDef> updatedCfs = Lists.newArrayList();
    for (Entry<Cell, byte[]> entry : metadataRequestedForUpdate.entrySet()) {
        Value val = persistedMetadata.get(entry.getKey());
        if (val == null || !Arrays.equals(val.getContents(), entry.getValue())) {
            newMetadata.put(entry.getKey(), entry.getValue());
            updatedCfs.add(getCfForTable(new String(entry.getKey().getRowName()), entry.getValue()));
        }
    }

    if (!newMetadata.isEmpty()) {
        try {
            if (possiblyNeedToPerformSettingsChanges) {
                trySchemaMutationLock();
            }
            clientPool.runWithPooledResource(new FunctionCheckedException<Client, Void, Exception>() {
                @Override
                public Void apply(Client client) throws Exception {
                    if (possiblyNeedToPerformSettingsChanges) {
                        for (CfDef cf : updatedCfs) {
                            client.system_update_column_family(cf);
                        }

                        CassandraKeyValueServices.waitForSchemaVersions(client,
                                "(all tables in a call to putMetadataForTables)",
                                configManager.getConfig().schemaMutationTimeoutMillis());
                    }
                    // Done with actual schema mutation, push the metadata
                    put(CassandraConstants.METADATA_TABLE, newMetadata, System.currentTimeMillis());
                    return null;
                }
            });
        } catch (Exception e) {
            throw Throwables.throwUncheckedException(e);
        } finally {
            if (possiblyNeedToPerformSettingsChanges) {
                schemaMutationLock.unlock();
            }
        }
    }
}