Example usage for java.util Collections unmodifiableSet

List of usage examples for java.util Collections unmodifiableSet

Introduction

In this page you can find the example usage for java.util Collections unmodifiableSet.

Prototype

public static <T> Set<T> unmodifiableSet(Set<? extends T> s) 

Source Link

Document

Returns an unmodifiable view of the specified set.

Usage

From source file:com.rackspacecloud.client.service_registry.clients.BaseClient.java

protected <T extends HasId> Iterator<T> getListIterator(final Class<T> clazz, final String path,
        final MethodOptions methodOptions, final HttpRequestBase method, final boolean parseAsJson,
        final Type type) {
    return new Iterator<T>() {

        // means we are done fetching, not done iterating.
        private boolean exhausted = false;

        private List<T> curValues;
        private String nextMarker = methodOptions.getMarker();

        // NOTE: The groundwork has been laid to let methodOptions.getLimit() become a limit for the number of total
        //       results returned. We can use any value we want for the page size now.  As for now,
        //       methodOptions.getLimit() refers to the page size, which may not be intuitive.
        // these are all the keys we are interested in when paging.
        private Set<String> constantPagingParams = Collections.unmodifiableSet(new HashSet<String>() {
            {/*from w w  w. j a v  a  2s . com*/
                addAll(methodOptions.getNonNullKeys());
                remove(MethodOptions.PaginationOptions.Marker.toString());
            }
        });

        public boolean hasNext() {
            if (this.curValues == null && !this.exhausted) {
                this.curValues = getNextPage();
            }
            return this.curValues != null && this.curValues.size() > 0;
        }

        public T next() {
            T item = this.curValues.remove(0);
            if (this.curValues.size() == 0 && !this.exhausted) {
                this.curValues = this.getNextPage();
            }
            return item;
        }

        public void remove() {
            throw new RuntimeException("Not implemented");
        }

        private List<T> getNextPage() {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // backfill everything from options into params except "marker". We handle that manually.
            for (String key : constantPagingParams) {
                params.add(new BasicNameValuePair(key, methodOptions.get(key)));
            }

            if (this.nextMarker != null) {
                params.add(new BasicNameValuePair("marker", this.nextMarker));
            }

            try {
                ClientResponse response = performRequest(path, params, method, parseAsJson, type);
                ContainerMeta<T> container = (ContainerMeta<T>) response.getBody();
                List<T> values = container.getValues();
                if (container.getNextMarker() == null) {
                    this.exhausted = true;
                } else {
                    nextMarker = container.getNextMarker();
                }

                return values;
            } catch (Exception ex) {
                // be careful about throwing, you're in an iterator.
                this.exhausted = true;
                return new ArrayList<T>();
            }

        }
    };
}

From source file:com.redhat.rhn.domain.org.Org.java

/**
 * Gets the roles assigned to this Org. The Map returned from this method
 * has been decorated with a call to//w  ww .ja  v  a  2 s  .c  om
 * {@link java.util.Collections#unmodifiableMap} in order to enforce the
 * rule that roles are not changeable during runtime.
 * @return Set of Roles associated with this Org
 */
