Example usage for java.util Collections emptySet

List of usage examples for java.util Collections emptySet

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public static final <T> Set<T> emptySet() 

Source Link

Document

Returns an empty set (immutable).

Usage

From source file:io.gravitee.repository.redis.management.internal.impl.ApplicationRedisRepositoryImpl.java

@Override
public Set<RedisApplication> findByName(final String partialName) {

    List<String> matchedNames = redisTemplate.execute(new RedisCallback<List<String>>() {
        @Override//from  w ww . ja  v a 2 s.com
        public List<String> doInRedis(RedisConnection redisConnection) throws DataAccessException {
            ScanOptions options = ScanOptions.scanOptions()
                    .match(REDIS_KEY + ":search-by:name:*" + partialName.toUpperCase() + "*").build();
            Cursor<byte[]> cursor = redisConnection.scan(options);
            List<String> result = new ArrayList<>();
            if (cursor != null) {
                while (cursor.hasNext()) {
                    result.add(new String(cursor.next()));
                }
            }
            return result;
        }
    });

    if (matchedNames == null || matchedNames.isEmpty()) {
        return Collections.emptySet();
    }
    Set<Object> applicationIds = new HashSet<>();
    matchedNames.forEach(matchedName -> applicationIds.addAll(redisTemplate.opsForSet().members(matchedName)));

    return find(applicationIds.stream().map(Object::toString).collect(Collectors.toList()));
}

From source file:com.devicehive.resource.impl.DeviceCommandResourceImpl.java

private void poll(final long timeout, final String deviceGuidsCsv, final String namesCsv,
        final String timestamp, final AsyncResponse asyncResponse) throws InterruptedException {
    final HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();//from   w  ww  . j  a  v  a2 s  .  com

    final Date ts = TimestampQueryParamParser
            .parse(timestamp == null ? timestampService.getDateAsString() : timestamp);

    final Response response = ResponseFactory.response(Response.Status.OK, Collections.emptyList(),
            JsonPolicyDef.Policy.COMMAND_LISTED);

    asyncResponse.setTimeoutHandler(asyncRes -> asyncRes.resume(response));

    Set<String> availableDevices;
    if (deviceGuidsCsv == null) {
        availableDevices = deviceService.findByGuidWithPermissionsCheck(Collections.emptyList(), principal)
                .stream().map(DeviceVO::getGuid).collect(Collectors.toSet());

    } else {
        availableDevices = Optional.ofNullable(StringUtils.split(deviceGuidsCsv, ',')).map(Arrays::asList)
                .map(list -> deviceService.findByGuidWithPermissionsCheck(list, principal))
                .map(list -> list.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()))
                .orElse(Collections.emptySet());
    }

    Set<String> names = Optional.ofNullable(StringUtils.split(namesCsv, ',')).map(Arrays::asList)
            .map(list -> list.stream().collect(Collectors.toSet())).orElse(Collections.emptySet());

    BiConsumer<DeviceCommand, String> callback = (command, subscriptionId) -> {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(ResponseFactory.response(Response.Status.OK, Collections.singleton(command),
                    Policy.COMMAND_LISTED));
        }
    };

    if (!availableDevices.isEmpty()) {
        Pair<String, CompletableFuture<List<DeviceCommand>>> pair = commandService
                .sendSubscribeRequest(availableDevices, names, ts, callback);
        pair.getRight().thenAccept(collection -> {
            if (!collection.isEmpty() && !asyncResponse.isDone()) {
                asyncResponse.resume(
                        ResponseFactory.response(Response.Status.OK, collection, Policy.COMMAND_LISTED));
            }

            if (timeout == 0) {
                asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause
                // the thread to suspend indefinitely, see AsyncResponse docs
            } else {
                asyncResponse.setTimeout(timeout, TimeUnit.SECONDS);
            }
        });

        asyncResponse.register(new CompletionCallback() {
            @Override
            public void onComplete(Throwable throwable) {
                commandService.sendUnsubscribeRequest(pair.getLeft(), null);
            }
        });
    } else {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(response);
        }
    }

}

From source file:com.playhaven.android.data.DataCollectionField.java

/**
 * Unavailable in <11, so copied in. Difference is that names are not re-encoded in UTF-8. 
 * // www .  j  a  v a2  s .  c  om
 * Returns a set of the unique names of all query parameters. Iterating
 * over the set will return the names in order of their first occurrence.
 *
 * @throws UnsupportedOperationException if this isn't a hierarchical URI
 *
 * @return a set of decoded names
 */
