Example usage for com.google.common.collect Maps filterKeys

List of usage examples for com.google.common.collect Maps filterKeys

Introduction

In this page you can find the example usage for com.google.common.collect Maps filterKeys.

Prototype

@CheckReturnValue
public static <K, V> BiMap<K, V> filterKeys(BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) 

Source Link

Document

Returns a bimap containing the mappings in unfiltered whose keys satisfy a predicate.

Usage

From source file:org.apache.brooklyn.location.jclouds.ComputeServiceRegistryImpl.java

@Override
public ComputeService findComputeService(ConfigBag conf, boolean allowReuse) {
    String provider = checkNotNull(conf.get(CLOUD_PROVIDER), "provider must not be null");
    String identity = checkNotNull(conf.get(CloudLocationConfig.ACCESS_IDENTITY), "identity must not be null");
    String credential = checkNotNull(conf.get(CloudLocationConfig.ACCESS_CREDENTIAL),
            "credential must not be null");

    Properties properties = new Properties();
    properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, Boolean.toString(true));
    properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, Boolean.toString(true));
    properties.setProperty("jclouds.ssh.max-retries",
            conf.getStringKey("jclouds.ssh.max-retries") != null
                    ? conf.getStringKey("jclouds.ssh.max-retries").toString()
                    : "50");
    // Enable aws-ec2 lazy image fetching, if given a specific imageId; otherwise customize for specific owners; or all as a last resort
    // See https://issues.apache.org/jira/browse/WHIRR-416
    if ("aws-ec2".equals(provider)) {
        // TODO convert AWS-only flags to config keys
        if (groovyTruth(conf.get(IMAGE_ID))) {
            properties.setProperty(PROPERTY_EC2_AMI_QUERY, "");
            properties.setProperty(PROPERTY_EC2_CC_AMI_QUERY, "");
        } else if (groovyTruth(conf.getStringKey("imageOwner"))) {
            properties.setProperty(PROPERTY_EC2_AMI_QUERY,
                    "owner-id=" + conf.getStringKey("imageOwner") + ";state=available;image-type=machine");
        } else if (groovyTruth(conf.getStringKey("anyOwner"))) {
            // set `anyOwner: true` to override the default query (which is restricted to certain owners as per below), 
            // allowing the AMI query to bind to any machine
            // (note however, we sometimes pick defaults in JcloudsLocationFactory);
            // (and be careful, this can give a LOT of data back, taking several minutes,
            // and requiring extra memory allocated on the command-line)
            properties.setProperty(PROPERTY_EC2_AMI_QUERY, "state=available;image-type=machine");
            /*//from   w ww  .j  a va2 s.c  om
             * by default the following filters are applied:
             * Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&
             * Filter.1.Value.2=063491364108&
             * Filter.1.Value.3=099720109477&
             * Filter.1.Value.4=411009282317&
             * Filter.2.Name=state&Filter.2.Value.1=available&
             * Filter.3.Name=image-type&Filter.3.Value.1=machine&
             */
        }

        // occasionally can get com.google.common.util.concurrent.UncheckedExecutionException: java.lang.RuntimeException: 
        //     security group eu-central-1/jclouds#brooklyn-bxza-alex-eu-central-shoul-u2jy-nginx-ielm is not available after creating
        // the default timeout was 500ms so let's raise it in case that helps
        properties.setProperty(EC2Constants.PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT,
                "" + Duration.seconds(30).toMilliseconds());
    }

    // FIXME Deprecated mechanism, should have a ConfigKey for overrides
    Map<String, Object> extra = Maps.filterKeys(conf.getAllConfig(), Predicates.containsPattern("^jclouds\\."));
    if (extra.size() > 0) {
        LOG.warn("Jclouds using deprecated property overrides: " + Sanitizer.sanitize(extra));
    }
    properties.putAll(extra);

    String endpoint = conf.get(CloudLocationConfig.CLOUD_ENDPOINT);
    if (!groovyTruth(endpoint))
        endpoint = getDeprecatedProperty(conf, Constants.PROPERTY_ENDPOINT);
    if (groovyTruth(endpoint))
        properties.setProperty(Constants.PROPERTY_ENDPOINT, endpoint);

    Map<?, ?> cacheKey = MutableMap.builder().putAll(properties).put("provider", provider)
            .put("identity", identity).put("credential", credential).putIfNotNull("endpoint", endpoint).build()
            .asUnmodifiable();

    if (allowReuse) {
        ComputeService result = cachedComputeServices.get(cacheKey);
        if (result != null) {
            LOG.trace("jclouds ComputeService cache hit for compute service, for "
                    + Sanitizer.sanitize(properties));
            return result;
        }
        LOG.debug("jclouds ComputeService cache miss for compute service, creating, for "
                + Sanitizer.sanitize(properties));
    }

    Iterable<Module> modules = getCommonModules();

    // Synchronizing to avoid deadlock from sun.reflect.annotation.AnnotationType.
    // See https://github.com/brooklyncentral/brooklyn/issues/974
    ComputeServiceContext computeServiceContext;
    synchronized (createComputeServicesMutex) {
        computeServiceContext = ContextBuilder.newBuilder(provider).modules(modules)
                .credentials(identity, credential).overrides(properties).build(ComputeServiceContext.class);
    }
    final ComputeService computeService = computeServiceContext.getComputeService();
    if (allowReuse) {
        synchronized (cachedComputeServices) {
            ComputeService result = cachedComputeServices.get(cacheKey);
            if (result != null) {
                LOG.debug("jclouds ComputeService cache recovery for compute service, for "
                        + Sanitizer.sanitize(cacheKey));
                //keep the old one, discard the new one
                computeService.getContext().close();
                return result;
            }
            LOG.debug("jclouds ComputeService created " + computeService + ", adding to cache, for "
                    + Sanitizer.sanitize(properties));
            cachedComputeServices.put(cacheKey, computeService);
        }
    }
    return computeService;
}

