Example usage for com.google.common.collect ImmutableMap values

List of usage examples for com.google.common.collect ImmutableMap values

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMap values.

Prototype

public ImmutableCollection<V> values() 

Source Link

Usage

From source file:com.facebook.buck.android.NonPreDexedDexBuildable.java

/** @return the resulting set of ProGuarded classpath entries to dex. */
@VisibleForTesting/*from w  ww.  j  av a 2s  .c o m*/
ImmutableSet<Path> addProguardCommands(Set<Path> classpathEntriesToDex, Set<Path> depsProguardConfigs,
        boolean skipProguard, ImmutableList.Builder<Step> steps, BuildableContext buildableContext,
        BuildContext buildContext) {
    // Create list of proguard Configs for the app project and its dependencies
    ImmutableSet.Builder<Path> proguardConfigsBuilder = ImmutableSet.builder();
    proguardConfigsBuilder.addAll(depsProguardConfigs);
    if (proguardConfig.isPresent()) {
        proguardConfigsBuilder.add(buildContext.getSourcePathResolver().getAbsolutePath(proguardConfig.get()));
    }
    for (SourcePath aaptGeneratedProguardConfigFile : proguardConfigs) {
        proguardConfigsBuilder
                .add(buildContext.getSourcePathResolver().getAbsolutePath(aaptGeneratedProguardConfigFile));
    }

    // Transform our input classpath to a set of output locations for each input classpath.
    // TODO(devjasta): the output path we choose is the result of a slicing function against
    // input classpath. This is fragile and should be replaced with knowledge of the BuildTarget.
    ImmutableMap<Path, Path> inputOutputEntries = classpathEntriesToDex.stream().collect(
            ImmutableMap.toImmutableMap(java.util.function.Function.identity(), (path) -> AndroidBinaryBuildable
                    .getProguardOutputFromInputClasspath(getProguardInputsDir(), path)));

    // Run ProGuard on the classpath entries.
    ProGuardObfuscateStep.create(androidPlatformTarget,
            javaRuntimeLauncher.getCommandPrefix(buildContext.getSourcePathResolver()), getProjectFilesystem(),
            proguardJarOverride.isPresent()
                    ? Optional
                            .of(buildContext.getSourcePathResolver().getAbsolutePath(proguardJarOverride.get()))
                    : Optional.empty(),
            proguardMaxHeapSize, proguardAgentPath, proguardConfigsBuilder.build(), sdkProguardConfig,
            optimizationPasses, proguardJvmArgs, inputOutputEntries,
            buildContext.getSourcePathResolver().getAllAbsolutePaths(additionalJarsForProguardAndDesugar),
            getProguardConfigDir(), buildableContext, buildContext, skipProguard, steps);

    // Apply the transformed inputs to the classpath (this will modify deps.classpathEntriesToDex
    // so that we're now dexing the proguarded artifacts). However, if we are not running
    // ProGuard then return the input classes to dex.
    if (skipProguard) {
        return ImmutableSet.copyOf(inputOutputEntries.keySet());
    } else {
        return ImmutableSet.copyOf(inputOutputEntries.values());
    }
}

From source file:com.facebook.buck.android.AndroidBinaryRule.java

/**
 * @return the resulting set of ProGuarded classpath entries to dex.
 */// w  ww .  j  av a2 s . c om
@VisibleForTesting
ImmutableSet<String> addProguardCommands(BuildContext context, Set<String> classpathEntriesToDex,
        Set<String> depsProguardConfigs, ImmutableList.Builder<Step> steps, Set<String> resDirectories) {
    final ImmutableSetMultimap<JavaLibraryRule, String> classpathEntriesMap = getTransitiveClasspathEntries();
    ImmutableSet.Builder<String> additionalLibraryJarsForProguardBuilder = ImmutableSet.builder();

    for (BuildRule buildRule : buildRulesToExcludeFromDex) {
        if (buildRule instanceof JavaLibraryRule) {
            additionalLibraryJarsForProguardBuilder
                    .addAll(classpathEntriesMap.get((JavaLibraryRule) buildRule));
        }
    }

    // Clean out the directory for generated ProGuard files.
    Path proguardDirectory = getPathForProGuardDirectory();
    steps.add(new MakeCleanDirectoryStep(proguardDirectory));

    // Generate a file of ProGuard config options using aapt.
    String generatedProGuardConfig = proguardDirectory + "/proguard.txt";
    GenProGuardConfigStep genProGuardConfig = new GenProGuardConfigStep(getAndroidManifestXml(), resDirectories,
            generatedProGuardConfig);
    steps.add(genProGuardConfig);

    // Create list of proguard Configs for the app project and its dependencies
    ImmutableSet.Builder<String> proguardConfigsBuilder = ImmutableSet.builder();
    proguardConfigsBuilder.addAll(depsProguardConfigs);
    if (proguardConfig.isPresent()) {
        proguardConfigsBuilder.add(proguardConfig.get().resolve(context).toString());
    }

    // Transform our input classpath to a set of output locations for each input classpath.
    // TODO(devjasta): the output path we choose is the result of a slicing function against
    // input classpath. This is fragile and should be replaced with knowledge of the BuildTarget.
    final ImmutableMap<String, String> inputOutputEntries = FluentIterable.from(classpathEntriesToDex)
            .toMap(new Function<String, String>() {
                @Override
                public String apply(String classpathEntry) {
                    return getProguardOutputFromInputClasspath(classpathEntry).toString();
                }
            });

    // Run ProGuard on the classpath entries.
    // TODO: ProGuardObfuscateStep's final argument should be a Path
    Step obfuscateCommand = ProGuardObfuscateStep.create(generatedProGuardConfig,
            proguardConfigsBuilder.build(), useAndroidProguardConfigWithOptimizations, inputOutputEntries,
            additionalLibraryJarsForProguardBuilder.build(), proguardDirectory.toString());
    steps.add(obfuscateCommand);

    // Apply the transformed inputs to the classpath (this will modify deps.classpathEntriesToDex
    // so that we're now dexing the proguarded artifacts).
    return ImmutableSet.copyOf(inputOutputEntries.values());
}