public static Set<String> getQueryParameterNames(Uri uri) {

    String query = uri.getEncodedQuery();
    if (query == null) {
        return Collections.emptySet();
    }

    Set<String> names = new LinkedHashSet<String>();
    int start = 0;
    do {
        int next = query.indexOf('&', start);
        int end = (next == -1) ? query.length() : next;

        int separator = query.indexOf('=', start);
        if (separator > end || separator == -1) {
            separator = end;
        }

        String name = query.substring(start, separator);
        names.add(name);

        // Move start to end of name.
        start = end + 1;
    } while (start < query.length());

    return Collections.unmodifiableSet(names);
}

From source file:mitm.application.djigzo.impl.hibernate.UserHibernate.java

@Override
public Set<X509Certificate> getAutoSelectEncryptionCertificates() throws HierarchicalPropertiesException {
    /*//from  w w w  .  j  av  a2  s  .  c o  m
     * Only auto select certificates if enabled
     */
    if (getUserPreferences().getProperties().isAutoSelectEncryptionCerts()) {
        return encryptionCertificateSelector.getMatchingCertificates(getEmail());
    }

    return Collections.emptySet();
}

From source file:com.github.gaoyangthu.core.hbase.HbaseSynchronizationManager.java

/**
 * Returns the bound tables (by name)./*from ww  w .  j  a va  2 s  .c  o  m*/
 * 
 * @return names of bound tables
 */
public static Set<String> getTableNames() {
    Map<String, HTableInterface> map = resources.get();
    if (map != null && !map.isEmpty()) {
        return Collections.unmodifiableSet(map.keySet());
    }
    return Collections.emptySet();
}

From source file:info.magnolia.ui.workbench.tree.HierarchicalJcrContainer.java

@Override
public Collection<JcrItemId> rootItemIds() {
    try {/*from  ww  w  . j a  v  a 2  s . c  o  m*/
        return createContainerIds(getRootItemIds());
    } catch (RepositoryException e) {
        handleRepositoryException(log, "Cannot retrieve root item id's", e);
        return Collections.emptySet();
    }
}

From source file:org.jasig.springframework.security.portlet.authentication.PortletXmlMappableAttributesRetrieverTest.java

@Test
public void testOneNoAttributes() throws Exception {
    final PortletXmlMappableAttributesRetriever portletXmlMappableAttributesRetriever = new PortletXmlMappableAttributesRetriever();

    final ResourceLoader resourceLoader = mock(ResourceLoader.class);
    when(resourceLoader.getResource("/WEB-INF/portlet.xml")).thenReturn(new ClassPathResource(
            "/org/jasig/springframework/security/portlet/authentication/portlet_1_no_attributes.xml"));
    portletXmlMappableAttributesRetriever.setResourceLoader(resourceLoader);

    portletXmlMappableAttributesRetriever.afterPropertiesSet();

    final Set<String> mappableAttributes = portletXmlMappableAttributesRetriever.getMappableAttributes();

    assertEquals(Collections.emptySet(), mappableAttributes);
}

From source file:com.scvngr.levelup.core.model.util.JsonUtilsTest.java

/**
 * Tests {@link com.scvngr.levelup.core.model.util.JsonUtils#optStringSet(org.json.JSONObject, String)}.
 *
 * @throws org.json.JSONException if there's a parse error.
 *///  w ww. j a v  a  2  s .c  o  m
public void testStringSet() throws JSONException {
    final JSONObject object1 = new JSONObject("{ 'test': null }");

    Set<String> strings = JsonUtils.optStringSet(object1, "test");

    assertNull(strings);

    final JSONObject object2 = new JSONObject("{ 'test': ['foo','bar', 'baz'] }");

    strings = JsonUtils.optStringSet(object2, "test");

    assertNotNull(strings);
    assertEquals(new HashSet<String>(Arrays.asList("foo", "bar", "baz")), strings);

    assertEquals(new HashSet<String>(Arrays.asList("foo")),
            JsonUtils.optStringSet(new JSONObject("{ 'test': ['foo'] }"), "test"));

    assertEquals(new HashSet<String>(Arrays.asList("")),
            JsonUtils.optStringSet(new JSONObject("{ 'test': [''] }"), "test"));

    assertEquals(new HashSet<String>(Arrays.asList("foo")),
            JsonUtils.optStringSet(new JSONObject("{ 'test': ['foo','foo','foo'] }"), "test"));

    assertEquals(Collections.emptySet(), JsonUtils.optStringSet(new JSONObject("{ 'test': [] }"), "test"));
}

