Example usage for java.util Set toArray

List of usage examples for java.util Set toArray

Introduction

In this page you can find the example usage for java.util Set toArray.

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Usage

From source file:com.googlecode.ddom.weaver.mixin.MergeAdapter.java

@Override
public void visit(int version, int access, String name, String signature, String superName,
        String[] interfaces) {/*from   w w  w  . ja  v  a  2  s.co  m*/
    finalName = name;
    Set<String> mergedInterfaces = new HashSet<String>();
    mergedInterfaces.addAll(Arrays.asList(interfaces));
    for (MixinInfo mixin : mixins) {
        mergedInterfaces.addAll(mixin.getContributedInterfaces());
    }
    super.visit(version, access, name, signature, superName,
            mergedInterfaces.toArray(new String[mergedInterfaces.size()]));
    Map<String, String> mapping = new HashMap<String, String>();
    for (MixinInfo mixin : mixins) {
        mapping.put(mixin.getName(), name);
    }
    remapper = new SimpleRemapper(mapping);
}

From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java

/**
 * @param useSmtps in order to use smtp.gmail.com (for testing)
 * @throws AddressException //from ww  w .  ja  va2s . co  m
 */
public SmtpEmailService(String host, String username, String replyTos, String password, boolean useSmtps)
        throws AddressException {
    this.host = host;
    this.username = username;
    this.password = password;
    this.useSmtps = useSmtps;
    if (replyTos != null) {
        String[] sreplyTos = replyTos.split(",");
        Set<InternetAddress> set = Sets.newHashSet();
        for (String s : sreplyTos) {
            if (!StringUtils.isEmpty(s))
                set.add(new InternetAddress(s));
        }
        this.replyTos = set.toArray(new InternetAddress[] {});
    }
}

From source file:hoot.services.osm.OsmTestUtils.java