From source file:org.kiji.scoring.impl.InternalFreshKijiTableReader.java

/** {@inheritDoc} */
@Override//from w  w w .  j  a  v a2  s  .  c  o  m
public KijiRowData get(final EntityId entityId, final KijiDataRequest dataRequest,
        final FreshRequestOptions options) throws IOException {
    requireState(LifecycleState.OPEN);
    // Get the start time for the request.
    final long startTime = System.nanoTime();

    final String id = String.format("%s#%s", mReaderUID, mUniqueIdGenerator.getNextUniqueId());
    LOG.debug("{} starting with EntityId: {} data request: {} request options: {}", id, entityId, dataRequest,
            options);

    final KijiTableReader requestReader = ScoringUtils.getPooledReader(mReaderPool);
    try {
        final ImmutableList<KijiColumnName> requestColumns = removeDisabledColumns(
                getColumnsFromRequest(dataRequest), options.getDisabledColumns());

        final ImmutableMap<KijiColumnName, Freshener> fresheners;
        final ImmutableMap<KijiColumnName, KijiFreshenerRecord> records;
        // Get a retained snapshot of the rereadable state.
        final RereadableState rereadableState = getRereadableState();
        try {
            // Collect the Fresheners and Records applicable to this request.
            fresheners = filterFresheners(requestColumns, rereadableState.mFresheners);
            records = filterRecords(rereadableState.mFreshenerRecords, requestColumns);
            // If there are no Fresheners attached to the requested columns, return the requested data.
            if (fresheners.isEmpty()) {
                return requestReader.get(entityId, dataRequest);
            } else {
                // Retain the Fresheners so that they cannot be cleaned up while in use.
                for (Map.Entry<KijiColumnName, Freshener> freshenerEntry : fresheners.entrySet()) {
                    freshenerEntry.getValue().retain();
                }
            }
        } finally {
            rereadableState.release();
        }

        LOG.debug("{} will run Fresheners: {}", id, fresheners.values());

        final Future<KijiRowData> clientDataFuture = ScoringUtils.getFuture(mExecutorService,
                new TableReadCallable(mReaderPool, entityId, dataRequest));

        final FresheningRequestContext requestContext = new FresheningRequestContext(id, startTime, fresheners,
                options.getParameters(), records, mReaderPool, entityId, dataRequest, clientDataFuture,
                mBufferedWriter, mAllowPartial, mStatisticGatheringMode, mStatisticsQueue, mExecutorService);

        final ImmutableList<Future<Boolean>> futures = requestContext.getFuturesForFresheners();

        final Future<List<Boolean>> superFuture = ScoringUtils.getFuture(mExecutorService,
                new FutureAggregatingCallable<Boolean>(futures));

        // If the options specify timeout of -1 this indicates we should use the configured timeout.
        final long timeout = (-1 == options.getTimeout()) ? mTimeout : options.getTimeout();
        try {
            if (ScoringUtils.getFromFuture(superFuture, timeout).contains(true)) {
                // If all Fresheners return in time and at least one has written a new value, read from
                // the table.
                LOG.debug("{} completed on time and data was written.", id);
                return requestReader.get(entityId, dataRequest);
            } else {
                // If all Fresheners return in time, but none have written new values, do not read from
                // the table.
                LOG.debug("{} completed on time and no data was written.", id);
                try {
                    return ScoringUtils.getFromFuture(clientDataFuture, 0L);
                } catch (TimeoutException te) {
                    // If client data is not immediately available, read from the table.
                    return requestReader.get(entityId, dataRequest);
                }
            }
        } catch (TimeoutException te) {
            requestContext.timeOut();
            // If superFuture times out, read partially freshened data from the table or return the
            // cached data based on whether partial freshness is allowed.
            LOG.debug("{} timed out, checking for partial writes.", id);
            return requestContext.checkAndRead();
        }
    } finally {
        // Return the reader to the pool.
        requestReader.close();
    }
}

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

