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:clocker.docker.location.DockerContainerLocation.java

@Override
public int copyTo(final Map<String, ?> props, final InputStream src, final long filesize,
        final String destination) {
    Map<String, ?> nonPortProps = Maps.filterKeys(props, Predicates.not(Predicates.containsPattern("port")));
    boolean entitySsh = Boolean.TRUE.equals(entity.config().get(DockerContainer.DOCKER_USE_SSH));
    boolean dockerSsh = Boolean.TRUE.equals(getOwner().config().get(DockerContainer.DOCKER_USE_SSH));
    if (entitySsh && dockerSsh) {
        return super.copyTo(nonPortProps, src, filesize, destination);
    } else {/*from   w w w  .j  a va2 s  .  c  o m*/
        return copyTo(props, src, destination);
    }
}

From source file:org.apache.ambari.server.api.services.stackadvisor.StackAdvisorBlueprintProcessor.java

/**
 * Remove user defined properties from stack advisor output in case of it applies only on the stack defaults
 *//*  ww w. j  av  a2s. c  om*/
private BlueprintConfigurations filterBlueprintConfig(String configType, BlueprintConfigurations config,
        Map<String, Map<String, String>> userProvidedProperties, ClusterTopology topology) {
    if (topology.getConfigRecommendationStrategy() == ConfigRecommendationStrategy.ONLY_STACK_DEFAULTS_APPLY) {
        if (userProvidedProperties.containsKey(configType)) {
            BlueprintConfigurations newConfig = new BlueprintConfigurations();
            Map<String, String> filteredProps = Maps.filterKeys(config.getProperties(),
                    Predicates.not(Predicates.in(userProvidedProperties.get(configType).keySet())));
            newConfig.setProperties(Maps.newHashMap(filteredProps));

            if (config.getPropertyAttributes() != null) {
                Map<String, ValueAttributesInfo> filteredAttributes = Maps.filterKeys(
                        config.getPropertyAttributes(),
                        Predicates.not(Predicates.in(userProvidedProperties.get(configType).keySet())));
                newConfig.setPropertyAttributes(Maps.newHashMap(filteredAttributes));
            }
            return newConfig;
        }
    }
    return config;
}

From source file:org.apache.brooklyn.core.mgmt.EntityManagementUtils.java

/** Modifies the child so it includes the inessential setup of its parent,
 * for use when unwrapping specific children, but a name or other item may have been set on the parent.
 * See {@link #WRAPPER_APP_MARKER}. */
private static void mergeWrapperParentSpecToChildEntity(EntitySpec<? extends Application> wrapperParent,
        EntitySpec<?> wrappedChild) {
    if (Strings.isNonEmpty(wrapperParent.getDisplayName())) {
        wrappedChild.displayName(wrapperParent.getDisplayName());
    }//  ww w  .  j a v a2  s  .c  om

    wrappedChild.locations(wrapperParent.getLocations());

    if (!wrapperParent.getParameters().isEmpty())
        wrappedChild.parametersReplace(wrapperParent.getParameters());

    // prefer the wrapper ID (change in 2016-01); see notes on the catalogItemIdIfNotNull method
    wrappedChild.catalogItemIdIfNotNull(wrapperParent.getCatalogItemId());

    // NB: this clobber's child config wherever they conflict; might prefer to deeply merge maps etc
    // (or maybe even prevent the merge in these cases; 
    // not sure there is a compelling reason to have config on a pure-wrapper parent)
    Map<ConfigKey<?>, Object> configWithoutWrapperMarker = Maps.filterKeys(wrapperParent.getConfig(),
            Predicates.not(Predicates.<ConfigKey<?>>equalTo(EntityManagementUtils.WRAPPER_APP_MARKER)));
    wrappedChild.configure(configWithoutWrapperMarker);
    wrappedChild.configure(wrapperParent.getFlags());

    // copying tags to all entities may be something the caller wants to control,
    // e.g. if we're adding multiple, the caller might not want to copy the parent
    // (the BrooklynTags.YAML_SPEC tag will include the parents source including siblings),
    // but OTOH they might because otherwise the parent's tags might get lost.
    // also if we are unwrapping multiple registry references we will get the YAML_SPEC for each;
    // putting the parent's tags first however causes the preferred (outer) one to be retrieved first.
    wrappedChild.tagsReplace(MutableList.copyOf(wrapperParent.getTags()).appendAll(wrappedChild.getTags()));
}