public static void verifyTestRelationsUnmodified(final Set<Long> relationIds, final Set<Long> wayIds,
        final Set<Long> nodeIds, final long changesetId, final boolean verifyTags) {
    QCurrentRelations currentRelations = QCurrentRelations.currentRelations;
    final Long[] relationIdsArr = relationIds.toArray(new Long[] {});
    final Long[] nodeIdsArr = nodeIds.toArray(new Long[] {});
    final Long[] wayIdsArr = wayIds.toArray(new Long[] {});
    try {/*from w  w w  . ja  va2s. co m*/
        final Map<Long, CurrentRelations> relations =

                new SQLQuery(conn, DbUtils.getConfiguration(mapId)).from(currentRelations)
                        .where((currentRelations.changesetId.eq(changesetId)))
                        .map(currentRelations.id, currentRelations);
        Assert.assertEquals(4, relations.size());

        QCurrentRelationMembers currentRelationMembers = QCurrentRelationMembers.currentRelationMembers;
        CurrentRelations relationRecord = (CurrentRelations) relations.get(relationIdsArr[0]);
        Assert.assertEquals(new Long(changesetId), relationRecord.getChangesetId());
        Assert.assertEquals(relationIdsArr[0], relationRecord.getId());
        Assert.assertEquals(new Long(1), relationRecord.getVersion());
        List<CurrentRelationMembers> relationMembers = new SQLQuery(conn, DbUtils.getConfiguration(mapId))
                .from(currentRelationMembers).where(currentRelationMembers.relationId.eq(relationIdsArr[0]))
                .orderBy(currentRelationMembers.sequenceId.asc()).list(currentRelationMembers);
        Assert.assertEquals(4, relationMembers.size());
        CurrentRelationMembers member = relationMembers.get(0);
        Assert.assertEquals(relationRecord.getId(), member.getRelationId());
        Assert.assertEquals(DbUtils.nwr_enum.node, member.getMemberType());
        Assert.assertEquals("role1", member.getMemberRole());
        Assert.assertEquals(new Integer(1), member.getSequenceId());

        Assert.assertEquals(nodeIdsArr[0], member.getMemberId());
        member = relationMembers.get(1);
        Assert.assertEquals(relationRecord.getId(), member.getRelationId());
        Assert.assertEquals(DbUtils.nwr_enum.way, member.getMemberType());
        Assert.assertEquals("role3", member.getMemberRole());
        Assert.assertEquals(new Integer(2), member.getSequenceId());

        Assert.assertEquals(wayIdsArr[1], member.getMemberId());
        member = relationMembers.get(2);
        Assert.assertEquals(relationRecord.getId(), member.getRelationId());
        Assert.assertEquals(DbUtils.nwr_enum.way, member.getMemberType());
        Assert.assertEquals("role2", member.getMemberRole());
        Assert.assertEquals(new Integer(3), member.getSequenceId());

        Assert.assertEquals(wayIdsArr[0], member.getMemberId());
        member = relationMembers.get(3);
        Assert.assertEquals(relationRecord.getId(), member.getRelationId());
        Assert.assertEquals(DbUtils.nwr_enum.node, member.getMemberType());
        Assert.assertEquals("", member.getMemberRole());
        Assert.assertEquals(new Integer(4), member.getSequenceId());

        Assert.assertEquals(nodeIdsArr[2], member.getMemberId());
        if (verifyTags) {
            try {
                Map<String, String> tags = PostgresUtils
                        .postgresObjToHStore((PGobject) relationRecord.getTags());
                Assert.assertEquals(1, tags.size());
                Assert.assertEquals("val 1", tags.get("key 1"));
            } catch (Exception e) {
                Assert.fail("Error checking relation tags: " + e.getMessage());
            }
        }

        relationRecord = (CurrentRelations) relations.get(relationIdsArr[1]);
        Assert.assertEquals(new Long(changesetId), relationRecord.getChangesetId());
        Assert.assertEquals(relationIdsArr[1], relationRecord.getId());
        Assert.assertEquals(new Long(1), relationRecord.getVersion());
        relationMembers = new SQLQuery(conn, DbUtils.getConfiguration(mapId)).from(currentRelationMembers)
                .where(currentRelationMembers.relationId.eq(relationIdsArr[1]))
                .orderBy(currentRelationMembers.sequenceId.asc()).list(currentRelationMembers);
        Assert.assertEquals(2, relationMembers.size());
        member = relationMembers.get(0);
        Assert.assertEquals(relationRecord.getId(), member.getRelationId());
        Assert.assertEquals(DbUtils.nwr_enum.node, member.getMemberType());
        Assert.assertEquals("role1", member.getMemberRole());
        Assert.assertEquals(new Integer(1), member.getSequenceId());

        Assert.assertEquals(nodeIdsArr[4], member.getMemberId());
        member = relationMembers.get(1);
        Assert.assertEquals(relationRecord.getId(), member.getRelationId());
        Assert.assertEquals(DbUtils.nwr_enum.relation, member.getMemberType());
        Assert.assertEquals("role1", member.getMemberRole());
        Assert.assertEquals(new Integer(2), member.getSequenceId());

        Assert.assertEquals(relationIdsArr[0], member.getMemberId());
        if (verifyTags) {
            try {
                Map<String, String> tags = PostgresUtils
                        .postgresObjToHStore((PGobject) relationRecord.getTags());
                Assert.assertEquals(2, tags.size());
                Assert.assertEquals("val 2", tags.get("key 2"));
                Assert.assertEquals("val 3", tags.get("key 3"));
            } catch (Exception e) {
                Assert.fail("Error checking relation tags: " + e.getMessage());
            }
        }

        relationRecord = (CurrentRelations) relations.get(relationIdsArr[2]);
        Assert.assertEquals(new Long(changesetId), relationRecord.getChangesetId());
        Assert.assertEquals(relationIdsArr[2], relationRecord.getId());
        Assert.assertEquals(new Long(1), relationRecord.getVersion());
        relationMembers = new SQLQuery(conn, DbUtils.getConfiguration(mapId)).from(currentRelationMembers)
                .where(currentRelationMembers.relationId.eq(relationIdsArr[2]))
                .orderBy(currentRelationMembers.sequenceId.asc()).list(currentRelationMembers);
        Assert.assertEquals(1, relationMembers.size());
        member = relationMembers.get(0);
        Assert.assertEquals(relationRecord.getId(), member.getRelationId());
        Assert.assertEquals(DbUtils.nwr_enum.way, member.getMemberType());
        Assert.assertEquals("", member.getMemberRole());
        Assert.assertEquals(new Integer(1), member.getSequenceId());

        Assert.assertEquals(wayIdsArr[1], member.getMemberId());
        if (verifyTags) {
            try {
                Map<String, String> tags = PostgresUtils
                        .postgresObjToHStore((PGobject) relationRecord.getTags());
                Assert.assertEquals(1, tags.size());
                Assert.assertEquals("val 4", tags.get("key 4"));
            } catch (Exception e) {
                Assert.fail("Error checking relation tags: " + e.getMessage());
            }
        }

        relationRecord = (CurrentRelations) relations.get(relationIdsArr[3]);
        Assert.assertEquals(new Long(changesetId), relationRecord.getChangesetId());
        Assert.assertEquals(relationIdsArr[3], relationRecord.getId());
        Assert.assertEquals(new Long(1), relationRecord.getVersion());
        relationMembers =

                new SQLQuery(conn, DbUtils.getConfiguration(mapId)).from(currentRelationMembers)
                        .where(currentRelationMembers.relationId.eq(relationIdsArr[3]))
                        .orderBy(currentRelationMembers.sequenceId.asc()).list(currentRelationMembers);
        Assert.assertEquals(1, relationMembers.size());
        member = relationMembers.get(0);
        Assert.assertEquals(relationRecord.getId(), member.getRelationId());
        Assert.assertEquals(DbUtils.nwr_enum.node, member.getMemberType());
        Assert.assertEquals("role1", member.getMemberRole());
        Assert.assertEquals(new Integer(1), member.getSequenceId());

        Assert.assertEquals(nodeIdsArr[2], member.getMemberId());
        if (verifyTags) {
            try {
                Assert.assertTrue(relationRecord.getTags() == null
                        || StringUtils.isEmpty(((PGobject) relationRecord.getTags()).getValue()));
            } catch (Exception e) {
                Assert.fail("Error checking relation tags: " + e.getMessage());
            }
        }
    } catch (Exception e) {
        Assert.fail("Error checking relations: " + e.getMessage());
    }
}

