Example usage for java.util Collections singleton

List of usage examples for java.util Collections singleton

Introduction

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

Prototype

public static <T> Set<T> singleton(T o) 

Source Link

Document

Returns an immutable set containing only the specified object.

Usage

From source file:ch.cyberduck.core.openstack.SwiftAuthenticationService.java

public Set<? extends AuthenticationRequest> getRequest(final Host host, final LoginCallback prompt)
        throws LoginCanceledException {
    final Credentials credentials = host.getCredentials();
    final StringBuilder url = new StringBuilder();
    url.append(host.getProtocol().getScheme().toString()).append("://");
    url.append(host.getHostname());/*  w w w. j a  v  a 2  s .c o  m*/
    if (!(host.getProtocol().getScheme().getPort() == host.getPort())) {
        url.append(":").append(host.getPort());
    }
    final String context = PathNormalizer.normalize(host.getProtocol().getContext());
    // Custom authentication context
    url.append(context);
    if (host.getProtocol().getDefaultHostname().endsWith("identity.api.rackspacecloud.com")
            || host.getHostname().endsWith("identity.api.rackspacecloud.com")) {
        return Collections.singleton(new Authentication20RAXUsernameKeyRequest(URI.create(url.toString()),
                credentials.getUsername(), credentials.getPassword(), null));
    }
    final LoginOptions options = new LoginOptions(host.getProtocol()).password(false).anonymous(false)
            .publickey(false);
    if (context.contains("1.0")) {
        return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()),
                credentials.getUsername(), credentials.getPassword()));
    } else if (context.contains("1.1")) {
        return Collections.singleton(new Authentication11UsernameKeyRequest(URI.create(url.toString()),
                credentials.getUsername(), credentials.getPassword()));
    } else if (context.contains("2.0")) {
        // Prompt for tenant
        final String user;
        final String tenant;
        if (StringUtils.contains(credentials.getUsername(), ':')) {
            final String[] parts = StringUtils.splitPreserveAllTokens(credentials.getUsername(), ':');
            tenant = parts[0];
            user = parts[1];
        } else {
            user = credentials.getUsername();
            tenant = prompt
                    .prompt(host, credentials.getUsername(),
                            LocaleFactory.localizedString("Provide additional login credentials",
                                    "Credentials"),
                            LocaleFactory.localizedString("Tenant Name", "Mosso"),
                            options.usernamePlaceholder(LocaleFactory.localizedString("Tenant Name", "Mosso")))
                    .getUsername();
            // Save tenant in username
            credentials.setUsername(String.format("%s:%s", tenant, credentials.getUsername()));
        }
        final Set<AuthenticationRequest> requests = new LinkedHashSet<AuthenticationRequest>();
        requests.add(new Authentication20UsernamePasswordRequest(URI.create(url.toString()), user,
                credentials.getPassword(), tenant));
        requests.add(new Authentication20UsernamePasswordTenantIdRequest(URI.create(url.toString()), user,
                credentials.getPassword(), tenant));
        requests.add(new Authentication20AccessKeySecretKeyRequest(URI.create(url.toString()), user,
                credentials.getPassword(), tenant));
        return requests;
    } else if (context.contains("3")) {
        // Prompt for project
        final String user;
        final String project;
        final String domain;
        if (StringUtils.contains(credentials.getUsername(), ':')) {
            final String[] parts = StringUtils.splitPreserveAllTokens(credentials.getUsername(), ':');
            if (parts.length == 3) {
                project = parts[0];
                domain = parts[1];
                user = parts[2];
            } else {
                project = parts[0];
                user = parts[1];
                domain = prompt
                        .prompt(host, credentials.getUsername(),
                                LocaleFactory.localizedString("Provide additional login credentials",
                                        "Credentials"),
                                LocaleFactory.localizedString("Project Domain Name", "Mosso"),
                                options.usernamePlaceholder(
                                        LocaleFactory.localizedString("Project Domain Name", "Mosso")))
                        .getUsername();
                // Save project name and domain in username
                credentials.setUsername(String.format("%s:%s:%s", project, domain, credentials.getUsername()));
            }
        } else {
            user = credentials.getUsername();
            final Credentials projectName = prompt.prompt(host, credentials.getUsername(),
                    LocaleFactory.localizedString("Provide additional login credentials", "Credentials"),
                    LocaleFactory.localizedString("Project Name", "Mosso"),
                    options.usernamePlaceholder(LocaleFactory.localizedString("Project Name", "Mosso")));
            if (StringUtils.contains(credentials.getUsername(), ':')) {
                final String[] parts = StringUtils.splitPreserveAllTokens(projectName.getUsername(), ':');
                project = parts[0];
                domain = parts[1];
            } else {
                project = projectName.getUsername();
                domain = prompt
                        .prompt(host, credentials.getUsername(),
                                LocaleFactory.localizedString("Provide additional login credentials",
                                        "Credentials"),
                                LocaleFactory.localizedString("Project Domain Name", "Mosso"),
                                options.usernamePlaceholder(
                                        LocaleFactory.localizedString("Project Domain Name", "Mosso")))
                        .getUsername();
            }
            // Save project name and domain in username
            credentials.setUsername(String.format("%s:%s:%s", project, domain, credentials.getUsername()));
        }
        final Set<AuthenticationRequest> requests = new LinkedHashSet<AuthenticationRequest>();
        requests.add(new Authentication3UsernamePasswordProjectRequest(URI.create(url.toString()), user,
                credentials.getPassword(), project, domain));
        return requests;
    } else {
        log.warn(String.format("Unknown context version in %s. Default to v1 authentication.", context));
        // Default to 1.0
        return Collections.singleton(new Authentication10UsernameKeyRequest(URI.create(url.toString()),
                credentials.getUsername(), credentials.getPassword()));
    }
}

