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:com.frequencymarketing.citi.saml.UsmSaml.java

private SAMLResponse getSAMLResponse(TyUsmSamlProfileData memberData, String a_clientIp) throws Exception {
    String memberId = memberData.getMemberId();
    SAMLIdentifier idgen = SAMLIdentifierFactory.getInstance();
    SAMLResponse samlResponse = new SAMLResponse();
    SAMLAssertion samlAssertion = new SAMLAssertion();
    SAMLAuthenticationStatement samlAuthenticationStatement = new SAMLAuthenticationStatement();
    SAMLSubject samlSubject = new SAMLSubject(new SAMLNameIdentifier(memberId, null, null),
            Collections.singleton(SAMLSubject.CONF_BEARER), null, null);

    samlAuthenticationStatement.setSubjectIP(a_clientIp);
    samlAuthenticationStatement.setSubject(samlSubject);
    samlAuthenticationStatement.setAuthInstant(new Date());
    samlAuthenticationStatement.setAuthMethod(SAMLAuthenticationStatement.AuthenticationMethod_Password);
    samlAssertion.addStatement(samlAuthenticationStatement);
    samlAssertion.setId(idgen.getIdentifier());
    samlAssertion.setIssuer(getSamlProps().getIssuer());
    samlAssertion.setNotBefore(new Date(System.currentTimeMillis() - 30000));
    samlAssertion.setNotOnOrAfter(new Date(System.currentTimeMillis() + 90000));//2 minutes
    samlAssertion.addCondition(new SAMLAudienceRestrictionCondition(
            Collections.singleton(getSamlProps().getAudienceRestriction())));

    //NameIdentifier is the Member id.
    SAMLAttributeStatement samlsaStatement = new SAMLAttributeStatement();
    SAMLSubject l_subject2 = new SAMLSubject(new SAMLNameIdentifier(memberId, null, null),
            Collections.singleton(SAMLSubject.CONF_BEARER), null, null);

    samlsaStatement.setSubject(l_subject2);
    samlsaStatement = addToAttributeStatement(samlsaStatement, "member_id", memberId, null, XML.SAML_NS);

    samlsaStatement = addToAttributeStatement(samlsaStatement, "agent_id", memberData.getAgentId(), null,
            XML.SAML_NS);/*  w w  w  .ja  va 2s . c o m*/

    samlsaStatement = addToAttributeStatement(samlsaStatement, "mbr_name_first", memberData.getFirstName(),
            null, XML.SAML_NS);
    samlsaStatement = addToAttributeStatement(samlsaStatement, "mbr_name_last", memberData.getLastName(), null,
            XML.SAML_NS);

    samlsaStatement = addToAttributeStatement(samlsaStatement, "point_balance", memberData.getPointBalance(),
            null, XML.SAML_NS);
    samlAssertion.addStatement(samlsaStatement);
    samlResponse.addAssertion(samlAssertion);
    samlResponse.setId(idgen.getIdentifier());

    //Load the KeyStore
    KeyStore keystore = CryptoKeystoreUtil.getKeyStore(getSamlProps().getKeystore(),
            getSamlProps().getKeystorePass().toCharArray());

    KeyPair keyPair = CryptoKeystoreUtil.getKeyPair(keystore, getSamlProps().getKeystoreAlias(),
            getSamlProps().getKeystorePass().toCharArray());

    samlResponse.sign(XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, keyPair.getPrivate(), null);

    s_logger.debug(samlResponse.toString());

    System.out.println(samlResponse);

    return samlResponse;
}

From source file:eu.fusepool.p3.transformer.sample.SimpleAsyncTransformer.java

@Override
public Set<MimeType> getSupportedOutputFormats() {
    return Collections.singleton(getOutputMimeType());
}

From source file:com.exxonmobile.ace.hybris.core.search.solrfacetsearch.provider.impl.VariantProductSource.java

protected Set<ProductModel> getBaseProducts(final Object model) {
    if (model instanceof VariantProductModel) {
        // Collect all the variant products and all their super variants, until the final base product is hit
        final Set<ProductModel> products = new HashSet<ProductModel>();

        ProductModel currentProduct = (ProductModel) model;
        while (currentProduct instanceof VariantProductModel) {
            products.add(currentProduct);
            currentProduct = ((VariantProductModel) currentProduct).getBaseProduct();
        }/*w  w w  .  ja v a  2  s . c  om*/

        products.add(currentProduct);
        return products;
    } else if (model instanceof ProductModel) {
        return Collections.singleton((ProductModel) model);
    }
    return Collections.emptySet();
}

