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:org.jboss.arquillian.spring.integration.javaconfig.utils.DefaultConfigurationClassesProcessor.java

/**
 * Tries to find all default configuration classes for given testClass
 *
 * @param testClass - test class to check
 *
 * @return - list of all inner static classes marked with @Configuration annotation
 *//*from www.  j  a  v a 2  s  . com*/
private Class<?>[] defaultConfigurationClasses(Class testClass) {
    Class<?>[] configurationCandidates = testClass.getClasses();
    Set<Class<?>> configurationClasses = new HashSet<Class<?>>();

    for (Class<?> configurationCandidate : configurationCandidates) {
        if (configurationCandidate.isAnnotationPresent(Configuration.class)) {
            validateConfigurationCandidate(configurationCandidate);
            configurationClasses.add(configurationCandidate);
        }
    }

    return configurationClasses.toArray(new Class<?>[0]);
}

From source file:edu.sampleu.admin.EdocLiteXmlIngesterBase.java

protected String[] getResourceListing(Class clazz, String pathStartsWith) throws Exception {
    String classPath = clazz.getName().replace(".", "/") + ".class";
    URL dirUrl = clazz.getClassLoader().getResource(classPath);

    if (!"jar".equals(dirUrl.getProtocol())) {
        throw new UnsupportedOperationException("Cannot list files for URL " + dirUrl);
    }/*from w  ww. ja v  a  2 s .com*/

    String jarPath = dirUrl.getPath().substring(5, dirUrl.getPath().indexOf("!")); //strip out only the JAR file
    JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    Enumeration<JarEntry> entries = jar.entries();
    Set<String> result = new HashSet<String>();

    while (entries.hasMoreElements()) {
        String entry = entries.nextElement().getName();
        if (entry.startsWith(pathStartsWith) && !entry.endsWith("/")) { //filter according to the pathStartsWith skipping directories
            result.add(entry);
        }
    }

    return result.toArray(new String[result.size()]);
}

From source file:com.netspective.axiom.DatabasePolicies.java

/**
 * Return the database policies with identifiers (keys) that match the given regular expression. A special case,
 * called '*' will simply return all the database policies.
 *///from  ww  w .  j av  a2  s  .  c o m

public DatabasePolicy[] getMatchingPolices(String regularExpression) {
    Set policies = new HashSet();

    for (Iterator i = policiesById.entrySet().iterator(); i.hasNext();) {
        Map.Entry entry = (Map.Entry) i.next();
        String id = (String) entry.getKey();

        if (regularExpression.equals(DBPOLICYIDMATCH_ALL) || ValidationUtils.matchRegexp(id, regularExpression))
            policies.add(entry.getValue());
    }

    return (DatabasePolicy[]) policies.toArray(new DatabasePolicy[policies.size()]);
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from w  w  w  .  j  a  va  2s . c  o m*/
@Path("users.json")
@RestQuery(name = "allusers", description = "Returns a list of users", returnDescription = "Returns a JSON representation of the list of user accounts", restParameters = {
        @RestParameter(defaultValue = "0", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING),
        @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING) }, reponses = {
                @RestResponse(responseCode = SC_OK, description = "The user accounts.") })
