Example usage for com.google.common.base Predicates containsPattern

List of usage examples for com.google.common.base Predicates containsPattern

Introduction

In this page you can find the example usage for com.google.common.base Predicates containsPattern.

Prototype

@GwtIncompatible(value = "java.util.regex.Pattern")
public static Predicate<CharSequence> containsPattern(String pattern) 

Source Link

Document

Returns a predicate that evaluates to true if the CharSequence being tested contains any match for the given regular expression pattern.

Usage

From source file:grkvlt.Ec2CleanUp.java

/**
 * Delete all matching {@link KeyPair}s.
 *///from   ww  w  . j  av a 2s  . com
public void deleteKeyPairs(KeyPairClient keyPairApi) throws Exception {
    Set<KeyPair> keys = keyPairApi.describeKeyPairsInRegion(region);
    Iterable<String> filtered = Iterables.filter(Iterables.transform(keys, new Function<KeyPair, String>() {
        @Override
        public String apply(@Nullable KeyPair input) {
            return input.getKeyName();
        }
    }), Predicates.containsPattern("^" + regexp + "$"));
    LOG.info("Found {} matching KeyPairs", Iterables.size(filtered));
    if (!check) {
        int deleted = 0;
        for (String name : filtered) {
            try {
                keyPairApi.deleteKeyPairInRegion(region, name);
                deleted++;
            } catch (Exception e) {
                if (e.getMessage() != null && e.getMessage().contains("RequestLimitExceeded")) {
                    Thread.sleep(1000l); // Avoid triggering rate-limiter again
                }
                LOG.warn("Error deleting KeyPair '{}': {}", name, e.getMessage());
            }
        }
        LOG.info("Deleted {} KeyPairs", deleted);
    }
}

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

@Override
public BlobStoreContext newBlobStoreContext(Location location) {
    String rawProvider = checkNotNull(location.getConfig(LocationConfigKeys.CLOUD_PROVIDER),
            "provider must not be null");
    String provider = DeserializingJcloudsRenamesProvider.INSTANCE.applyJcloudsRenames(rawProvider);
    String identity = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_IDENTITY),
            "identity must not be null");
    String credential = checkNotNull(location.getConfig(LocationConfigKeys.ACCESS_CREDENTIAL),
            "credential must not be null");
    String endpoint = location.getConfig(CloudLocationConfig.CLOUD_ENDPOINT);

    Properties overrides = new Properties();
    // * Java 7,8 bug workaround - sockets closed by GC break the internal bookkeeping
    //   of HttpUrlConnection, leading to invalid handling of the "HTTP/1.1 100 Continue"
    //   response. Coupled with a bug when using SSL sockets reads will block
    //   indefinitely even though a read timeout is explicitly set.
    // * Java 6 ignores the header anyways as it is included in its restricted headers black list.
    // * Also there's a bug in SL object store which still expects Content-Length bytes
    //   even when it responds with a 408 timeout response, leading to incorrectly
    //   interpreting the next request (triggered by above problem).
    overrides.setProperty(Constants.PROPERTY_STRIP_EXPECT_HEADER, "true");

    // Add extra jclouds-specific configuration
    Map<String, Object> extra = Maps.filterKeys(((LocationInternal) location).config().getBag().getAllConfig(),
            Predicates.containsPattern("^jclouds\\."));
    if (extra.size() > 0) {
        LOG.debug("Configuring custom jclouds property overrides for {}: {}", provider,
                Sanitizer.sanitize(extra));
    }// w w w  .j  a  v  a 2s  . co m
    overrides.putAll(Maps.filterValues(extra, Predicates.notNull()));

    ContextBuilder contextBuilder = ContextBuilder.newBuilder(provider).credentials(identity, credential);
    contextBuilder.modules(MutableList.copyOf(getCommonModules()));
    if (!org.apache.brooklyn.util.text.Strings.isBlank(endpoint)) {
        contextBuilder.endpoint(endpoint);
    }
    contextBuilder.overrides(overrides);
    BlobStoreContext context = contextBuilder.buildView(BlobStoreContext.class);
    return context;
}

From source file: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(ACCESS_IDENTITY), "identity must not be null");
    String credential = checkNotNull(conf.get(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 w w. j  a  v a 2s .  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&
             */
        }
    }

    // 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: " + Entities.sanitize(extra));
    }
    properties.putAll(extra);

    String endpoint = conf.get(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 "
                    + Entities.sanitize(properties));
            return result;
        }
        LOG.debug("jclouds ComputeService cache miss for compute service, creating, for "
                + Entities.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 "
                        + Entities.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 "
                    + Entities.sanitize(properties));
            cachedComputeServices.put(cacheKey, computeService);
        }
    }
    return computeService;
}

From source file:com.eucalyptus.util.Exceptions.java

private static Predicate<String> makeSteFilter(final List<String> patterns) {
    Predicate<String> filter = Predicates.alwaysTrue();
    for (String f : patterns) {
        filter = Predicates.or(filter, Predicates.containsPattern(f));
    }/*ww w.jav  a 2  s  .co  m*/
    return filter;
}

