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

Object[] toArray();

Source Link

Document

Returns an array containing all of the elements in this set.

Usage

From source file:com.aurel.track.admin.customize.lists.systemOption.IssueTypeBL.java

/**
 * Load all possible item types which can be created by the user
 * @param personID//from  www  . ja  v a 2 s  .c om
 * @param locale
 * @return
 */
public static List<TListTypeBean> loadAllByPerson(Integer personID, Locale locale) {
    //get all create item role assignments for person
    List<TAccessControlListBean> accessControlListBeans = AccessBeans.loadByPersonAndRight(personID,
            new int[] { AccessFlagIndexes.CREATETASK, AccessFlagIndexes.PROJECTADMIN }, true);
    Map<Integer, Set<Integer>> projectsToRolesMap = new HashMap<Integer, Set<Integer>>();
    Set<Integer> allPersonRolesSet = new HashSet<Integer>();
    if (accessControlListBeans != null) {
        for (TAccessControlListBean accessControlListBean : accessControlListBeans) {
            Integer projectID = accessControlListBean.getProjectID();
            Integer roleID = accessControlListBean.getRoleID();
            allPersonRolesSet.add(roleID);
            Set<Integer> rolesInProject = projectsToRolesMap.get(projectID);
            if (rolesInProject == null) {
                rolesInProject = new HashSet<Integer>();
                projectsToRolesMap.put(projectID, rolesInProject);
            }
            rolesInProject.add(roleID);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(accessControlListBeans.size() + " assignments found for person " + personID + ": "
                    + allPersonRolesSet.size() + " roles " + " in " + projectsToRolesMap.size() + " projects ");
        }
    } else {
        return new LinkedList<TListTypeBean>();
    }
    //gets the itemType assignments for the assigned roles 
    Map<Integer, Set<Integer>> roleToItemTypesMap = new HashMap<Integer, Set<Integer>>();
    List<TRoleListTypeBean> itemTypesInRoles = RoleBL
            .loadByRoles(GeneralUtils.createIntegerListFromCollection(allPersonRolesSet));
    if (itemTypesInRoles != null) {
        for (TRoleListTypeBean roleListTypeBean : itemTypesInRoles) {
            Integer roleID = roleListTypeBean.getRole();
            Integer itemTypeID = roleListTypeBean.getListType();
            Set<Integer> itemTypesInRoleSet = roleToItemTypesMap.get(roleID);
            if (itemTypesInRoleSet == null) {
                itemTypesInRoleSet = new HashSet<Integer>();
                roleToItemTypesMap.put(roleID, itemTypesInRoleSet);
            }
            itemTypesInRoleSet.add(itemTypeID);
        }
    }
    Set<Integer> projectSet = projectsToRolesMap.keySet();
    if (projectSet.isEmpty()) {
        LOGGER.info("No project assignment for person " + personID);
        return new LinkedList<TListTypeBean>();
    }
    //gets the project to projectType map
    List<TProjectBean> projectList = ProjectBL
            .loadByProjectIDs(GeneralUtils.createIntegerListFromCollection(projectSet));
    Map<Integer, Integer> projectToProjectTypeMap = new HashMap<Integer, Integer>();
    Set<Integer> projectTypesSet = new HashSet<Integer>();
    for (TProjectBean projectBean : projectList) {
        Integer projectTypeID = projectBean.getProjectType();
        projectToProjectTypeMap.put(projectBean.getObjectID(), projectTypeID);
        projectTypesSet.add(projectTypeID);
    }
    //gets the item type assignments for project types
    List<TPlistTypeBean> plistTypes = loadByProjectTypes(projectTypesSet.toArray());
    Map<Integer, Set<Integer>> projectTypeToItemTypesMap = new HashMap<Integer, Set<Integer>>();
    if (plistTypes != null) {
        for (TPlistTypeBean plistTypeBean : plistTypes) {
            Integer projectTypeID = plistTypeBean.getProjectType();
            Integer itemTypeID = plistTypeBean.getCategory();
            Set<Integer> itemTypesSet = projectTypeToItemTypesMap.get(projectTypeID);
            if (itemTypesSet == null) {
                itemTypesSet = new HashSet<Integer>();
                projectTypeToItemTypesMap.put(projectTypeID, itemTypesSet);
            }
            itemTypesSet.add(itemTypeID);
        }
    }
    Set<Integer> allowedItemTypeIDs = new HashSet<Integer>();
    List<TListTypeBean> allSelectableitemTypeBeans = IssueTypeBL.loadAllSelectable(locale);
    Set<Integer> allSelectableItemTypeIDs = GeneralUtils
            .createIntegerSetFromBeanList(allSelectableitemTypeBeans);
    for (Map.Entry<Integer, Set<Integer>> rolesInProjectEntry : projectsToRolesMap.entrySet()) {
        Integer projectID = rolesInProjectEntry.getKey();
        Set<Integer> roleIDs = rolesInProjectEntry.getValue();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(roleIDs.size() + " roles found in project " + projectID);
        }
        Integer projectTypeID = projectToProjectTypeMap.get(projectID);
        Set<Integer> projectTypeLimitedItemTypes = projectTypeToItemTypesMap.get(projectTypeID);
        Set<Integer> rolesLimitedItemTypes = new HashSet<Integer>();
        //get the item types limited in all roles
        for (Integer roleID : roleIDs) {
            Set<Integer> roleLimitedItemTypes = roleToItemTypesMap.get(roleID);
            if (roleLimitedItemTypes != null) {
                rolesLimitedItemTypes.addAll(roleLimitedItemTypes);
            } else {
                //at least one role has no item type limitations
                rolesLimitedItemTypes.clear();
                break;
            }
        }
        if ((projectTypeLimitedItemTypes == null || projectTypeLimitedItemTypes.isEmpty())
                && rolesLimitedItemTypes.isEmpty()) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("No roles or project type specific limitation found for project " + projectID);
            }
            return allSelectableitemTypeBeans;
        } else {
            if (projectTypeLimitedItemTypes == null || projectTypeLimitedItemTypes.isEmpty()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Add role specific item type limitations for project " + projectID);
                }
                allowedItemTypeIDs.addAll(rolesLimitedItemTypes);
            } else {
                if (rolesLimitedItemTypes.isEmpty()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(
                                "Add project type specific item type limitations for project " + projectID);
                    }
                    allowedItemTypeIDs.addAll(projectTypeLimitedItemTypes);
                } else {
                    Collection<Integer> intersection = CollectionUtils.intersection(projectTypeLimitedItemTypes,
                            rolesLimitedItemTypes);
                    if (intersection != null) {
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug(
                                    "Add project type specific and role specific item type limitations for project "
                                            + projectID);
                        }
                        allowedItemTypeIDs.addAll(intersection);
                    }
                }
            }
        }
    }
    allowedItemTypeIDs.retainAll(allSelectableItemTypeIDs);
    if (allowedItemTypeIDs.isEmpty()) {
        return new LinkedList<TListTypeBean>();
    } else {
        return LocalizeUtil.localizeDropDownList(
                loadByIssueTypeIDs(GeneralUtils.createIntegerListFromCollection(allowedItemTypeIDs)), locale);
    }
}