From source file:com.jivesoftware.os.routing.bird.server.JerseyEndpoints.java

@Override
public Handler getHandler(final Server server, String context, String applicationName) {

    ResourceConfig rc = new ResourceConfig();

    if (enableSwagger) {
        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setVersion("1.0.0");
        beanConfig.setResourcePackage(resourcePackage);
        beanConfig.setScan(true);//from  ww  w  . jav  a  2 s . c  o  m
        beanConfig.setBasePath("/");
        beanConfig.setTitle(applicationName);

        Set<String> packages = new HashSet<>();
        packages.add(ApiListingResource.class.getPackage().getName());
        for (Class<?> clazz : allClasses) {
            packages.add(clazz.getPackage().getName());
        }
        rc.packages(packages.toArray(new String[0]));
    }

    rc.registerClasses(allClasses);
    rc.register(HttpMethodOverrideFilter.class);
    rc.register(new JacksonFeature().withMapper(mapper));
    rc.register(MultiPartFeature.class); // adds support for multi-part API requests
    rc.registerInstances(allBinders);
    rc.registerInstances(new InjectableBinder(allInjectables), new AbstractBinder() {
        @Override
        protected void configure() {
            bind(server).to(Server.class);
        }
    });

    if (supportCORS) {
        rc.register(CorsContainerResponseFilter.class);
    }

    for (ContainerRequestFilter containerRequestFilter : containerRequestFilters) {
        rc.register(containerRequestFilter);
    }

    for (ContainerResponseFilter containerResponseFilter : containerResponseFilters) {
        rc.register(containerResponseFilter);
    }

    ServletHolder servletHolder = new ServletHolder(new ServletContainer(rc));
    ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    servletContextHandler.setContextPath(context);
    if (!applicationName.isEmpty()) {
        servletContextHandler.setDisplayName(applicationName);
    }
    servletContextHandler.addServlet(servletHolder, "/*");
    servletContextHandler.addFilter(NewRelicRequestFilter.class, "/", EnumSet.of(DispatcherType.REQUEST));

    return servletContextHandler;
}

From source file:eu.supersede.fe.multitenant.MultiJpaProvider.java