public static CxxLinkAndCompileRules createBuildRulesForCxxBinary(BuildRuleParams params,
        BuildRuleResolver resolver, CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform,
        ImmutableMap<String, CxxSource> srcs, ImmutableMap<Path, SourcePath> headers,
        Iterable<? extends BuildRule> deps, Optional<StripStyle> stripStyle,
        Optional<LinkerMapMode> flavoredLinkerMapMode, Linker.LinkableDepType linkStyle,
        ImmutableList<String> preprocessorFlags,
        PatternMatchedCollection<ImmutableList<String>> platformPreprocessorFlags,
        ImmutableMap<CxxSource.Type, ImmutableList<String>> langPreprocessorFlags,
        ImmutableSortedSet<FrameworkPath> frameworks, ImmutableSortedSet<FrameworkPath> libraries,
        ImmutableList<String> compilerFlags,
        ImmutableMap<CxxSource.Type, ImmutableList<String>> langCompilerFlags,
        PatternMatchedCollection<ImmutableList<String>> platformCompilerFlags,
        Optional<SourcePath> prefixHeader, Optional<SourcePath> precompiledHeader,
        ImmutableList<String> linkerFlags, PatternMatchedCollection<ImmutableList<String>> platformLinkerFlags,
        Optional<Linker.CxxRuntimeType> cxxRuntimeType, ImmutableList<String> includeDirs,
        Optional<Boolean> xcodePrivateHeadersSymlinks) throws NoSuchBuildTargetException {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver sourcePathResolver = new SourcePathResolver(ruleFinder);
    //    TODO(beefon): should be:
    //    Path linkOutput = getLinkOutputPath(
    //        createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode),
    //        params.getProjectFilesystem());

    BuildTarget target = params.getBuildTarget();
    if (flavoredLinkerMapMode.isPresent()) {
        target = target.withAppendedFlavors(flavoredLinkerMapMode.get().getFlavor());
    }//from  ww w.ja  v  a2  s .c  o m
    Path linkOutput = getBinaryOutputPath(target, params.getProjectFilesystem(),
            cxxPlatform.getBinaryExtension());
    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();
    CommandTool.Builder executableBuilder = new CommandTool.Builder();

    // Setup the header symlink tree and combine all the preprocessor input from this rule
    // and all dependencies.
    boolean shouldCreatePrivateHeadersSymlinks = xcodePrivateHeadersSymlinks.orElse(true);
    HeaderSymlinkTree headerSymlinkTree = requireHeaderSymlinkTree(params, resolver, sourcePathResolver,
            cxxPlatform, headers, HeaderVisibility.PRIVATE, shouldCreatePrivateHeadersSymlinks);
    Optional<SymlinkTree> sandboxTree = Optional.empty();
    if (cxxBuckConfig.sandboxSources()) {
        sandboxTree = createSandboxTree(params, resolver, cxxPlatform);
    }
    ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput = collectCxxPreprocessorInput(params, cxxPlatform,
            CxxFlags.getLanguageFlags(
                    preprocessorFlags, platformPreprocessorFlags, langPreprocessorFlags, cxxPlatform),
            ImmutableList.of(headerSymlinkTree), frameworks,
            CxxPreprocessables.getTransitiveCxxPreprocessorInput(cxxPlatform,
                    RichStream.from(deps).filter(CxxPreprocessorDep.class::isInstance).toImmutableList()),
            includeDirs, sandboxTree);

    // Generate and add all the build rules to preprocess and compile the source to the
    // resolver and get the `SourcePath`s representing the generated object files.
    ImmutableMap<CxxPreprocessAndCompile, SourcePath> objects = CxxSourceRuleFactory
            .requirePreprocessAndCompileRules(params, resolver, sourcePathResolver, ruleFinder, cxxBuckConfig,
                    cxxPlatform, cxxPreprocessorInput,
                    CxxFlags.getLanguageFlags(compilerFlags, platformCompilerFlags, langCompilerFlags,
                            cxxPlatform),
                    prefixHeader, precompiledHeader, srcs,
                    linkStyle == Linker.LinkableDepType.STATIC ? CxxSourceRuleFactory.PicType.PDC
                            : CxxSourceRuleFactory.PicType.PIC,
                    sandboxTree);

    // Build up the linker flags, which support macro expansion.
    ImmutableList<String> resolvedLinkerFlags = CxxFlags.getFlags(linkerFlags, platformLinkerFlags,
            cxxPlatform);
    argsBuilder.addAll(resolvedLinkerFlags.stream().map(MacroArg.toMacroArgFunction(MACRO_HANDLER,
            params.getBuildTarget(), params.getCellRoots(), resolver)::apply).iterator());

    // Special handling for dynamically linked binaries.
    if (linkStyle == Linker.LinkableDepType.SHARED) {

        // Create a symlink tree with for all shared libraries needed by this binary.
        SymlinkTree sharedLibraries = requireSharedLibrarySymlinkTree(params, resolver, sourcePathResolver,
                cxxPlatform, deps, NativeLinkable.class::isInstance);

        // Embed a origin-relative library path into the binary so it can find the shared libraries.
        // The shared libraries root is absolute. Also need an absolute path to the linkOutput

        Path absLinkOut = params.getBuildTarget().getCellPath().resolve(linkOutput);

        argsBuilder.addAll(StringArg.from(Linkers.iXlinker("-rpath",
                String.format("%s/%s", cxxPlatform.getLd().resolve(resolver).origin(),
                        absLinkOut.getParent().relativize(sharedLibraries.getRoot()).toString()))));

        // Add all the shared libraries and the symlink tree as inputs to the tool that represents
        // this binary, so that users can attach the proper deps.
        executableBuilder.addDep(sharedLibraries);
        executableBuilder.addInputs(sharedLibraries.getLinks().values());
    }

    // Add object files into the args.
    ImmutableList<SourcePathArg> objectArgs = SourcePathArg.from(sourcePathResolver, objects.values()).stream()
            .map(input -> {
                Preconditions.checkArgument(input instanceof SourcePathArg);
                return (SourcePathArg) input;
            }).collect(MoreCollectors.toImmutableList());
    argsBuilder.addAll(FileListableLinkerInputArg.from(objectArgs));

    BuildTarget linkRuleTarget = createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode);

    CxxLink cxxLink = createCxxLinkRule(params, resolver, cxxBuckConfig, cxxPlatform,
            RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(), linkStyle, frameworks,
            libraries, cxxRuntimeType, sourcePathResolver, ruleFinder, linkOutput, argsBuilder, linkRuleTarget);

    BuildRule binaryRuleForExecutable;
    Optional<CxxStrip> cxxStrip = Optional.empty();
    if (stripStyle.isPresent()) {
        BuildRuleParams cxxParams = params;
        if (flavoredLinkerMapMode.isPresent()) {
            cxxParams = params.withFlavor(flavoredLinkerMapMode.get().getFlavor());
        }
        CxxStrip stripRule = createCxxStripRule(cxxParams, resolver, stripStyle.get(), sourcePathResolver,
                cxxLink, cxxPlatform);
        cxxStrip = Optional.of(stripRule);
        binaryRuleForExecutable = stripRule;
    } else {
        binaryRuleForExecutable = cxxLink;
    }

    // Add the output of the link as the lone argument needed to invoke this binary as a tool.
    executableBuilder.addArg(new SourcePathArg(sourcePathResolver,
            new BuildTargetSourcePath(binaryRuleForExecutable.getBuildTarget())));

    return new CxxLinkAndCompileRules(cxxLink, cxxStrip, ImmutableSortedSet.copyOf(objects.keySet()),
            executableBuilder.build());
}