From source file:com.thesmartweb.swebrank.GoogleResults.java

/**
 * Method to get the results number for a specific query
 * @param quer the query to search for//from  w w  w. ja va  2s.c om
 * @param config_path the directory to get the keys from
 * @return the number of results
 */
public Long Get_Results_Number(String quer, String config_path) {//it gets the results number for a specific query
    long results_number = 0;
    //we connect through the google api JSON custom search
    String check_quer = quer.substring(quer.length() - 1, quer.length());
    char plus = "+".charAt(0);
    char check_plus = check_quer.charAt(0);
    if (check_plus == plus) {
        quer = quer.substring(0, quer.length() - 1);
    }
    String[] keys = GetKeys(config_path);
    int flag_key = 0;
    int i = 0;
    while (flag_key == 0 && i < (keys.length)) {
        try {
            String key = keys[i];
            i++;
            URL link_ur = new URL(
                    "https://www.googleapis.com/customsearch/v1?key=" + key + "&q=" + quer + "&alt=json");
            APIconn apicon = new APIconn();
            String line = apicon.connect(link_ur);
            if (!line.equalsIgnoreCase("fail")) {
                flag_key = 1;
                JSONParser parser = new JSONParser();
                //Create the map
                Map json = (Map) parser.parse(line);
                // Get a set of the entries
                Set set = json.entrySet();
                Object[] obj = set.toArray();
                Map.Entry entry = (Map.Entry) obj[2];
                //get to the second level
                String you = entry.getValue().toString();
                json = (Map) parser.parse(you);
                set = json.entrySet();
                obj = set.toArray();
                entry = (Map.Entry) obj[obj.length - 1];
                //get to the third level
                you = entry.getValue().toString();
                JSONArray json_arr = (JSONArray) parser.parse(you);
                obj = json_arr.toArray();
                you = obj[0].toString();
                //get to the fourth level
                json = (Map) parser.parse(you);
                set = json.entrySet();
                obj = set.toArray();
                entry = (Map.Entry) obj[4];
                results_number = (Long) entry.getValue();
            }
        } catch (MalformedURLException | ParseException ex) {
            Logger.getLogger(GoogleResults.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return results_number;

}

From source file:io.neba.core.resourcemodels.adaptation.ResourceToModelAdapterUpdater.java

private Dictionary<String, Object> createResourceToModelAdapterProperties() {
    Dictionary<String, Object> properties = new Hashtable<>();
    Set<String> fullyQualifiedNamesOfRegisteredModels = getAdapterTypeNames();
    properties.put(ADAPTER_CLASSES, fullyQualifiedNamesOfRegisteredModels.toArray());
    properties.put(ADAPTABLE_CLASSES, new String[] { Resource.class.getName() });
    properties.put(SERVICE_VENDOR, "neba.io");
    properties.put(SERVICE_DESCRIPTION, "Adapts Resources to @ResourceModels.");
    return properties;
}

From source file:com.speedment.spring.boot.autoconfigure.SpeedmentConfiguration.java

@ConditionalOnProperty(prefix = "speedment", value = { "password", "basePackage" })
@Bean/*w  w  w . j av a 2s. c o m*/
public Speedment speedment() throws Exception {
    Reflections reflections = new Reflections(properties.getBasePackage());

    Set<Class<? extends SpeedmentApplicationLifecycle>> speedmentApplications = reflections
            .getSubTypesOf(SpeedmentApplicationLifecycle.class);

    Speedment speedment = ((Class<? extends SpeedmentApplicationLifecycle>) speedmentApplications.toArray()[0])
            .newInstance().withPassword(properties.getPassword()).build();

    //TODO: Below code block can be used to create the Manager instances as spring beans
    /* Set<Class<? extends Entity>> entities = reflections.getSubTypesOf(Entity.class);
     List<Manager> interfaces = entities.stream()
      .filter(Class::isInterface)
      .map(i -> speedment.managerOf(i))
      .collect(Collectors.toList());*/
    return speedment;
}

From source file:io.druid.indexer.updater.HadoopConverterJob.java

private static void setJobName(JobConf jobConf, List<DataSegment> segments) {
    if (segments.size() == 1) {
        final DataSegment segment = segments.get(0);
        jobConf.setJobName(String.format("druid-convert-%s-%s-%s", segment.getDataSource(),
                segment.getInterval(), segment.getVersion()));
    } else {/*w w w .j  av  a2 s . c  o  m*/
        final Set<String> dataSources = Sets
                .newHashSet(Iterables.transform(segments, new Function<DataSegment, String>() {
                    @Override
                    public String apply(DataSegment input) {
                        return input.getDataSource();
                    }
                }));
        final Set<String> versions = Sets
                .newHashSet(Iterables.transform(segments, new Function<DataSegment, String>() {
                    @Override
                    public String apply(DataSegment input) {
                        return input.getVersion();
                    }
                }));
        jobConf.setJobName(String.format("druid-convert-%s-%s", Arrays.toString(dataSources.toArray()),
                Arrays.toString(versions.toArray())));
    }
}

From source file:com.hengyi.japp.execution.domain.Sms.java

public String getPhonesAsString() {
    Set<String> phoneSet = Sets.newHashSet();
    for (Mobile mobile : getMobiles()) {
        phoneSet.add(mobile.getPhone());
    }/*from   w w  w. j a  v  a  2 s  .  c o m*/
    String phones = Arrays.toString(phoneSet.toArray());
    phones = deleteWhitespace(phones);
    return phones.substring(1, phones.length() - 1);
}

From source file:edu.pitt.dbmi.ccd.queue.task.SlurmAlgorithmJob.java

@Scheduled(fixedRate = 5000)
public void manageJobsInQueue() {
    List<JobStatus> finishedJobList = algorithmSlurmService.getFinishedJobs();
    Map<Long, JobStatus> finishedJobMap = new HashMap<>();
    if (finishedJobList != null && !finishedJobList.isEmpty()) {
        finishedJobList.forEach(jobStatus -> {
            finishedJobMap.put(new Long(jobStatus.getJobId()), jobStatus);
        });/*from  w w  w  .  j  a  va2 s.c  o m*/
    }

    int numRunningJobs = 0;

    List<JobQueueInfo> runningJobList = jobQueueInfoService.findByStatus(1);
    for (JobQueueInfo job : runningJobList) {
        Long pid = job.getPid();
        if (pid != null && finishedJobMap.containsKey(pid)) {
            if (finishedJobMap.containsKey(pid)) {
                Long queueId = job.getId();
                jobQueueInfoService.deleteJobById(queueId);

                JobStatus status = finishedJobMap.get(pid);
                JobStat stat = algorithmSlurmService.getJobStat(pid);
                Set<UserAccount> userAccounts = job.getUserAccounts();
                UserAccount userAccount = (UserAccount) userAccounts.toArray()[0];
                String username = userAccount.getUsername();
                LOGGER.info("JobUsage{" + "JobId=" + queueId + ", " + "HPCjobId=" + pid + ", " + "User='"
                        + username + "', " + "State='" + status.getState() + "', " + "Elapsed='"
                        + status.getTime() + "', " + "Start='" + stat.getStart() + "', " + "End='"
                        + stat.getEnd() + "', " + "Partition='" + status.getPartition() + "', " + "AllocCPUS="
                        + stat.getAllocCPUS() + ", " + "AllocNodes=" + stat.getAllocNodes() + ", "
                        + "NodeList='" + status.getNodelist() + "'}");

                algorithmSlurmService.downloadJobResult(job);
            } else {
                numRunningJobs++;
            }
        }
    }

    if (numRunningJobs < queueSize) {
        // Waiting list to execute
        List<JobQueueInfo> jobList = jobQueueInfoService.findByStatus(0);
        if (!jobList.isEmpty()) {
            // Execute one at a time
            JobQueueInfo jobQueueInfo = jobList.get(0);
            LOGGER.info("Run Job ID: " + jobQueueInfo.getId());

            try {
                LOGGER.info("Set Job's status to be 1 (running): " + jobQueueInfo.getId());
                jobQueueInfo.setStatus(1);
                jobQueueInfoService.saveJobIntoQueue(jobQueueInfo);

                algorithmSlurmService.submitJobtoSlurm(jobQueueInfo);
            } catch (Exception exception) {
                LOGGER.error("Unable to run " + jobQueueInfo.getAlgorName(), exception);
            }
        }
    }

    // Waiting list to terminate
    List<JobQueueInfo> jobList = jobQueueInfoService.findByStatus(2);
    jobList.forEach(job -> {
        killJob(job.getId());
    });

}

From source file:com.aurel.track.persist.TBasketPeer.java

/**
 * Loads a basketBeans by keys // w w  w . ja  v  a 2  s .com
 * @param objectID
 * @return
 */
@Override
public List<TBasketBean> loadByPrimaryKeys(Set<Integer> objectIDs) {
    Criteria crit = new Criteria();
    crit.addIn(OBJECTID, objectIDs.toArray());
    try {
        return convertTorqueListToBeanList(doSelect(crit));
    } catch (Exception e) {
        LOGGER.error("Loading all main baskets failed with " + e.getMessage());
        return null;
    }
}

From source file:com.netpace.cms.sso.filter.OpenSSOClientAdapter.java

public String getUserAttribute(String attribute, SSOToken token) {
    String attributeValue = null;
    try {//from   w  w w  .  j  a  v  a  2s.c  o  m
        Set<String> attributeValues = (Set<String>) IdUtils.getIdentity(token).getAttribute(attribute);
        if (!attributeValues.isEmpty()) {
            attributeValue = attributeValues.toArray()[0].toString();
        }
    } catch (SSOException e) {
        e.printStackTrace();
    } catch (IdRepoException e) {
        e.printStackTrace();
    }
    return attributeValue;
}

From source file:org.ambraproject.journal.JournalServiceTest.java

@Test(dataProvider = "articles", dependsOnMethods = { "getJournalTest", "getJournalByEissn" })
public void getJournalsForObjectTest(final String journalKey, final String doi) {
    Set<Journal> journals = journalService.getJournalsForObject(doi);
    assertNotNull(journals, "returned null set of journals");
    assertEquals(journals.size(), 1, "incorrect number of journals");
    assertEquals(((Journal) journals.toArray()[0]).getKey(), journalKey, "returned incorrect journal");
}