@SuppressWarnings("unchecked")
public String getUsersAsJson(@QueryParam("limit") int limit, @QueryParam("offset") int offset)
        throws IOException {
    if (limit < 1) {
        limit = 100;
    }
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("users").setMaxResults(limit).setFirstResult(offset);
        q.setParameter("o", securityService.getOrganization().getId());
        List<JpaUser> jpaUsers = q.getResultList();
        JSONArray jsonArray = new JSONArray();
        for (JpaUser user : jpaUsers) {
            Set<String> roles = user.getRoles();
            jsonArray.add(toJson(new User(user.getUsername(), user.getOrganization(),
                    roles.toArray(new String[roles.size()]))));
        }
        return jsonArray.toJSONString();
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:be.dnsbelgium.rdap.jackson.ContactSerializer.java

@Override
public void serialize(Contact contact, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException {
    jsonGenerator.writeStartArray();/*from w  ww  .  jav a  2 s  . co  m*/
    // start write version
    jsonGenerator.writeStartArray();
    jsonGenerator.writeString("version");
    jsonGenerator.writeStartObject();
    jsonGenerator.writeEndObject();
    jsonGenerator.writeString("text");
    jsonGenerator.writeString("4.0");
    jsonGenerator.writeEndArray();
    // end write version
    for (Contact.Property property : contact.getProperties()) {
        // start write property
        jsonGenerator.writeStartArray();
        // start write property name
        String key = (property.getGroup() == null) ? property.getName()
                : property.getGroup() + "." + property.getName();
        jsonGenerator.writeString(property.getName().toLowerCase(Locale.ENGLISH));
        // end write property name
        // start write property parameters
        jsonGenerator.writeStartObject();
        if (property.getGroup() != null) {
            jsonGenerator.writeFieldName("group");
            jsonGenerator.writeString(property.getGroup());
        }
        if (property.getParameters() != null) {

            Iterator<String> it = property.getParameters().keys();
            while (it.hasNext()) {
                String k = it.next();
                if (k.equalsIgnoreCase("value")) {
                    continue;
                }
                Set<String> values = property.getParameters().get(k);
                if (values.size() == 0) {
                    // no parameters for this property, skip this step
                    continue;
                }
                jsonGenerator.writeFieldName(k.toLowerCase(Locale.ENGLISH));
                if (values.size() == 1) {
                    jsonGenerator.writeString(values.toArray(new String[values.size()])[0]);
                    continue;
                }
                // start write all property parameter values (array)
                jsonGenerator.writeStartArray();
                for (String str : property.getParameters().get(k)) {
                    jsonGenerator.writeString(str);
                }
                jsonGenerator.writeEndArray();
                // end write all property parameter values (array)

            }
        }
        jsonGenerator.writeEndObject();
        // end write property parameters
        // start write property type
        String value = "text";
        if (property.getParameters() != null) {
            Set<String> types = property.getParameters().get("VALUE");
            if (types != null) {
                value = types.iterator().next();
            }
        }
        jsonGenerator.writeString(value);
        // end write property type
        // start write property value
        JsonSerializer s = serializerProvider.findValueSerializer(property.getValue().getClass(), null);
        s.serialize(property.getValue(), jsonGenerator, serializerProvider);
        // end write property value
        jsonGenerator.writeEndArray();
        // end write property
    }
    jsonGenerator.writeEndArray();
}

From source file:com.ibm.jaggr.core.impl.modulebuilder.javascript.RequireExpansionCompilerPass.java

/**
 * Recursively called to process AST nodes looking for require calls. If a
 * require call is found, then the dependency list is expanded to include
 * nested dependencies. The set of nested dependencies is obtained from the
 * config object and is trimmed so as not to include enclosing dependencies
 * (dependencies specified in the enclosing define or any enclosing require
 * calls.//w  w  w  . ja v a2s  . c  o  m
 *
 * @param node
 *            The node being processed
 * @param enclosingDependencies
 *            The set of dependencies specified by enclosing define or
 *            require calls.
 * @throws IOException
 */
public void processChildren(Node node, List<DependencyList> enclosingDependencies) throws IOException {
    for (Node cursor = node.getFirstChild(); cursor != null; cursor = cursor.getNext()) {
        Node dependencies = null;
        if ((dependencies = NodeUtil.moduleDepsFromRequire(cursor)) != null) {
            enclosingDependencies = new LinkedList<DependencyList>(enclosingDependencies);
            expandRequireList(dependencies, enclosingDependencies,
                    logDebug ? MessageFormat.format(Messages.RequireExpansionCompilerPass_0,
                            new Object[] { cursor.getLineno() }) : null,
                    true);
        } else if ((dependencies = NodeUtil.moduleDepsFromConfigDeps(cursor, configVarName)) != null) {
            expandRequireList(dependencies, new LinkedList<DependencyList>(),
                    logDebug ? MessageFormat.format(Messages.RequireExpansionCompilerPass_2,
                            new Object[] { cursor.getLineno() }) : null,
                    false);
        } else if ((dependencies = NodeUtil.moduleDepsFromDefine(cursor)) != null) {
            String moduleName = cursor.getFirstChild().getProp(Node.SOURCENAME_PROP).toString();

            if (aggregator.getOptions().isDevelopmentMode() && aggregator.getOptions().isVerifyDeps()) {
                // Validate dependencies for this module by comparing the
                // declared dependencies against the dependencies that were
                // used to calculate the dependency graph.
                Node strNode = dependencies.getFirstChild();
                List<String> deps = new ArrayList<String>();
                while (strNode != null) {
                    if (strNode.getType() == Token.STRING) {
                        String mid = strNode.getString();
                        if (!PathUtil.invalidChars.matcher(mid).find()) {
                            // ignore names with invalid characters
                            deps.add(strNode.getString());
                        }
                    }
                    strNode = strNode.getNext();
                }
                int idx = moduleName.lastIndexOf("/"); //$NON-NLS-1$
                String ref = (idx == -1) ? "" : moduleName.substring(0, idx); //$NON-NLS-1$
                List<String> normalized = Arrays
                        .asList(PathUtil.normalizePaths(ref, deps.toArray(new String[deps.size()])));

                // Run the list through a linked hash set to remove duplicate entries, yet keep list ordering
                Set<String> temp = new LinkedHashSet<String>(normalized);
                normalized = Arrays.asList(temp.toArray(new String[temp.size()]));

                List<String> processedDeps = aggregator.getDependencies().getDelcaredDependencies(moduleName);
                if (processedDeps != null && !processedDeps.equals(normalized)) {
                    // The dependency list for this module has changed since the dependencies
                    // were last created/validated.  Throw an exception.
                    throw new DependencyVerificationException(moduleName);
                }
            }
            // Add the expanded dependencies to the set of enclosing dependencies for
            // the module.
            List<String> moduleDeps = aggregator.getDependencies().getDelcaredDependencies(moduleName);
            if (moduleDeps != null) {
                enclosingDependencies = new LinkedList<DependencyList>(enclosingDependencies);
                DependencyList depList = new DependencyList(moduleName, moduleDeps, aggregator, hasFeatures,
                        true, // resolveAliases
                        logDebug);
                depList.setLabel(MessageFormat.format(Messages.RequireExpansionCompilerPass_1,
                        new Object[] { cursor.getLineno() }));
                enclosingDependencies.add(depList);
            }
        }
        // Recursively call this method to process the child nodes
        if (cursor.hasChildren())
            processChildren(cursor, enclosingDependencies);
    }
}

From source file:io.wcm.testing.mock.osgi.MockBundleContext.java

@Override
public ServiceReference[] getServiceReferences(final String clazz, final String filter) {
    Set<ServiceReference> result = new TreeSet<>();
    for (MockServiceRegistration serviceRegistration : this.registeredServices) {
        if (serviceRegistration.matches(clazz, filter)) {
            result.add(serviceRegistration.getReference());
        }/*w  w  w . j  a v  a  2 s . c om*/
    }
    if (result.size() == 0) {
        return null;
    } else {
        return result.toArray(new ServiceReference[result.size()]);
    }
}

From source file:com.intuit.wasabi.email.impl.EmailServiceImpl.java

/**
 * Removed duplicated and wrong addresses from the given set.
 *
 * @param emails the emails to be checked
 * @return and cleaned up array/*w w  w.  j a  v a 2  s  .  c om*/
 */
String[] removeInvalidEmails(String[] emails) {
    Set<String> cleanAddresses = new HashSet<>();
    for (String emailTo : emails) {
        if (emailVal.isValid(emailTo)) {
            cleanAddresses.add(emailTo);
        } else {
            LOGGER.warn(
                    "Remove email address: [" + emailTo + "] from email recipients, because it is not valid");
        }
    }
    return cleanAddresses.toArray(new String[cleanAddresses.size()]);
}

From source file:io.servicecomb.transport.rest.servlet.CseXmlWebApplicationContext.java

private String[] splitLocations(String locations) {
    Set<String> locationSet = new LinkedHashSet<>();
    if (!StringUtils.isEmpty(locations)) {
        for (String location : locations.split("[,\n]")) {
            location = location.trim();/*w  w w  .java 2s  . c o m*/
            if (StringUtils.isEmpty(location)) {
                continue;
            }

            locationSet.add(location);
        }
    }

    if (!StringUtils.isEmpty(defaultBeanResource)) {
        locationSet.add(defaultBeanResource);
    }

    return locationSet.toArray(new String[locationSet.size()]);
}

From source file:com.envision.envservice.service.UserService.java

/**
 * TO BO// w  ww. ja  v a 2 s .c  o m
 */
private UserBo toBo(SAPUser sapUser, boolean needManager) throws Exception {
    UserBo user = new UserBo();

    user.setUser_id(sapUser.getUserId());
    user.setName(sapUser.getUsername());
    user.setTitle(SAPUtil.toFieldDisplay(sapUser.getTitle()));
    user.setPhoto(PicUtil.getPicPath(user.getUser_id()));
    user.setCn_name(sapUser.getLastName());
    user.setEn_name(sapUser.getFirstName());
    user.setDepartment(SAPUtil.toFieldDisplay(sapUser.getDepartment()));
    user.setDivision(SAPUtil.toFieldDisplay(sapUser.getDivision()));
    user.setEmployee_type(sapUser.getCustom06());
    user.setEmail(sapUser.getEmail());
    user.setLocation(SAPUtil.toFieldDisplay(sapUser.getLocation()));
    user.setHire_date(SAPUtil.formatSAPDate(sapUser.getHireDate()));
    user.setPhone(StringUtils.trim(sapUser.getCustom08()));
    user.setChallenge_level(sapUser.getCustom04());
    user.setLast_performance_assess(sapUser.getCustom01());

    if (needManager) {
        Set<String> hlIds = orgStructureService.queryHigherLevel(user.getUser_id());
        if (hlIds.size() > 0) {
            String hdId = hlIds.toArray(new String[hlIds.size()])[0];

            List<UserBo> managers = queryByIds(false, false, hdId);
            if (managers.size() > 0) {
                UserBo manager = managers.get(0);

                user.setManager_id(hdId);
                user.setManager_cn_name(manager.getCn_name());
                user.setManager_en_name(manager.getEn_name());
            }
        }
    }

    return user;
}