From source file:com.techcavern.pircbotz.UserChannelDao.java

@Synchronized("accessLock")
public UserChannelDaoSnapshot createSnapshot() {
    //Create snapshots of all users and channels
    ImmutableMap.Builder<U, UserSnapshot> userSnapshotBuilder = ImmutableMap.builder();
    for (U curUser : userNickMap.values())
        userSnapshotBuilder.put(curUser, curUser.createSnapshot());
    ImmutableMap<U, UserSnapshot> userSnapshotMap = userSnapshotBuilder.build();
    ImmutableMap.Builder<C, ChannelSnapshot> channelSnapshotBuilder = ImmutableMap.builder();
    for (C curChannel : channelNameMap.values())
        channelSnapshotBuilder.put(curChannel, curChannel.createSnapshot());
    ImmutableMap<C, ChannelSnapshot> channelSnapshotMap = channelSnapshotBuilder.build();

    //Make snapshots of the relationship maps using the above user and channel snapshots
    UserChannelMapSnapshot mainMapSnapshot = mainMap.createSnapshot(userSnapshotMap, channelSnapshotMap);
    EnumMap<UserLevel, UserChannelMap<UserSnapshot, ChannelSnapshot>> levelsMapSnapshot = Maps
            .newEnumMap(UserLevel.class);
    for (Map.Entry<UserLevel, UserChannelMap<U, C>> curLevel : levelsMap.entrySet())
        levelsMapSnapshot.put(curLevel.getKey(),
                curLevel.getValue().createSnapshot(userSnapshotMap, channelSnapshotMap));
    ImmutableBiMap.Builder<String, UserSnapshot> userNickMapSnapshotBuilder = ImmutableBiMap.builder();
    for (Map.Entry<String, U> curNick : userNickMap.entrySet())
        userNickMapSnapshotBuilder.put(curNick.getKey(), curNick.getValue().createSnapshot());
    ImmutableBiMap.Builder<String, ChannelSnapshot> channelNameMapSnapshotBuilder = ImmutableBiMap.builder();
    for (Map.Entry<String, C> curName : channelNameMap.entrySet())
        channelNameMapSnapshotBuilder.put(curName.getKey(), curName.getValue().createSnapshot());
    ImmutableSortedSet.Builder<UserSnapshot> privateUserSnapshotBuilder = ImmutableSortedSet.naturalOrder();
    for (User curUser : privateUsers)
        privateUserSnapshotBuilder.add(curUser.createSnapshot());

    //Finally can create the snapshot object
    UserChannelDaoSnapshot daoSnapshot = new UserChannelDaoSnapshot(bot, locale, mainMapSnapshot,
            levelsMapSnapshot, userNickMapSnapshotBuilder.build(), channelNameMapSnapshotBuilder.build(),
            privateUserSnapshotBuilder.build());

    //Tell UserSnapshots and ChannelSnapshots what the new backing dao is
    for (UserSnapshot curUserSnapshot : userSnapshotMap.values())
        curUserSnapshot.setDao(daoSnapshot);
    for (ChannelSnapshot curChannelSnapshot : channelSnapshotMap.values())
        curChannelSnapshot.setDao(daoSnapshot);

    //Finally/*from   ww  w.  j  ava2s .c  om*/
    return daoSnapshot;
}