From source file:io.sarl.lang.scoping.batch.SARLMapExtensions.java

/** Replies the elements of the given map except the pair with the given key.
 *
 * <p>The replied map is a view on the given map. It means that any change
 * in the original map is reflected to the result of this operation.
 *
 * @param <K> - type of the map keys.
 * @param <V> - type of the map values.
 * @param map - the map to update./*from   w w w .jav  a 2  s  .  c  o m*/
 * @param key - the key to remove.
 * @return the map with the content of the map except the key.
 */
@Pure
public static <K, V> Map<K, V> operator_minus(Map<K, V> map, final K key) {
    return Maps.filterKeys(map, new Predicate<K>() {
        @Override
        public boolean apply(K input) {
            return !Objects.equal(input, key);
        }
    });
}

From source file:org.jfrog.hudson.release.PromoteBuildAction.java

/**
 * Form submission is calling this method
 *///from  ww w.  j a  v  a2  s  . c  o m
@SuppressWarnings({ "UnusedDeclaration" })
public void doSubmit(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {
    getACL().checkPermission(getPermission());

    req.bindParameters(this);

    JSONObject formData = req.getSubmittedForm();
    if (formData.has("promotionPlugin")) {
        JSONObject pluginSettings = formData.getJSONObject("promotionPlugin");
        if (pluginSettings.has("pluginName")) {
            String pluginName = pluginSettings.getString("pluginName");
            if (!UserPluginInfo.NO_PLUGIN_KEY.equals(pluginName)) {
                PluginSettings settings = new PluginSettings();
                Map<String, String> paramMap = Maps.newHashMap();
                settings.setPluginName(pluginName);
                Map<String, Object> filteredPluginSettings = Maps.filterKeys(pluginSettings,
                        new Predicate<String>() {
                            public boolean apply(String input) {
                                return StringUtils.isNotBlank(input) && !"pluginName".equals(input);
                            }
                        });
                for (Map.Entry<String, Object> settingsEntry : filteredPluginSettings.entrySet()) {
                    String key = settingsEntry.getKey();
                    paramMap.put(key, pluginSettings.getString(key));
                }
                if (!paramMap.isEmpty()) {
                    settings.setParamMap(paramMap);
                }
                setPromotionPlugin(settings);
            }
        }
    }

    ArtifactoryRedeployPublisher artifactoryPublisher = ActionableHelper.getPublisher(build.getProject(),
            ArtifactoryRedeployPublisher.class);
    ArtifactoryServer server = getArtifactoryServer();

    new PromoteWorkerThread(server, getCredentials(server)).start();

    resp.sendRedirect(".");
}

From source file:org.jfrog.bamboo.builder.BaseBuildInfoHelper.java

/**
 * Filters Bamboo global variables for build info model and matrix params
 *///from  ww w.ja  v a2 s .  c  om
protected Map<String, String> filterAndGetGlobalVariables() {
    Map<String, String> variablesToReturn = Maps.newHashMap();

    Map<String, String> globalVariables = getGlobalVariables();

    String propFilePath = globalVariables.get(BuildInfoConfigProperties.PROP_PROPS_FILE);
    if (StringUtils.isNotBlank(propFilePath)) {
        File propFile = new File(propFilePath);
        if (propFile.isFile()) {
            Properties fileProperties = new Properties();

            FileInputStream inputStream = null;
            try {
                inputStream = new FileInputStream(propFile);
                fileProperties.load(inputStream);
            } catch (IOException ioe) {
                log.error("Error occurred while trying to resolve build info properties from: " + propFilePath,
                        ioe);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }

            Properties filteredProperties = new Properties();
            filteredProperties.putAll(BuildInfoExtractorUtils.filterDynamicProperties(fileProperties,
                    BuildInfoExtractorUtils.MATRIX_PARAM_PREDICATE));
            filteredProperties.putAll(BuildInfoExtractorUtils.filterDynamicProperties(fileProperties,
                    BuildInfoExtractorUtils.BUILD_INFO_PROP_PREDICATE));

            for (Map.Entry filteredProperty : filteredProperties.entrySet()) {
                setVariable(variablesToReturn, ((String) filteredProperty.getKey()),
                        ((String) filteredProperty.getValue()));
            }
        }
    }

    addGlobalVariables(variablesToReturn,
            Maps.filterKeys(globalVariables, BuildInfoExtractorUtils.MATRIX_PARAM_PREDICATE));

    addGlobalVariables(variablesToReturn,
            Maps.filterKeys(globalVariables, BuildInfoExtractorUtils.BUILD_INFO_PROP_PREDICATE));

    return variablesToReturn;
}

From source file:org.pau.assetmanager.viewmodel.chart.ChartDataModel.java

private static Double getYearBeforeFinalVirtualStockBalance(Integer year,
        Table<Integer, Integer, Set<StockState>> historicalStockBalanceStateTable) {
    Double balance = 0.0;/*  w w w.  j  a v a  2s  .  c  o  m*/
    final Integer yearBefore = year - 1;
    Map<Integer, Map<Integer, Set<StockState>>> historicalStockBalanceStateRowMap = historicalStockBalanceStateTable
            .rowMap();
    historicalStockBalanceStateRowMap = Maps.filterKeys(historicalStockBalanceStateRowMap,
            new Predicate<Integer>() {
                @Override
                public boolean apply(Integer year) {
                    return year <= yearBefore;
                }
            });
    List<Integer> years = Lists.newArrayList(historicalStockBalanceStateRowMap.keySet());
    if (years.size() > 0) {
        Collections.sort(years);
        // get last year
        Integer lastYear = years.get(years.size() - 1);
        Map<Integer, Set<StockState>> historicalStockBalanceStateLastYear = historicalStockBalanceStateRowMap
                .get(lastYear);
        List<Integer> months = Lists.newArrayList(historicalStockBalanceStateLastYear.keySet());
        Collections.sort(months);
        Integer lastMonth = months.get(months.size() - 1);
        Set<StockState> historicalStockLastMonth = historicalStockBalanceStateLastYear.get(lastMonth);
        for (StockState currentStockState : historicalStockLastMonth) {
            balance += currentStockState.getVirtualBalance();
        }
    }
    return balance;
}

From source file:org.apache.cassandra.schema.IndexMetadata.java

private void validateCustomIndexOptions(CFMetaData cfm, Class<? extends Index> indexerClass,
        Map<String, String> options) throws ConfigurationException {
    try {/*  w w  w  .  j  a  v a2  s. c o  m*/
        Map<String, String> filteredOptions = Maps.filterKeys(options,
                key -> !key.equals(IndexTarget.CUSTOM_INDEX_OPTION_NAME));

        if (filteredOptions.isEmpty())
            return;

        Map<?, ?> unknownOptions;
        try {
            unknownOptions = (Map) indexerClass.getMethod("validateOptions", Map.class, CFMetaData.class)
                    .invoke(null, filteredOptions, cfm);
        } catch (NoSuchMethodException e) {
            unknownOptions = (Map) indexerClass.getMethod("validateOptions", Map.class).invoke(null,
                    filteredOptions);
        }

        if (!unknownOptions.isEmpty())
            throw new ConfigurationException(String.format("Properties specified %s are not understood by %s",
                    unknownOptions.keySet(), indexerClass.getSimpleName()));
    } catch (NoSuchMethodException e) {
        logger.info("Indexer {} does not have a static validateOptions method. Validation ignored",
                indexerClass.getName());
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof ConfigurationException)
            throw (ConfigurationException) e.getTargetException();
        throw new ConfigurationException("Failed to validate custom indexer options: " + options);
    } catch (ConfigurationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConfigurationException("Failed to validate custom indexer options: " + options);
    }
}