From source file:grails.plugin.freemarker.AbstractTagLibAwareConfigurer.java

protected void reconfigure(Configuration configuration) {
    // TODO: Reconfiguration of reloaded tags
    if (configuration != null) {
        synchronized (configuration) {
            Boolean isConfigured = (Boolean) configuration.getCustomAttribute(CONFIGURED_ATTRIBUTE_NAME);
            if (isConfigured == null || isConfigured == false) {
                try {
                    ApplicationContext springContext = grailsApplication.getMainContext();

                    Map<String, Map<String, TemplateModel>> sharedVars = new LinkedHashMap<String, Map<String, TemplateModel>>();
                    GrailsClass[] tagLibClasses = grailsApplication.getArtefacts(TagLibArtefactHandler.TYPE);

                    for (GrailsClass grailsClass : tagLibClasses) {
                        GrailsTagLibClass tagLibClass = (GrailsTagLibClass) grailsClass;
                        String namespace = tagLibClass.getNamespace();

                        if (log.isDebugEnabled()) {
                            log.debug("reconfigure(): Exposing tag '" + namespace + "' ("
                                    + tagLibClass.getFullName() + ")");
                        }//from  ww  w . j a v a2s  .c om

                        GroovyObject tagLibInstance = getTagLibInstance(springContext,
                                tagLibClass.getFullName());
                        Map<String, TemplateModel> sharedVar = sharedVars.get(namespace);
                        if (sharedVar == null) {
                            sharedVar = new LinkedHashMap<String, TemplateModel>();
                            sharedVars.put(namespace, sharedVar);
                        }

                        Set<String> tagNamesWithReturn = tagLibClass.getTagNamesThatReturnObject();
                        if (tagNamesWithReturn == null) {
                            tagNamesWithReturn = Collections.emptySet();
                        } else {
                            if (log.isDebugEnabled())
                                log.debug("found TagNamesThatReturnObject" + tagNamesWithReturn);
                        }

                        for (String tagName : tagLibClass.getTagNames()) {
                            if (log.isDebugEnabled())
                                log.debug("reconfigure(): tag " + tagName);
                            if (tagName.equals("grailsApplication")) {
                                continue;
                            }
                            Object tagInstanceObject = null;
                            try {
                                tagInstanceObject = tagLibInstance.getProperty(tagName);
                            } catch (IllegalStateException e) {
                                //Workaround for properties exposed as tags and dependent of RequestAttributes
                                log.debug("reconfigure() error on " + tagName, e);
                            }
                            if (tagInstanceObject != null && tagInstanceObject instanceof Closure) {
                                Closure tagInstance = (Closure) tagInstanceObject;
                                sharedVar.put(tagName,
                                        new TagLibToDirectiveAndFunction(namespace, tagLibInstance, tagName,
                                                tagInstance, tagNamesWithReturn.contains(tagName)));
                            }
                        }
                    }

                    for (Map.Entry<String, Map<String, TemplateModel>> entry : sharedVars.entrySet()) {
                        // if (log.isDebugEnabled()) log.debug("reconfigure(): @" + entry.getKey()+ ". = " + entry.getValue());
                        configuration.setSharedVariable(entry.getKey(), entry.getValue());
                    }

                    configuration.setCustomAttribute(AbstractTagLibAwareConfigurer.CONFIGURED_ATTRIBUTE_NAME,
                            Boolean.TRUE);
                } catch (TemplateModelException e) {
                    throw new RuntimeException(e);
                }
            } //end if
        } //end snchronized
    } //end if
}

From source file:com.haulmont.cuba.gui.dynamicattributes.DynamicAttributesGuiTools.java

protected Set<Class> collectEntityClassesWithDynamicAttributes(@Nullable View view) {
    if (view == null) {
        return Collections.emptySet();
    }/*from w  w w. j  av a2s. c om*/

    DynamicAttributes dynamicAttributes = AppBeans.get(DynamicAttributes.class);
    Metadata metadata = AppBeans.get(Metadata.class);
    return collectEntityClasses(view, new HashSet<>()).stream()
            .filter(BaseGenericIdEntity.class::isAssignableFrom).filter(aClass -> !dynamicAttributes
                    .getAttributesForMetaClass(metadata.getClassNN(aClass)).isEmpty())
            .collect(Collectors.toSet());
}