public Set<Role> getRoles() {
    Set<Role> orgRoles = new HashSet<Role>();
    for (Iterator<UserGroup> i = usergroups.iterator(); i.hasNext();) {
        UserGroup ug = i.next();
        orgRoles.add(ug.getRole());
    }
    return Collections.unmodifiableSet(orgRoles);
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.LdapUserServiceImpl.java

@Override
public Set<BasicUser> searchForUserByEmail(String email) {
    email = StringUtils.trimToNull(email);
    if (email == null) {
        return Collections.emptySet();
    }/*from w  ww. j a v a  2 s  .  c om*/

    final AndFilter andFilter = createBaseFilter();
    andFilter.and(new LikeFilter(mailAttributeName, email + "*"));

    final String searchFilter = andFilter.encode();
    @SuppressWarnings("unchecked")
    final List<BasicUser> results = ldapOperations.search("", searchFilter, basicUserAttributeMapper);

    return Collections.unmodifiableSet(new LinkedHashSet<BasicUser>(results));
}

From source file:com.facebook.AccessToken.java

/**
 * Creates a new AccessToken using the supplied information from a previously-obtained access
 * token (for instance, from an already-cached access token obtained prior to integration with
 * the Facebook SDK). Note that the caller is asserting that all parameters provided are correct
 * with respect to the access token string; no validation is done to verify they are correct.
 *
 * @param accessToken         the access token string obtained from Facebook
 * @param applicationId       the ID of the Facebook Application associated with this access
 *                            token/*from w w w .  j a va  2  s. co m*/
 * @param userId              the id of the user
 * @param permissions         the permissions that were requested when the token was obtained
 *                            (or when it was last reauthorized); may be null if permission set
 *                            is unknown
 * @param declinedPermissions the permissions that were declined when the token was obtained;
 *                            may be null if permission set is unknown
 * @param accessTokenSource   an enum indicating how the token was originally obtained (in most
 *                            cases, this will be either AccessTokenSource.FACEBOOK_APPLICATION
 *                            or AccessTokenSource.WEB_VIEW); if null, FACEBOOK_APPLICATION is
 *                            assumed.
 * @param expirationTime      the expiration date associated with the token; if null, an
 *                            infinite expiration time is assumed (but will become correct when
 *                            the token is refreshed)
 * @param lastRefreshTime     the last time the token was refreshed (or when it was first
 *                            obtained); if null, the current time is used.
 */
public AccessToken(final String accessToken, final String applicationId, final String userId,
        @Nullable final Collection<String> permissions, @Nullable final Collection<String> declinedPermissions,
        @Nullable final AccessTokenSource accessTokenSource, @Nullable final Date expirationTime,
        @Nullable final Date lastRefreshTime) {
    Validate.notNullOrEmpty(accessToken, "accessToken");
    Validate.notNullOrEmpty(applicationId, "applicationId");
    Validate.notNullOrEmpty(userId, "userId");

    this.expires = expirationTime != null ? expirationTime : DEFAULT_EXPIRATION_TIME;
    this.permissions = Collections
            .unmodifiableSet(permissions != null ? new HashSet<String>(permissions) : new HashSet<String>());
    this.declinedPermissions = Collections.unmodifiableSet(
            declinedPermissions != null ? new HashSet<String>(declinedPermissions) : new HashSet<String>());
    this.token = accessToken;
    this.source = accessTokenSource != null ? accessTokenSource : DEFAULT_ACCESS_TOKEN_SOURCE;
    this.lastRefresh = lastRefreshTime != null ? lastRefreshTime : DEFAULT_LAST_REFRESH_TIME;
    this.applicationId = applicationId;
    this.userId = userId;
}

From source file:com.valygard.aohruthless.framework.ArenaTemplate.java

@Override
public Set<Player> getPlayersInArena() {
    return Collections.unmodifiableSet(arenaPlayers);
}

From source file:com.datamelt.nifi.processors.SplitToAttribute.java

@Override
public void init(final ProcessorInitializationContext context) {
    List<PropertyDescriptor> properties = new ArrayList<>();
    properties.add(ATTRIBUTE_PREFIX);//from  www. ja v  a  2  s .  c  om
    properties.add(FIELD_SEPARATOR);
    properties.add(FIELD_NUMBER_NUMBERFORMAT);
    this.properties = Collections.unmodifiableList(properties);

    Set<Relationship> relationships = new HashSet<>();
    relationships.add(SUCCESS);
    this.relationships = Collections.unmodifiableSet(relationships);
}

From source file:eu.ggnet.dwoss.receipt.unit.UnitModel.java

public Set<Action> getActions() {
    return Collections.unmodifiableSet(actions);
}

From source file:com.indeed.imhotep.web.ImhotepMetadataCache.java

public Set<String> getKeywordAnalyzerWhitelist(String dataset) {
    if (!datasetToKeywordAnaylzerWhitelist.containsKey(dataset)) {
        return Collections.emptySet();
    }//from   ww  w.  j a v  a 2 s .  c o  m
    return Collections.unmodifiableSet(datasetToKeywordAnaylzerWhitelist.get(dataset));
}

From source file:de.flashpixx.rrd_antlr4.TestCLanguageLabels.java

/**
 * test-case all resource strings/*from  w w w .j a v a  2 s . c  om*/
 *
 * @throws IOException throws on io errors
 */
@Test
public void testResourceString() throws IOException {
    assumeTrue("no languages are defined for checking", !LANGUAGEPROPERY.isEmpty());

    final Set<String> l_ignoredlabel = new HashSet<>();

    // --- parse source and get label definition
    final Set<String> l_label = Collections.unmodifiableSet(Files.walk(Paths.get(SEARCHPATH))
            .filter(Files::isRegularFile).filter(i -> i.toString().endsWith(".java")).flatMap(i -> {
                try {
                    final CJavaVistor l_parser = new CJavaVistor();
                    l_parser.visit(JavaParser.parse(new FileInputStream(i.toFile())), null);
                    return l_parser.labels().stream();
                } catch (final IOException l_excpetion) {
                    assertTrue(MessageFormat.format("io error on file [{0}]: {1}", i, l_excpetion.getMessage()),
                            false);
                    return Stream.<String>empty();
                } catch (final ParseException l_exception) {
                    // add label build by class path to the ignore list
                    l_ignoredlabel.add(i.toAbsolutePath().toString()
                            // remove path to class directory
                            .replace(FileSystems.getDefault().provider().getPath(SEARCHPATH).toAbsolutePath()
                                    .toString(), "")
                            // string starts with path separator
                            .substring(1)
                            // remove file extension
                            .replace(".java", "")
                            // replace separators with dots
                            .replace("/", CLASSSEPARATOR)
                            // convert to lower-case
                            .toLowerCase()
                            // remove package-root name
                            .replace(CCommon.PACKAGEROOT + CLASSSEPARATOR, ""));

                    System.err.println(MessageFormat.format("parsing error on file [{0}]:\n{1}", i,
                            l_exception.getMessage()));
                    return Stream.<String>empty();
                }
            }).collect(Collectors.toSet()));

    // --- check of any label is found
    assertFalse("translation labels are empty, check naming of translation method", l_label.isEmpty());

    // --- check label towards the property definition
    if (l_ignoredlabel.size() > 0)
        System.err.println(MessageFormat.format(
                "labels that starts with {0} are ignored, because parsing errors are occurred",
                l_ignoredlabel));

    LANGUAGEPROPERY.entrySet().forEach(i -> {
        try {
            final Properties l_property = new Properties();
            l_property.load(new FileInputStream(new File(i.getValue())));

            final Set<String> l_parseditems = new HashSet<>(l_label);
            final Set<String> l_propertyitems = l_property.keySet().parallelStream().map(Object::toString)
                    .collect(Collectors.toSet());

            // --- check if all property items are within the parsed labels
            l_parseditems.removeAll(l_propertyitems);
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the language file:\n{2}",
                    i.getKey(), l_parseditems.size(), StringUtils.join(l_parseditems, ", ")),
                    l_parseditems.isEmpty());

            // --- check if all parsed labels within the property item and remove ignored labels
            l_propertyitems.removeAll(l_label);
            final Set<String> l_ignoredpropertyitems = l_propertyitems.parallelStream()
                    .filter(j -> l_ignoredlabel.parallelStream().map(j::startsWith).allMatch(l -> false))
                    .collect(Collectors.toSet());
            assertTrue(MessageFormat.format(
                    "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the source code:\n{2}",
                    i.getKey(), l_ignoredpropertyitems.size(), StringUtils.join(l_ignoredpropertyitems, ", ")),
                    l_ignoredpropertyitems.isEmpty());
        } catch (final IOException l_exception) {
            assertTrue(MessageFormat.format("io exception: {0}", l_exception.getMessage()), false);
        }
    });
}

From source file:com.valygard.aohruthless.framework.ArenaTemplate.java

@Override
public Set<Player> getPlayersInLobby() {
    return Collections.unmodifiableSet(lobbyPlayers);
}