From source file:com.facebook.presto.connector.jmx.JmxDataStreamProvider.java

private RecordSet createRecordSet(Split split, List<ColumnHandle> columns) {
    checkNotNull(split, "split is null");
    checkArgument(split instanceof JmxSplit, "Split must be of type %s, not %s", JmxSplit.class.getName(),
            split.getClass().getName());
    JmxTableHandle tableHandle = ((JmxSplit) split).getTableHandle();

    checkNotNull(columns, "columns is null");
    checkArgument(!columns.isEmpty(), "must provide at least one column");

    ImmutableMap.Builder<String, ColumnType> builder = ImmutableMap.builder();
    for (ColumnHandle column : columns) {
        checkArgument(column instanceof JmxColumnHandle, "column must be of type %s, not %s",
                JmxColumnHandle.class.getName(), column.getClass().getName());
        JmxColumnHandle jmxColumnHandle = (JmxColumnHandle) column;
        builder.put(jmxColumnHandle.getColumnName(), jmxColumnHandle.getColumnType());
    }//  ww  w  .jav  a  2 s .  com
    ImmutableMap<String, ColumnType> columnTypes = builder.build();

    List<List<Object>> rows;
    try {
        Map<String, Object> attributes = getAttributes(columnTypes.keySet(), tableHandle);
        List<Object> row = new ArrayList<>();
        // NOTE: data must be produced in the order of the columns parameter.  This code relies on the
        // fact that columnTypes is an ImmutableMap which is an order preserving LinkedHashMap under
        // the covers.
        for (Entry<String, ColumnType> entry : columnTypes.entrySet()) {
            if (entry.getKey().equals("node")) {
                row.add(nodeId);
            } else {
                Object value = attributes.get(entry.getKey());
                if (value == null) {
                    row.add(null);
                } else {
                    switch (entry.getValue()) {
                    case BOOLEAN:
                        if (value instanceof Boolean) {
                            row.add(value);
                        } else {
                            // mbeans can lie about types
                            row.add(null);
                        }
                        break;
                    case LONG:
                        if (value instanceof Number) {
                            row.add(((Number) value).longValue());
                        } else {
                            // mbeans can lie about types
                            row.add(null);
                        }
                        break;
                    case DOUBLE:
                        if (value instanceof Number) {
                            row.add(((Number) value).doubleValue());
                        } else {
                            // mbeans can lie about types
                            row.add(null);
                        }
                        break;
                    case STRING:
                        row.add(value.toString());
                        break;
                    }
                }
            }
        }
        rows = ImmutableList.of(row);
    } catch (JMException e) {
        rows = ImmutableList.of();
    }

    return new InMemoryRecordSet(columnTypes.values(), rows);
}

From source file:org.chaston.oakfunds.storage.mgmt.SchemaValidator.java