From source file:com.mgmtp.perfload.core.client.config.LtProcessModule.java

/**
 * <p>/*from w  w w.j  av  a 2  s  . c  om*/
 * Provides a list of configured local ip addresses. If the client has multiple network
 * interface cards, multiple ip addresses may be configured. The format is
 * {@code ipaddress.<index>}, e. g.:
 * </p>
 * <p>
 * {@code ipaddress.1=192.168.19.121}<br />
 * {@code ipaddress.2=192.168.19.122}<br />
 * {@code ipaddress.3=192.168.19.123}<br />
 * {@code ipaddress.4=192.168.19.124}<br />
 * {@code ipaddress.5=192.168.19.125}
 * </p>
 * 
 * @param properties
 *            the properties
 * @return a list of {@link InetAddress} objects
 */
@Provides
@Singleton
protected List<InetAddress> provideLocalAddresses(final PropertiesMap properties) throws IOException {
    Collection<String> addresses = Maps.filterKeys(properties, new Predicate<String>() {
        @Override
        public boolean apply(final String input) {
            return input.startsWith("ipaddress.");
        }
    }).values();

    List<InetAddress> result = newArrayList();

    for (String addressString : addresses) {
        InetAddress address = InetAddress.getByName(addressString);
        if (!address.isReachable(2000)) { // 2 sec
            throw new IllegalStateException("Configured IP address not reachable: " + address);
        }
        result.add(address);
    }

    return ImmutableList.copyOf(result);
}

From source file:clocker.docker.location.DockerContainerLocation.java

@Override
public int copyTo(final Map<String, ?> props, final InputStream src, final String destination) {
    Map<String, ?> nonPortProps = Maps.filterKeys(props, Predicates.not(Predicates.containsPattern("port")));
    boolean entitySsh = Boolean.TRUE.equals(entity.config().get(DockerContainer.DOCKER_USE_SSH));
    boolean dockerSsh = Boolean.TRUE.equals(getOwner().config().get(DockerContainer.DOCKER_USE_SSH));
    if (entitySsh && dockerSsh) {
        return super.copyTo(nonPortProps, src, destination);
    } else {/*from   ww w  . ja v a  2  s.co  m*/
        try {
            String tmp = Os.mergePaths("/tmp", Joiner.on('-').join(dockerContainer.getId(),
                    Urls.getBasename(destination), Strings.makeRandomId(4)));
            hostMachine.copyTo(nonPortProps, src, tmp);
            copyFile(tmp, destination);
            src.close();
            return 0;
        } catch (IOException ioe) {
            throw Exceptions.propagate(ioe);
        }
    }
}

From source file:clocker.docker.location.DockerContainerLocation.java

@Override
public int copyTo(Map<String, ?> props, File src, String destination) {
    Map<String, ?> nonPortProps = Maps.filterKeys(props, Predicates.not(Predicates.containsPattern("port")));
    boolean entitySsh = Boolean.TRUE.equals(entity.config().get(DockerContainer.DOCKER_USE_SSH));
    boolean dockerSsh = Boolean.TRUE.equals(getOwner().config().get(DockerContainer.DOCKER_USE_SSH));
    if (entitySsh && dockerSsh) {
        return super.copyTo(nonPortProps, src, destination);
    } else {// w  ww  .  j  av a2 s .  c o  m
        String tmp = Os.mergePaths("/tmp", Joiner.on('-').join(dockerContainer.getId(),
                Urls.getBasename(destination), Strings.makeRandomId(4)));
        hostMachine.copyTo(nonPortProps, src, tmp);
        copyFile(tmp, destination);
        return 0;
    }
}