From source file:org.apache.brooklyn.util.text.StringPredicates.java

public static Predicate<CharSequence> containsRegex(final String regex) {
    // "Pattern" ... what a bad name :)
    return Predicates.containsPattern(regex);
}

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");
            /*//w  w  w. j a  v a 2  s  .c  o m
             * 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:grkvlt.Ec2CleanUp.java

/**
 * Delete all matching {@link SecurityGroup}s.
 */// w  w  w  .  jav a  2  s  .  co  m
public void deleteSecurityGroups(SecurityGroupClient securityGroupApi) throws Exception {
    Set<SecurityGroup> groups = securityGroupApi.describeSecurityGroupsInRegion(region);
    Iterable<String> filtered = Iterables
            .filter(Iterables.transform(groups, new Function<SecurityGroup, String>() {
                @Override
                public String apply(@Nullable SecurityGroup input) {
                    return input.getName();
                }
            }), Predicates.containsPattern("^" + regexp + "$"));
    LOG.info("Found {} matching SecurityGroups", Iterables.size(filtered));
    if (!check) {
        int deleted = 0;
        for (String name : filtered) {
            try {
                securityGroupApi.deleteSecurityGroupInRegion(region, name);
                deleted++;
            } catch (Exception e) {
                if (e.getMessage() != null && e.getMessage().contains("RequestLimitExceeded")) {
                    Thread.sleep(1000l); // Avoid triggering rate-limiter again
                }
                LOG.warn("Error deleting SecurityGroup '{}': {}", name, e.getMessage());
            }
        }
        LOG.info("Deleted {} SecurityGroups", deleted);
    }
}

From source file:brooklyn.entity.waratek.cloudvm.JavaVirtualMachineSshDriver.java

@Override
public Map<String, String> getCustomJavaSystemProperties() {
    MutableMap.Builder<String, String> builder = MutableMap.<String, String>builder()
            .putAll(super.getCustomJavaSystemProperties());
    if (installed.get()) {
        // Java options needed for launch only
        builder.put("com.waratek.jvm.name", getEntity().getAttribute(JavaVirtualMachine.JVM_NAME));
        builder.put("com.waratek.rootdir", getRootDirectory());
        // TODO JMXRMI debugging
        // builder.put("sun.rmi.transport.logLevel", "VERBOSE");
        // builder.put("sun.rmi.transport.tcp.logLevel", "VERBOSE");
        // builder.put("sun.rmi.server.logLevel", "VERBOSE");
        // builder.put("sun.rmi.client.logCalls", "true");
        if (getEntity().getConfig(JavaVirtualMachine.DEBUG)) {
            builder.put("com.waratek.debug.log", "guest.log");
            builder.put("com.waratek.debug.log_level", "debug");
        }/*from  w  ww  .j  a va 2s  . c  o m*/
        if (getEntity().getConfig(JavaVirtualMachine.SSH_ADMIN_ENABLE)) {
            builder.put("com.waratek.ssh.server", "on");
            builder.put("com.waratek.ssh.port",
                    getEntity().getAttribute(JavaVirtualMachine.SSH_PORT).toString());
            builder.put("com.waratek.ssh.ip", getMachine().getAddress().getHostAddress());
        } else {
            builder.put("com.waratek.ssh.server", "off");
        }
        if (getEntity().getConfig(JavaVirtualMachine.HTTP_ADMIN_ENABLE)) {
            // TODO extra properties and configuration required?
            builder.put("com.waratek.jmxhttp.jolokia",
                    "port=" + getEntity().getAttribute(JavaVirtualMachine.HTTP_PORT).toString());
        }
        String javaagent = Iterables.find(super.getJmxJavaConfigOptions(),
                Predicates.containsPattern("javaagent"));
        builder.put("com.waratek.javaagent", javaagent);

    }
    return builder.build();
}

From source file:com.cognifide.aet.vs.metadata.MetadataDAOMongoDBImpl.java

@Override
public Collection<DBKey> getProjects(String company) {
    final Collection<DBKey> result = new ArrayList<>();

    final Collection<String> databaseNames;
    if (!StringUtils.isBlank(company)) {
        databaseNames = Collections2.filter(client.getAetsDBNames(), Predicates.containsPattern("^" + company));
    } else {/*from  www. j  av a 2 s .co  m*/
        databaseNames = client.getAetsDBNames();
    }

    for (String dbName : databaseNames) {
        String[] companyAndProject = StringUtils.split(dbName, MongoDBClient.DB_NAME_SEPARATOR);
        result.add(new SimpleDBKey(companyAndProject[0], companyAndProject[1]));
    }
    return result;
}

From source file:org.nickelproject.util.testUtil.ClasspathUtil.java

private static Iterable<String> getClassPath() {
    // Removes some paths that eclipse adds during testing.
    return Iterables.filter(Lists.newArrayList(System.getProperty("java.class.path").split(File.pathSeparator)),
            Predicates.not(Predicates.containsPattern(Pattern.quote(kEclipseFilter))));
}