Iterable<SchemaDiscrepancy> validateSchema() throws SQLException {
    ImmutableMap<String, TableDef> tableDefs = schemaBuilder.getTableDefs();
    ImmutableMap<String, FunctionDef> functionDefs = schemaBuilder.getFunctionDefs();
    ImmutableList.Builder<SchemaDiscrepancy> schemaDiscrepancies = ImmutableList.builder();
    Set<String> seenTables = new HashSet<>();
    Set<String> seenFunctions = new HashSet<>();
    try (Connection connection = dataSource.getConnection()) {
        DatabaseMetaData metaData = connection.getMetaData();

        if (databaseVariantHandler.requiresSchemaCreation()) {
            // Look for schema.
            ResultSet allSchemas = metaData.getSchemas(null,
                    databaseVariantHandler.toDatabaseForm(SystemColumnDefs.SCHEMA));
            if (!allSchemas.next()) {
                schemaDiscrepancies.add(new MissingSchema(SystemColumnDefs.SCHEMA));
            }/*from  w ww. j a  v  a  2 s  .  c o m*/
        }

        // Look for tables.
        try (ResultSet allTables = metaData.getTables(null,
                databaseVariantHandler.toDatabaseForm(SystemColumnDefs.SCHEMA), null, null)) {
            while (allTables.next()) {
                String tableName = databaseVariantHandler.toNormalName(allTables.getString("TABLE_NAME"));
                TableDef tableDef = tableDefs.get(tableName);
                if (tableDef == null) {
                    // Table that the defs do not know (and hence care) about.
                    continue;
                }
                seenTables.add(tableName);
                validateTable(metaData, tableDef, schemaDiscrepancies);
            }
        }

        // Look for functions.
        try (ResultSet allFunctions = metaData.getFunctions(null,
                databaseVariantHandler.toDatabaseForm(SystemColumnDefs.SCHEMA), null)) {
            while (allFunctions.next()) {
                String functionName = databaseVariantHandler
                        .toNormalName(allFunctions.getString("FUNCTION_NAME"));
                FunctionDef functionDef = functionDefs.get(functionName);
                if (functionDef == null) {
                    // Function that the defs do not know (and hence care) about.
                    continue;
                }
                seenFunctions.add(functionName);
                // TODO: validate function (?)
            }
        }
    }
    for (TableDef expectedTable : tableDefs.values()) {
        if (!seenTables.contains(expectedTable.getName())) {
            schemaDiscrepancies.add(new MissingTable(expectedTable));
        }
    }
    for (FunctionDef expectedFunction : functionDefs.values()) {
        if (!seenFunctions.contains(expectedFunction.getName())) {
            schemaDiscrepancies.add(new MissingFunction(expectedFunction));
        }
    }
    return schemaDiscrepancies.build();
}

From source file:com.isotrol.impe3.pms.core.impl.PortalConfigurationManagerImpl.java

private void setValues(ConfigurationDefinition<?> cd, ConfigurationEntity entity,
        Collection<ConfigurationItemDTO> configuration) throws PMSException {
    checkNotNull(configuration);//from  ww w .j  a  va  2 s .  co  m
    checkArgument(!configuration.isEmpty() || cd.getMBPParameters().isEmpty());
    final Map<String, ConfigurationValue> values = entity.getValues();
    values.clear();
    final ImmutableMap<String, Item> parameters = cd.getParameters();
    for (final ConfigurationItemDTO itemDTO : configuration) {
        final String name = itemDTO.getKey();
        checkNotNull(name);
        checkArgument(!values.containsKey(name));
        checkArgument(parameters.containsKey(name));
        final Item item = parameters.get(name);
        final String value = itemDTO.getCurrentValue();
        if (value == null) {
            if (item.isMVP()) {
                logger.error("Configuration [{}] type [{}]: Required item [{}].",
                        new Object[] { entity.getId().toString(), cd.getType().getName(), name });
                throw new IllegalArgumentException(); // TODO
            }
            continue;
        }
        final ConfigurationValue configValue = new ConfigurationValue();
        final Class<?> type = item.getType();
        if (item.isEnum()) {
            configValue.setStringValue(((Enum<?>) item.fromString(value)).name());
        } else if (String.class == type) {
            configValue.setStringValue(value);
        } else if (Integer.class == type) {
            configValue.setIntegerValue(Integer.valueOf(value));
        } else if (FileId.class == type) {
            FileEntity file = load(FileEntity.class, value, NotFoundProviders.FILE);
            if (file.getPurpose() == FilePurpose.UNKNOWN) {
                file.setPurpose(FilePurpose.CONFIG);
            }
            NotFoundProviders.FILE.checkCondition(file.getPurpose() == FilePurpose.CONFIG, value);
            if (item.isCompressed()) {
                file.compress();
            }
            file.setBundle(item.isBundle());
            file.setDownloadable(item.isDownloadable());
            configValue.setFileValue(file);
        } else if (Category.class == type) {
            configValue.setCategoryValue(load(CategoryEntity.class, value, NotFoundProviders.CATEGORY));
        } else if (ContentType.class == type) {
            configValue
                    .setContentTypeValue(load(ContentTypeEntity.class, value, NotFoundProviders.CONTENT_TYPE));
        } else if (Boolean.class == type) {
            configValue.setBooleanValue(Boolean.valueOf(value));
        } else {
            logger.error("Configuration [{}] type [{}] item [{}] Invalid type.",
                    new Object[] { entity.getId().toString(), cd.getType().getName(), name });
            // TODO: other types.
            throw new IllegalStateException();
        }
        values.put(name, configValue);
    }
    for (final Item item : parameters.values()) {
        checkState(!item.isMVP() || values.containsKey(item.getParameter()));
    }
}