@PostConstruct
private void load() {
    Map<String, DataSource> datasources = dataSourceBasedMultiTenantConnectionProviderImpl.getDataSources();

    repositoriesFactory = new HashMap<>();

    for (String n : datasources.keySet()) {
        try {//w  w w . j av  a 2  s  .  com
            log.info("Loading database: " + datasources.get(n).getConnection().getMetaData().getURL());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Map<String, Object> hibernateProps = new LinkedHashMap<>();
        hibernateProps.putAll(jpaProperties.getHibernateProperties(datasources.get(n)));

        hibernateProps.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");

        Set<String> packages = new HashSet<>();
        String[] tmp = MODELS_PACKAGES.split(",");

        for (String t : tmp) {
            packages.add(t.trim());
        }

        LocalContainerEntityManagerFactoryBean emfb = builder.dataSource(datasources.get(n))
                .packages(packages.toArray(new String[packages.size()])).properties(hibernateProps).jta(false)
                .build();

        emfb.afterPropertiesSet();
        EntityManagerFactory emf = emfb.getObject();
        EntityManager em = emf.createEntityManager();

        final JpaTransactionManager jpaTranMan = new JpaTransactionManager(emf);
        JpaRepositoryFactory jpaFactory = new JpaRepositoryFactory(em);
        jpaFactory.addRepositoryProxyPostProcessor(new MultiJpaRepositoryProxyPostProcessor(jpaTranMan));

        repositoriesFactory.put(n, new ContainerUtil(jpaFactory, emf, em));
    }
}

From source file:com.impetus.client.cassandra.query.CassandraEntityReader.java

/**
 * Method responsible for reading back entity and relations using secondary
 * indexes(if it holds any relation), else retrieve row keys using lucene.
 * //  www.ja v a2 s  .  c o  m
 * @param m
 *            entity meta data
 * @param relationNames
 *            relation names
 * @param isParent
 *            if entity is not holding any relation.
 * @param client
 *            client instance
 * @return list of wrapped enhance entities.
 */

@Override
public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client) {
    List<EnhanceEntity> ls = null;
    List<String> relationNames = m.getRelationNames();
    boolean isParent = m.isParent();

    boolean isRowKeyQuery = conditions != null ? conditions.keySet().iterator().next() : false;

    // If Query is not for find by range.
    if (!isRowKeyQuery) {
        // If holding associations.
        if (!isParent) {
            // In case need to use secondary indexes.
            if (MetadataUtils.useSecondryIndex(m.getPersistenceUnit())) {

                ls = ((PelopsClient) client).find(m, relationNames, this.conditions.get(isRowKeyQuery), 100);

            } else {
                // prepare lucene query and find.
                Set<String> rSet = fetchDataFromLucene(client);

                try {
                    ls = (List<EnhanceEntity>) ((PelopsClient) client).find(m.getEntityClazz(), relationNames,
                            true, m, rSet.toArray(new String[] {}));
                } catch (Exception e) {
                    log.error("Error while executing handleAssociation for cassandra:" + e.getMessage());
                    throw new QueryHandlerException(e);
                }
            }
        } else {
            if (MetadataUtils.useSecondryIndex(m.getPersistenceUnit())) {
                // in case need to search on secondry columns and it is not
                // set
                // to true!
                ls = ((PelopsClient) client).find(this.conditions.get(isRowKeyQuery), m, true, null, 100);
            } else {
                ls = onAssociationUsingLucene(m, client, ls);
            }
        }
    } else {
        // List<Object> results = new ArrayList<Object>();
        ls = handleFindByRange(m, client, ls, conditions, isRowKeyQuery);
        // ls = (List<EnhanceEntity>) results;
    }
    return ls;
}

From source file:com.baasbox.android.BaasUser.java

private static void writeStringSet(Parcel p, Set<String> s) {
    p.writeInt(s.size());/* w w w.j  a  v  a  2s . c  o m*/
    p.writeStringArray(s.toArray(new String[s.size()]));
}

From source file:gov.llnl.ontology.mapreduce.stats.WordnetShortestPathMR.java

/**
 * {@inheritDoc}//w w w . j a  va 2s .  co m
 */