From source file:org.jfrog.teamcity.server.runner.ArtifactoryBuildStartContextProcessor.java

private void readAndAddFileProps(SRunnerContext runnerContext, String... propTypes) {
    Map<String, String> buildParams = runnerContext.getBuildParameters();
    for (String propType : propTypes) {
        String propFilePropKey = propType + BuildInfoConfigProperties.PROP_PROPS_FILE;
        String propertyFilePath = buildParams.get(propFilePropKey);
        if (StringUtils.isNotBlank(propertyFilePath)) {
            File propertiesFile = new File(propertyFilePath);

            if (!propertiesFile.exists()) {
                Loggers.SERVER.error("Ignoring build info properties file at '" + propertyFilePath
                        + "' given from property '" + propFilePropKey + "': file does not exist.");
                return;
            }/* ww w  .jav a2  s.c  o m*/

            if (!propertiesFile.canRead()) {
                Loggers.SERVER.error("Ignoring build info properties file at '" + propertyFilePath
                        + "' given from property '" + propFilePropKey + "': lacking read permissions.");
                return;
            }

            FileInputStream inputStream = null;
            try {
                inputStream = FileUtils.openInputStream(propertiesFile);
                Properties properties = new Properties();
                properties.load(inputStream);
                Map<Object, Object> filteredProperties = Maps.filterKeys(properties, new Predicate<Object>() {
                    public boolean apply(Object input) {
                        String key = (String) input;
                        return key.startsWith(BuildInfoProperties.BUILD_INFO_PROP_PREFIX)
                                || key.startsWith(ClientProperties.PROP_DEPLOY_PARAM_PROP_PREFIX);
                    }
                });
                for (Map.Entry<Object, Object> entry : filteredProperties.entrySet()) {
                    runnerContext.addBuildParameter(propType + entry.getKey(), (String) entry.getValue());
                }
            } catch (IOException ioe) {
                Loggers.SERVER.error("Error while reading build info properties file at '" + propertyFilePath
                        + "' given from property '" + propFilePropKey + "': " + ioe.getMessage());
                Loggers.SERVER.error(ioe);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }
}

From source file:com.android.build.gradle.tasks.PackageAndroidArtifact.java

/**
 * Packages the application incrementally. In case of instant run packaging, this is not a
 * perfectly incremental task as some files are always rewritten even if no change has
 * occurred./*  w w w .  j a  va2s.c  o m*/
 *
 * @param changedDex incremental dex packaging data
 * @param changedJavaResources incremental java resources
 * @param changedAssets incremental assets
 * @param changedAndroidResources incremental Android resource
 * @param changedNLibs incremental native libraries changed
 * @throws IOException failed to package the APK
 */
private void doTask(@NonNull ImmutableMap<RelativeFile, FileStatus> changedDex,
        @NonNull ImmutableMap<RelativeFile, FileStatus> changedJavaResources,
        @NonNull ImmutableMap<RelativeFile, FileStatus> changedAssets,
        @NonNull ImmutableMap<RelativeFile, FileStatus> changedAndroidResources,
        @NonNull ImmutableMap<RelativeFile, FileStatus> changedNLibs) throws IOException {

    ImmutableMap.Builder<RelativeFile, FileStatus> javaResourcesForApk = ImmutableMap.builder();
    javaResourcesForApk.putAll(changedJavaResources);

    Collection<File> instantRunDexBaseFiles;
    switch (dexPackagingPolicy) {
    case INSTANT_RUN_SHARDS_IN_SINGLE_APK:
        /*
         * If we're doing instant run, then we don't want to treat all dex archives
         * as dex archives for packaging. We will package some of the dex files as
         * resources.
         *
         * All dex files in directories whose name contains INSTANT_RUN_PACKAGES_PREFIX
         * are kept in the apk as dex files. All other dex files are placed as
         * resources as defined by makeInstantRunResourcesFromDex.
         */
        instantRunDexBaseFiles = getDexFolders().stream()
                .filter(input -> input.getName().contains(INSTANT_RUN_PACKAGES_PREFIX))
                .collect(Collectors.toSet());
        Iterable<File> nonInstantRunDexBaseFiles = getDexFolders().stream()
                .filter(f -> !instantRunDexBaseFiles.contains(f)).collect(Collectors.toSet());

        ImmutableMap<RelativeFile, FileStatus> newInstantRunResources = makeInstantRunResourcesFromDex(
                nonInstantRunDexBaseFiles);

        @SuppressWarnings("unchecked")
        ImmutableMap<RelativeFile, FileStatus> updatedChangedResources = IncrementalRelativeFileSets
                .union(Sets.newHashSet(changedJavaResources, newInstantRunResources));
        changedJavaResources = updatedChangedResources;

        changedDex = ImmutableMap.copyOf(Maps.filterKeys(changedDex,
                Predicates.compose(Predicates.in(instantRunDexBaseFiles), RelativeFile.EXTRACT_BASE)));

        break;
    case INSTANT_RUN_MULTI_APK:
        instantRunDexBaseFiles = getDexFolders().stream()
                .filter(input -> input.getName().contains(InstantRunSlicer.MAIN_SLICE_NAME))
                .collect(Collectors.toSet());
        changedDex = ImmutableMap.copyOf(Maps.filterKeys(changedDex,
                Predicates.compose(Predicates.in(instantRunDexBaseFiles), RelativeFile.EXTRACT_BASE)));

    case STANDARD:
        break;
    default:
        throw new RuntimeException("Unhandled DexPackagingPolicy : " + getDexPackagingPolicy());
    }

    PrivateKey key;
    X509Certificate certificate;
    boolean v1SigningEnabled;
    boolean v2SigningEnabled;

    try {
        if (signingConfig != null && signingConfig.isSigningReady()) {
            CertificateInfo certificateInfo = KeystoreHelper.getCertificateInfo(signingConfig.getStoreType(),
                    checkNotNull(signingConfig.getStoreFile()), checkNotNull(signingConfig.getStorePassword()),
                    checkNotNull(signingConfig.getKeyPassword()), checkNotNull(signingConfig.getKeyAlias()));
            key = certificateInfo.getKey();
            certificate = certificateInfo.getCertificate();
            v1SigningEnabled = signingConfig.isV1SigningEnabled();
            v2SigningEnabled = signingConfig.isV2SigningEnabled();
        } else {
            key = null;
            certificate = null;
            v1SigningEnabled = false;
            v2SigningEnabled = false;
        }

        ApkCreatorFactory.CreationData creationData = new ApkCreatorFactory.CreationData(getOutputFile(), key,
                certificate, v1SigningEnabled, v2SigningEnabled, null, // BuiltBy
                getBuilder().getCreatedBy(), getMinSdkVersion(),
                PackagingUtils.getNativeLibrariesLibrariesPackagingMode(manifest),
                getNoCompressPredicate()::apply);

        try (IncrementalPackager packager = createPackager(creationData)) {
            packager.updateDex(changedDex);
            packager.updateJavaResources(changedJavaResources);
            packager.updateAssets(changedAssets);
            packager.updateAndroidResources(changedAndroidResources);
            packager.updateNativeLibraries(changedNLibs);
        }
    } catch (PackagerException | KeytoolException e) {
        throw new RuntimeException(e);
    }

    /*
     * Save all used zips in the cache.
     */
    Stream.concat(changedDex.keySet().stream(),
            Stream.concat(changedJavaResources.keySet().stream(),
                    Stream.concat(changedAndroidResources.keySet().stream(), changedNLibs.keySet().stream())))
            .map(RelativeFile::getBase).filter(File::isFile).distinct().forEach((File f) -> {
                try {
                    cacheByPath.add(f);
                } catch (IOException e) {
                    throw new IOExceptionWrapper(e);
                }
            });

    // Mark this APK production, this will eventually be saved when instant-run is enabled.
    // this might get overridden if the apk is signed/aligned.
    try {
        instantRunContext.addChangedFile(instantRunFileType, getOutputFile());
    } catch (IOException e) {
        throw new BuildException(e.getMessage(), e);
    }
}

From source file:com.google.gerrit.server.notedb.ChangeBundle.java

private <K, V> Map<K, V> limitToValidPatchSets(Map<K, V> in, Function<K, PatchSet.Id> func) {
    return Maps.filterKeys(in, Predicates.compose(validPatchSetPredicate(), func));
}

From source file:com.aionemu.gameserver.services.SiegeService.java

/**
 * Updates next state for fortresses//from w w  w.jav  a 2 s  .  c  om
 */
protected void updateFortressNextState() {
    // get current hour and add 1 hour
    Calendar currentHourPlus1 = Calendar.getInstance();
    currentHourPlus1.set(Calendar.MINUTE, 0);
    currentHourPlus1.set(Calendar.SECOND, 0);
    currentHourPlus1.set(Calendar.MILLISECOND, 0);
    currentHourPlus1.add(Calendar.HOUR, 1);

    // filter fortress siege start runnables
    Map<Runnable, JobDetail> siegeStartRunables = CronService.getInstance().getRunnables();
    siegeStartRunables = Maps.filterKeys(siegeStartRunables, new Predicate<Runnable>() {
        @Override
        public boolean apply(@Nullable Runnable runnable) {
            return runnable instanceof SiegeStartRunnable;
        }
    });

    // Create map FortressId-To-AllTriggers
    Map<Integer, List<Trigger>> siegeIdToStartTriggers = Maps.newHashMap();
    for (Map.Entry<Runnable, JobDetail> entry : siegeStartRunables.entrySet()) {
        SiegeStartRunnable fssr = (SiegeStartRunnable) entry.getKey();

        List<Trigger> storage = siegeIdToStartTriggers.get(fssr.getLocationId());
        if (storage == null) {
            storage = Lists.newArrayList();
            siegeIdToStartTriggers.put(fssr.getLocationId(), storage);
        }
        storage.addAll(CronService.getInstance().getJobTriggers(entry.getValue()));
    }

    // update each fortress next state
    for (Map.Entry<Integer, List<Trigger>> entry : siegeIdToStartTriggers.entrySet()) {
        List<Date> nextFireDates = Lists.newArrayListWithCapacity(entry.getValue().size());
        for (Trigger trigger : entry.getValue()) {
            nextFireDates.add(trigger.getNextFireTime());
        }
        Collections.sort(nextFireDates);

        // clear non-required times
        Date nextSiegeDate = nextFireDates.get(0);
        Calendar siegeStartHour = Calendar.getInstance();
        siegeStartHour.setTime(nextSiegeDate);
        siegeStartHour.set(Calendar.MINUTE, 0);
        siegeStartHour.set(Calendar.SECOND, 0);
        siegeStartHour.set(Calendar.MILLISECOND, 0);

        // update fortress state that will be valid in 1 h
        SiegeLocation fortress = getSiegeLocation(entry.getKey());
        // check if siege duration is > than 1 Hour
        Calendar siegeCalendar = Calendar.getInstance();
        siegeCalendar.set(Calendar.MINUTE, 0);
        siegeCalendar.set(Calendar.SECOND, 0);
        siegeCalendar.set(Calendar.MILLISECOND, 0);
        siegeCalendar.add(Calendar.HOUR, 0);
        siegeCalendar.add(Calendar.SECOND, getRemainingSiegeTimeInSeconds(fortress.getLocationId()));

        if (fortress instanceof SourceLocation) {
            siegeStartHour.add(Calendar.HOUR, 1);
        }

        if (currentHourPlus1.getTimeInMillis() == siegeStartHour.getTimeInMillis()
                || siegeCalendar.getTimeInMillis() > currentHourPlus1.getTimeInMillis()) {
            fortress.setNextState(SiegeLocation.STATE_VULNERABLE);
        } else {
            fortress.setNextState(SiegeLocation.STATE_INVULNERABLE);
        }
    }
}