From source file:de.blizzy.documentr.util.Util.java

/**
 * <p>Joins a list of objects into a string using a delimiter. This works for different types
 * of <code>o</code>:</p>
 *
 * <ul>//from   w  w w.  jav  a 2 s . co  m
 *   <li>If <code>o</code> is a {@link Collection}, all elements are joined together.</li>
 *   <li>If <code>o</code> is an array, all elements are joined together.</li>
 *   <li>Otherwise, <code>o</code> is used directly.</li>
 * </ul>
 *
 * <p>For each element in <code>o</code> its respective {@link Object#toString()} method is invoked.</p>
 */
public static String join(Object o, String delimiter) {
    Collection<?> c;
    if (o instanceof Collection) {
        c = (Collection<?>) o;
    } else if (o.getClass().isArray()) {
        c = Lists.newArrayList((Object[]) o);
    } else {
        c = Collections.singleton(o);
    }
    return StringUtils.join(c, delimiter);
}

From source file:org.springframework.data.rest.webmvc.json.DomainObjectReaderUnitTests.java

@Before
public void setUp() {

    KeyValueMappingContext mappingContext = new KeyValueMappingContext();
    mappingContext.getPersistentEntity(SampleUser.class);
    mappingContext.getPersistentEntity(Person.class);
    mappingContext.getPersistentEntity(TypeWithGenericMap.class);
    mappingContext.getPersistentEntity(VersionedType.class);
    mappingContext.afterPropertiesSet();

    PersistentEntities entities = new PersistentEntities(Collections.singleton(mappingContext));

    this.reader = new DomainObjectReader(entities,
            new Associations(mappings, mock(RepositoryRestConfiguration.class)));
}

From source file:me.smoe.adar.utils.cam.o.statistics.Statistics.java

private void handleCase(CAMCases cases, boolean needParticiple) throws Exception {
    Set<String> words = needParticiple ? SentenceAnalyzer.analyzer(cases.getCases())
            : Collections.singleton(cases.getCases());
    for (String word : words) {
        WORD_COUNT.put(word, WORD_COUNT.containsKey(word) ? WORD_COUNT.get(word) + 1 : 1);

        Map<Long, Integer> camaping;
        if (WORD_M_CA_COUNT.containsKey(word)) {
            camaping = WORD_M_CA_COUNT.get(word);
        } else {//www .  j  a v a2  s . c  o  m
            camaping = new HashMap<Long, Integer>();
            WORD_M_CA_COUNT.put(word, camaping);
        }
        camaping.put(cases.getCa(), camaping.containsKey(cases.getCa()) ? camaping.get(cases.getCa()) + 1 : 1);
    }
}

From source file:ch.cyberduck.core.s3.S3SessionCredentialsRetrieverTest.java

@Test(expected = ConnectionTimeoutException.class)
@Ignore/*from ww  w . j a v a2  s.  co m*/
public void testGet() throws Exception {
    new S3SessionCredentialsRetriever(new DisabledX509TrustManager(), new DefaultX509KeyManager(),
            new ProtocolFactory(Collections.singleton(new DAVProtocol())), new DisabledTranscriptListener(),
            "http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access").get();
}

From source file:ch.cyberduck.core.irods.IRODSWriteFeatureTest.java

@Test
public void testWriteConcurrent() throws Exception {
    final ProtocolFactory factory = new ProtocolFactory(
            new HashSet<>(Collections.singleton(new IRODSProtocol())));
    final Profile profile = new ProfilePlistReader(factory)
            .read(new Local("../profiles/iRODS (iPlant Collaborative).cyberduckprofile"));
    final Host host = new Host(profile, profile.getDefaultHostname(),
            new Credentials(System.getProperties().getProperty("irods.key"),
                    System.getProperties().getProperty("irods.secret")));

    final IRODSSession session1 = new IRODSSession(host);
    session1.open(new DisabledHostKeyCallback());
    session1.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());

    final IRODSSession session2 = new IRODSSession(host);
    session2.open(new DisabledHostKeyCallback());
    session2.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());

    final Path test1 = new Path(new IRODSHomeFinderService(session1).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));
    final Path test2 = new Path(new IRODSHomeFinderService(session2).find(), UUID.randomUUID().toString(),
            EnumSet.of(Path.Type.file));

    final byte[] content = RandomUtils.nextBytes(68400);

    final OutputStream out1 = new IRODSWriteFeature(session1).write(test1,
            new TransferStatus().append(false).length(content.length), new DisabledConnectionCallback());
    final OutputStream out2 = new IRODSWriteFeature(session2).write(test2,
            new TransferStatus().append(false).length(content.length), new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content),
            out2);/*  w  ww. ja v a 2  s  .c  o m*/
    // Error code received from iRODS:-23000
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content),
            out1);

    {
        final InputStream in1 = session1.getFeature(Read.class).read(test1, new TransferStatus(),
                new DisabledConnectionCallback());
        final byte[] buffer1 = new byte[content.length];
        IOUtils.readFully(in1, buffer1);
        in1.close();
        assertArrayEquals(content, buffer1);
    }
    {
        final InputStream in2 = session2.getFeature(Read.class).read(test2, new TransferStatus(),
                new DisabledConnectionCallback());
        final byte[] buffer2 = new byte[content.length];
        IOUtils.readFully(in2, buffer2);
        in2.close();
        assertArrayEquals(content, buffer2);
    }
    session1.close();
    session2.close();
}