public int run(String[] args) throws Exception {
    // Setup and valdiate the arguments.
    ArgOptions options = new ArgOptions();
    options.addOption('w', "wordnetDir", "The directory path to the wordnet data files", true, "PATH",
            "Required");

    options.parseOptions(args);
    if (!options.hasOption('w')) {
        System.err.println("usage: java WordnetShortestPathMR [OPTIONS] <outdir>\n" + options.prettyPrint());
    }

    // Open the wordnet reader and gather the set of all Synsets known by
    // the ontology.
    OntologyReader reader = WordNetCorpusReader.initialize(options.getStringOption('w'));
    Set<Synset> synsetSet = new HashSet<Synset>();
    for (String lemma : reader.wordnetTerms())
        for (Synset synset : reader.getSynsets(lemma))
            synsetSet.add(synset);

    // Compute each pairing of Synsets and write that pairing to a file in
    // HDFS.
    Synset[] synsets = synsetSet.toArray(new Synset[0]);
    PrintStream outStream = createPrintStream();
    for (int i = 0; i < synsets.length; ++i)
        for (int j = i + 1; j < synsets.length; ++j)
            outStream.printf("%s|%s\n", synsets[i].getName(), synsets[j].getName());
    outStream.close();

    // Store the wordnet directory information so that the mappers can load
    // it up.  They need it to figure out the shortest path information.
    Configuration conf = getConf();
    conf.set(WORDNET, options.getStringOption('w'));

    // Setup the job information.
    Job job = new Job(conf, "Compute Wordnet Shortest Paths");
    job.setJarByClass(WordnetShortestPathMR.class);

    job.setMapperClass(WordnetShortestPathMapper.class);

    // The input file will be the temporary file created with the synset
    // pairings.
    job.setInputFormatClass(LineDocInputFormat.class);
    FileInputFormat.addInputPath(job, new Path(TEMP_TERM_PAIR_PATH));

    // The mappers do all of the real work, so we just write their output
    // straight to disk.
    job.setCombinerClass(Reducer.class);
    job.setReducerClass(Reducer.class);
    job.setOutputFormatClass(TextOutputFormat.class);
    TextOutputFormat.setOutputPath(job, new Path(options.getPositionalArg(0)));

    // Start the job.
    job.waitForCompletion(true);

    return 0;
}

From source file:us.swcraft.springframework.session.store.aerospike.AerospikeTemplate.java

@Override
public void persist(final String key, final Set<Bin> bins) {
    Assert.notNull(key, "key can't be null");
    final Key recordKey = new Key(namespace, setname, key);
    Assert.notNull(bins, "bins can't be null");
    Assert.notEmpty(bins, "bins should have data to store");
    getAerospikeClient().put(writePolicy, recordKey, bins.toArray(BIN_ARRAY_TYPE));
}

From source file:com.impetus.kundera.db.accessor.SuperColumnFamilyDataAccessor.java

/**
 * From thrift row.// ww  w  .  j  a  v a2s .c om
 * 
 * @param <E>
 *            the element type
 * @param clazz
 *            the clazz
 * @param m
 *            the m
 * @param cr
 *            the cr
 * @return the e
 * @throws Exception
 *             the exception
 */
private <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, BaseDataAccessor<SuperColumn>.ThriftRow cr)
        throws Exception {

    // Instantiate a new instance
    E e = clazz.newInstance();

    // Set row-key. Note: @Id is always String.
    PropertyAccessorHelper.set(e, m.getIdProperty(), cr.getId());

    // Get a name->field map for super-columns
    Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
    for (Map.Entry<String, EntityMetadata.SuperColumn> entry : m.getSuperColumnsMap().entrySet()) {
        for (EntityMetadata.Column cMetadata : entry.getValue().getColumns()) {
            columnNameToFieldMap.put(cMetadata.getName(), cMetadata.getField());
        }
    }

    for (SuperColumn sc : cr.getColumns()) {

        String scName = PropertyAccessorFactory.STRING.fromBytes(sc.getName());
        boolean intoRelations = false;
        if (scName.equals(TO_ONE_SUPER_COL_NAME)) {
            intoRelations = true;
        }

        for (Column column : sc.getColumns()) {
            String name = PropertyAccessorFactory.STRING.fromBytes(column.getName());
            byte[] value = column.getValue();

            if (value == null) {
                continue;
            }

            if (intoRelations) {
                EntityMetadata.Relation relation = m.getRelation(name);

                String foreignKeys = PropertyAccessorFactory.STRING.fromBytes(value);
                Set<String> keys = deserializeKeys(foreignKeys);
                getEntityManager().getEntityResolver().populateForeignEntities(e, cr.getId(), relation,
                        keys.toArray(new String[0]));

            } else {
                // set value of the field in the bean
                Field field = columnNameToFieldMap.get(name);
                PropertyAccessorHelper.set(e, field, value);
            }
        }
    }
    return e;
}