From source file:com.google.play.developerapi.publisher.samples.AndroidPublisherHelper.java

/**
 * Authorizes the installed application to access user's protected data.
 *
 * @throws java.io.IOException//from  ww  w . j  a v  a  2 s.c  om
 * @throws java.security.GeneralSecurityException
 */
private static Credential authorizeWithInstalledApplication(File secretFile, File authStore)
        throws IOException {
    log.info("Authorizing using installed application");

    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new FileReader(secretFile));
    // Ensure file has been filled out.
    checkClientSecretsFile(clientSecrets);

    dataStoreFactory = new FileDataStoreFactory(authStore);

    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
            clientSecrets, Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER))
                    .setDataStoreFactory(dataStoreFactory).build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(INST_APP_USER_ID);
}

From source file:org.immutables.gson.stream.GsonMessageBodyProvider.java

private static Set<MediaType> mediaSetFrom(List<MediaType> mediaTypes) {
    if (mediaTypes.isEmpty()) {
        return Collections.singleton(MediaType.APPLICATION_JSON_TYPE);
    }/* w w w  . j av a  2  s.  c  om*/
    return new HashSet<MediaType>(mediaTypes);
}

From source file:com.phoenixst.plexus.DefaultRootedTreeView.java

public Collection rootNodes() {
    if (!getGraph().containsNode(root)) {
        return Collections.EMPTY_SET;
    }/*from ww  w.  ja  v  a  2  s. c  o  m*/
    return Collections.singleton(root);
}

From source file:com.cloudera.nav.plugin.client.writer.MetadataWriter.java

/**
 * Write the given entity based on @MProperty annotations.
 * Also create and write relations based on @MRelation annotations.
 * @param entity/* w w w .j  av  a  2s .  c  o  m*/
 */
public void write(Entity entity) {
    write(Collections.singleton(entity));
}

From source file:com.devicehive.resource.DeviceCommandResourceTest.java