From source file:org.jahia.services.content.decorator.JCRProtectedNodeAbstractDecorator.java

@Override
public Map<String, String> getPropertiesAsString() throws RepositoryException {
    return (alwaysAllowSystem && getSession().isSystem()) ? super.getPropertiesAsString()
            : Maps.filterKeys(super.getPropertiesAsString(), new Predicate<String>() {
                @Override/*w  w  w.  ja va 2  s  .c  o  m*/
                public boolean apply(String input) {
                    try {
                        return canGetProperty(input);
                    } catch (RepositoryException e) {
                        return false;
                    }
                }
            });
}

From source file:com.streamsets.datacollector.record.HeaderImpl.java

@SuppressWarnings("unchecked")
public Map<String, String> getValues() {
    return (Map) Maps.filterKeys(map, this);
}

From source file:org.jfrog.hudson.plugins.artifactory.release.UnifiedPromoteBuildAction.java

/**
 * Form submission is calling this method
 *//*from  ww  w .  j  a v  a 2s.  c o m*/
@SuppressWarnings({ "UnusedDeclaration" })
public void doSubmit(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException {
    getACL().checkPermission(getPermission());

    req.bindParameters(this);

    // current user is bound to the thread and will be lost in the perform method
    User user = User.current();
    String ciUser = (user == null) ? "anonymous" : user.getId();

    JSONObject formData = req.getSubmittedForm();
    if (formData.has("promotionPlugin")) {
        JSONObject pluginSettings = formData.getJSONObject("promotionPlugin");
        if (pluginSettings.has("pluginName")) {
            String pluginName = pluginSettings.getString("pluginName");
            if (!UserPluginInfo.NO_PLUGIN_KEY.equals(pluginName)) {
                PluginSettings settings = new PluginSettings();
                Map<String, String> paramMap = Maps.newHashMap();
                settings.setPluginName(pluginName);
                Map<String, Object> filteredPluginSettings = Maps.filterKeys(pluginSettings,
                        new Predicate<String>() {
                            public boolean apply(String input) {
                                return StringUtils.isNotBlank(input) && !"pluginName".equals(input);
                            }
                        });
                for (Map.Entry<String, Object> settingsEntry : filteredPluginSettings.entrySet()) {
                    String key = settingsEntry.getKey();
                    paramMap.put(key, pluginSettings.getString(key));
                }
                paramMap.put("ciUser", ciUser);
                if (!paramMap.isEmpty()) {
                    settings.setParamMap(paramMap);
                }
                setPromotionPlugin(settings);
            }
        }
    }

    ArtifactoryServer server = configurator.getArtifactoryServer();

    new PromoteWorkerThread(server, CredentialResolver.getPreferredDeployer(configurator, server), ciUser)
            .start();

    resp.sendRedirect(".");
}

From source file:tile80.tile80.Tile80.java

public Tile80 removeKey(String key) {
    return new Tile80Eager(getPos(), getId(), getTags(), getBehavior(),
            Maps.filterKeys(getKeyspace(), Predicates.equalTo(key)));
}