From source file:com.isotrol.impe3.pms.core.impl.ConfigurationManagerImpl.java

private void setValues(PortalConfigurationDefinition<?> cd, ConfigurationEntity entity,
        Collection<ConfigurationItemDTO> configuration) throws PMSException {
    checkNotNull(configuration);//from www .  j  a  v a2s. co  m
    checkArgument(!configuration.isEmpty() || cd.getMBPParameters().isEmpty());
    final Map<String, ConfigurationValue> values = entity.getValues();
    values.clear();
    final ImmutableMap<String, Item> parameters = cd.getParameters();
    for (final ConfigurationItemDTO itemDTO : configuration) {
        final String name = itemDTO.getKey();
        checkNotNull(name);
        checkArgument(!values.containsKey(name));
        checkArgument(parameters.containsKey(name));
        final Item item = parameters.get(name);
        final String value = itemDTO.getCurrentValue();
        if (value == null) {
            if (item.isMVP()) {
                logger.error("Configuration [{}] type [{}]: Required item [{}].",
                        new Object[] { entity.getId().toString(), cd.getType().getName(), name });
                throw new IllegalArgumentException(); // TODO
            }
            continue;
        }
        final ConfigurationValue configValue = new ConfigurationValue();
        final Class<?> type = item.getType();
        if (item.isEnum()) {
            configValue.setStringValue(((Enum<?>) item.fromString(value)).name());
        } else if (String.class == type) {
            configValue.setStringValue(value);
        } else if (Integer.class == type) {
            configValue.setIntegerValue(Integer.valueOf(value));
        } else if (FileId.class == type) {
            FileEntity file = load(FileEntity.class, value, NotFoundProviders.FILE);
            if (file.getPurpose() == FilePurpose.UNKNOWN) {
                file.setPurpose(FilePurpose.CONFIG);
            }
            NotFoundProviders.FILE.checkCondition(file.getPurpose() == FilePurpose.CONFIG, value);
            if (item.isCompressed()) {
                file.compress();
            }
            file.setBundle(item.isBundle());
            file.setDownloadable(item.isDownloadable());
            configValue.setFileValue(file);
        } else if (Category.class == type) {
            configValue.setCategoryValue(load(CategoryEntity.class, value, NotFoundProviders.CATEGORY));
        } else if (ContentType.class == type) {
            configValue
                    .setContentTypeValue(load(ContentTypeEntity.class, value, NotFoundProviders.CONTENT_TYPE));
        } else if (Boolean.class == type) {
            configValue.setBooleanValue(Boolean.valueOf(value));
        } else {
            logger.error("Configuration [{}] type [{}] item [{}] Invalid type.",
                    new Object[] { entity.getId().toString(), cd.getType().getName(), name });
            // TODO: other types.
            throw new IllegalStateException();
        }
        values.put(name, configValue);
    }
    for (final Item item : parameters.values()) {
        checkState(!item.isMVP() || values.containsKey(item.getParameter()));
    }
}

From source file:org.elasticsearch.snapshots.SnapshotsService.java

/**
 * Starts snapshot.//from  w  ww . ja  v  a 2 s.  c o  m
 * <p/>
 * Creates snapshot in repository and updates snapshot metadata record with list of shards that needs to be processed.
 *
 * @param clusterState               cluster state
 * @param snapshot                   snapshot meta data
 * @param partial                    allow partial snapshots
 * @param userCreateSnapshotListener listener
 */