@Test
public void should_get_empty_response_with_status_204_when_command_not_processed() throws Exception {
    DeviceClassEquipmentVO equipment = DeviceFixture.createEquipmentVO();
    DeviceClassUpdate deviceClass = DeviceFixture.createDeviceClass();
    deviceClass.setEquipment(Optional.of(Collections.singleton(equipment)));
    NetworkVO network = DeviceFixture.createNetwork();
    String guid = UUID.randomUUID().toString();
    DeviceUpdate deviceUpdate = DeviceFixture.createDevice(guid);
    deviceUpdate.setDeviceClass(Optional.of(deviceClass));
    deviceUpdate.setNetwork(Optional.of(network));

    // register device
    Response response = performRequest("/device/" + guid, "PUT", emptyMap(),
            singletonMap(HttpHeaders.AUTHORIZATION, tokenAuthHeader(ACCESS_KEY)), deviceUpdate, NO_CONTENT,
            null);/*from  w  ww.j  a  v a  2  s . com*/
    assertNotNull(response);
    TimeUnit.SECONDS.sleep(1);

    // create command
    DeviceCommand command = DeviceFixture.createDeviceCommand();
    command = performRequest("/device/" + guid + "/command", "POST", emptyMap(),
            singletonMap(HttpHeaders.AUTHORIZATION, tokenAuthHeader(ACCESS_KEY)), command, CREATED,
            DeviceCommand.class);
    assertNotNull(command.getId());
    TimeUnit.SECONDS.sleep(1);

    // try get not processed command
    Map<String, Object> params = new HashMap<>();
    params.put("waitTimeout", 1);
    DeviceCommand updatedCommand = performRequest("/device/" + guid + "/command/" + command.getId() + "/poll",
            "GET", params, singletonMap(HttpHeaders.AUTHORIZATION, tokenAuthHeader(ACCESS_KEY)), command,
            NO_CONTENT, DeviceCommand.class);
    assertNull(updatedCommand);

}

From source file:ch.cyberduck.cli.CommandLineUriParserTest.java

@Test
public void testProfile() throws Exception {
    final CommandLineParser parser = new PosixParser();
    final CommandLine input = parser.parse(new Options(), new String[] {});
    final Set<Protocol> list = new HashSet<>(Arrays.asList(new SwiftProtocol(),
            new ProfilePlistReader(new ProtocolFactory(Collections.singleton(new SwiftProtocol() {
                @Override/*from w  w w  . jav a  2  s .  c  om*/
                public boolean isEnabled() {
                    return true;
                }
            }))).read(new Local("../profiles/default/Rackspace US.cyberduckprofile"))));
    assertTrue(new Host(new ProtocolFactory(list).forName("rackspace"), "identity.api.rackspacecloud.com", 443,
            "/cdn.cyberduck.ch/", new Credentials("u", null))
                    .compareTo(new CommandLineUriParser(input, new ProtocolFactory(list))
                            .parse("rackspace://u@cdn.cyberduck.ch/")) == 0);

}

From source file:de.hybris.platform.cms2.servicelayer.services.impl.DefaultCMSNavigationServiceTest.java

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);

    final CatalogModel catalogModel = new CatalogModel();
    catalogModel.setId("testCatalog");

    final CatalogVersionModel catalogVersionModel = new CatalogVersionModel();
    catalogVersionModel.setActive(Boolean.TRUE);
    catalogVersionModel.setVersion("test");
    catalogVersionModel.setCatalog(catalogModel);
    catalogModel.setCatalogVersions(Collections.singleton(catalogVersionModel));

    rootNavigationModel = new CMSNavigationNodeModel();
    rootNavigationModel.setUid("test_uid");
    rootNavigationModel.setCatalogVersion(catalogVersionModel);
    rootNavigationModel.setParent(null);
    rootNavigationModel.setChildren(createNavigationNodes(catalogVersionModel));

    Mockito.when(modelService.create(CMSNavigationEntryModel.class)).thenReturn(new CMSNavigationEntryModel(),
            new CMSNavigationEntryModel(), new CMSNavigationEntryModel());

}

From source file:org.opennms.ng.dao.support.FilterResourceWalker.java

/**
 * <p>walk</p>// w  w  w . ja v a 2 s .com
 *
 * @param node a {@link org.opennms.netmgt.model.OnmsNode} object.
 */
public void walk(OnmsNode node) {
    OnmsResource resource = getResourceDao().getResourceForNode(node);
    m_resourceWalker.walk(Collections.singleton(resource));
}

From source file:com.nesscomputing.cache.PrefixedCache.java

public void put(final P prefix, final K key, final V value) {
    final String keyString = keySerializer.apply(SerializablePair.of(prefix, key));
    final byte[] valueBytes = valueSerializer.apply(value);
    nessCache.set(namespace,// w  w w.j a va2 s .  co  m
            Collections.singleton(CacheStores.fromSharedBytes(keyString, valueBytes, getExpiry())));
}