From source file:com.redhat.red.offliner.ftest.SingleFoloRecordDownloadFTest.java

/**
 * In general, we should only have one test method per functional test. This allows for the best parallelism when we
 * execute the tests, especially if the setup takes some time.
 *
 * @throws Exception In case anything (anything at all) goes wrong!
 *///ww  w  .  ja v a2s. c o  m
@Test
public void run() throws Exception {
    // We only need one repo server.
    TestRepositoryServer server = newRepositoryServer();

    // Generate some test content
    byte[] content = contentGenerator.newBinaryContent(1024);

    TrackedContentEntryDTO dto = contentGenerator.newRemoteContentEntry(new StoreKey(StoreType.remote, "test"),
            "jar", server.getBaseUri(), content);

    TrackedContentDTO record = new TrackedContentDTO(new TrackingKey("test-record"), Collections.emptySet(),
            Collections.singleton(dto));

    String path = dto.getPath();

    // Register the generated content by writing it to the path within the repo server's dir structure.
    // This way when the path is requested it can be downloaded instead of returning a 404.
    server.registerContent(path, content);
    server.registerContent(path + Main.SHA_SUFFIX, sha1Hex(content));
    server.registerContent(path + Main.MD5_SUFFIX, md5Hex(content));

    // Write the plaintext file we'll use as input.
    File foloRecord = temporaryFolder.newFile("folo." + getClass().getSimpleName() + ".json");

    FileUtils.write(foloRecord, objectMapper.writeValueAsString(record));

    Options opts = new Options();
    opts.setBaseUrls(Collections.singletonList(server.getBaseUri()));

    // Capture the downloads here so we can verify the content.
    File downloads = temporaryFolder.newFolder();

    opts.setDownloads(downloads);
    opts.setLocations(Collections.singletonList(foloRecord.getAbsolutePath()));

    // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc.
    Main finishedMain = run(opts);

    assertThat("Wrong number of downloads logged. Should have been 3 including checksums.",
            finishedMain.getDownloaded(), equalTo(3));
    assertThat("Errors should be empty!", finishedMain.getErrors().isEmpty(), equalTo(true));

    File downloaded = new File(downloads, path);
    assertThat("File: " + path + " doesn't seem to have been downloaded!", downloaded.exists(), equalTo(true));
    assertThat("Downloaded file: " + path + " contains the wrong content!",
            FileUtils.readFileToByteArray(downloaded), equalTo(content));
}

From source file:org.commonjava.aprox.depgraph.rest.ProjectController.java

public String errors(final String groupId, final String artifactId, final String version,
        final String workspaceId) throws AproxWorkflowException {
    final ProjectVersionRef ref = new ProjectVersionRef(groupId, artifactId, version);
    final ViewParams params = new ViewParams(workspaceId, ref);
    try {/*  w w w.j  ava 2s  .c o  m*/
        final String error = ops.getProjectError(ref, params);
        if (error == null) {
            return null;
        }

        return serializer.writeValueAsString(Collections.singletonMap("items", Collections.singleton(error)));
    } catch (final CartoDataException e) {
        throw new AproxWorkflowException("Failed to lookup errors for: {} in: {}. Reason: {}", e,
                ref == null ? "all projects" : ref, params, e.getMessage());
    } catch (final JsonProcessingException e) {
        throw new AproxWorkflowException("Failed to serialize to JSON: %s", e, e.getMessage());
    }
}