private void beginSnapshot(ClusterState clusterState, final SnapshotMetaData.Entry snapshot,
        final boolean partial, final CreateSnapshotListener userCreateSnapshotListener) {
    boolean snapshotCreated = false;
    try {
        Repository repository = repositoriesService.repository(snapshot.snapshotId().getRepository());

        MetaData metaData = clusterState.metaData();
        if (!snapshot.includeGlobalState()) {
            // Remove global state from the cluster state
            MetaData.Builder builder = MetaData.builder();
            for (String index : snapshot.indices()) {
                builder.put(metaData.index(index), false);
            }
            metaData = builder.build();
        }

        repository.initializeSnapshot(snapshot.snapshotId(), snapshot.indices(), metaData);
        snapshotCreated = true;
        if (snapshot.indices().isEmpty()) {
            // No indices in this snapshot - we are done
            userCreateSnapshotListener.onResponse();
            endSnapshot(snapshot);
            return;
        }
        clusterService.submitStateUpdateTask("update_snapshot [" + snapshot + "]",
                new ProcessedClusterStateUpdateTask() {
                    boolean accepted = false;
                    SnapshotMetaData.Entry updatedSnapshot;
                    String failure = null;

                    @Override
                    public ClusterState execute(ClusterState currentState) {
                        MetaData metaData = currentState.metaData();
                        MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
                        SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
                        ImmutableList.Builder<SnapshotMetaData.Entry> entries = ImmutableList.builder();
                        for (SnapshotMetaData.Entry entry : snapshots.entries()) {
                            if (entry.snapshotId().equals(snapshot.snapshotId())) {
                                // Replace the snapshot that was just created
                                ImmutableMap<ShardId, SnapshotMetaData.ShardSnapshotStatus> shards = shards(
                                        snapshot.snapshotId(), currentState, snapshot.indices());
                                if (!partial) {
                                    Set<String> indicesWithMissingShards = indicesWithMissingShards(shards);
                                    if (indicesWithMissingShards != null) {
                                        updatedSnapshot = new SnapshotMetaData.Entry(snapshot.snapshotId(),
                                                snapshot.includeGlobalState(), State.FAILED, snapshot.indices(),
                                                shards);
                                        entries.add(updatedSnapshot);
                                        failure = "Indices don't have primary shards +["
                                                + indicesWithMissingShards + "]";
                                        continue;
                                    }
                                }
                                updatedSnapshot = new SnapshotMetaData.Entry(snapshot.snapshotId(),
                                        snapshot.includeGlobalState(), State.STARTED, snapshot.indices(),
                                        shards);
                                entries.add(updatedSnapshot);
                                if (!completed(shards.values())) {
                                    accepted = true;
                                }
                            } else {
                                entries.add(entry);
                            }
                        }
                        mdBuilder.putCustom(SnapshotMetaData.TYPE, new SnapshotMetaData(entries.build()));
                        return ClusterState.builder(currentState).metaData(mdBuilder).build();
                    }

                    @Override
                    public void onFailure(String source, Throwable t) {
                        logger.warn("[{}] failed to create snapshot", t, snapshot.snapshotId());
                        userCreateSnapshotListener.onFailure(t);
                    }

                    @Override
                    public void clusterStateProcessed(String source, ClusterState oldState,
                            ClusterState newState) {
                        // The userCreateSnapshotListener.onResponse() notifies caller that the snapshot was accepted
                        // for processing. If client wants to wait for the snapshot completion, it can register snapshot
                        // completion listener in this method. For the snapshot completion to work properly, the snapshot
                        // should still exist when listener is registered.
                        userCreateSnapshotListener.onResponse();

                        // Now that snapshot completion listener is registered we can end the snapshot if needed
                        // We should end snapshot only if 1) we didn't accept it for processing (which happens when there
                        // is nothing to do) and 2) there was a snapshot in metadata that we should end. Otherwise we should
                        // go ahead and continue working on this snapshot rather then end here.
                        if (!accepted && updatedSnapshot != null) {
                            endSnapshot(updatedSnapshot, failure);
                        }
                    }
                });
    } catch (Throwable t) {
        logger.warn("failed to create snapshot [{}]", t, snapshot.snapshotId());
        clusterService.submitStateUpdateTask("fail_snapshot [" + snapshot.snapshotId() + "]",
                new ClusterStateUpdateTask() {

                    @Override
                    public ClusterState execute(ClusterState currentState) {
                        MetaData metaData = currentState.metaData();
                        MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
                        SnapshotMetaData snapshots = metaData.custom(SnapshotMetaData.TYPE);
                        ImmutableList.Builder<SnapshotMetaData.Entry> entries = ImmutableList.builder();
                        for (SnapshotMetaData.Entry entry : snapshots.entries()) {
                            if (!entry.snapshotId().equals(snapshot.snapshotId())) {
                                entries.add(entry);
                            }
                        }
                        mdBuilder.putCustom(SnapshotMetaData.TYPE, new SnapshotMetaData(entries.build()));
                        return ClusterState.builder(currentState).metaData(mdBuilder).build();
                    }

                    @Override
                    public void onFailure(String source, Throwable t) {
                        logger.warn("[{}] failed to delete snapshot", t, snapshot.snapshotId());
                    }
                });
        if (snapshotCreated) {
            try {
                repositoriesService.repository(snapshot.snapshotId().getRepository()).finalizeSnapshot(
                        snapshot.snapshotId(), ExceptionsHelper.detailedMessage(t), 0,
                        ImmutableList.<SnapshotShardFailure>of());
            } catch (Throwable t2) {
                logger.warn("[{}] failed to close snapshot in repository", snapshot.snapshotId());
            }
        }
        userCreateSnapshotListener.onFailure(t);
    }
}