Example usage for java.util Set clear

List of usage examples for java.util Set clear

Introduction

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

Prototype

void clear();

Source Link

Document

Removes all of the elements from this set (optional operation).

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//www. j  a va2s . 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.qrmedia.commons.persistence.hibernate.clone.HibernateEntityGraphClonerWorkflowItest.java

@Test
public void clone_saveAsNew() {
    // use get rather than load to get associated collections
    Pet garfield = (Pet) session.get(Pet.class, garfieldId);
    Pet garfieldClone = entityGraphCloner.clone(garfield);
    session.evict(garfield);/*w  w w . j av a2 s .c  o m*/

    // we want the same owner, not a copy
    garfieldClone.getOwner().setId(garfield.getOwner().getId());

    // modify the business key of the entity
    garfieldClone.getNicknames().add("Fat boy");

    // the clone will have its own set of toys
    Set<Toy> garfieldCloneToys = garfieldClone.getToys();
    garfieldCloneToys.clear();

    String newToyProductName = "Paddington Bear";
    Toy cuddlyBear = new Toy(newToyProductName, 0);
    garfieldCloneToys.add(cuddlyBear);

    session.save(garfieldClone);
    flushAndEvict(garfieldClone);

    // load the persisted object and compare
    Pet newPet = loadEntity(Pet.class, garfieldClone.getId());
    assertEquals(garfieldClone, newPet);
    assertFalse("Expected different objects", newPet.equals(garfield));
    assertEquals(garfield.getNicknames().size() + 1, newPet.getNicknames().size());
    assertTrue(CollectionUtils.isEqualCollection(Arrays.asList(cuddlyBear), newPet.getToys()));

    // check that the original object still exists and hasn't been modified
    Pet originalGarfield = loadEntity(Pet.class, garfieldId);
    assertEquals(garfield.getNicknames(), originalGarfield.getNicknames());
    assertEquals(garfield.getToys(), originalGarfield.getToys());

    // check that a new object has been created
    assertEquals(2, session.createQuery("from Pet where species = ?").setParameter(0, garfield.getSpecies())
            .list().size());
}

From source file:ml.shifu.shifu.core.dvarsel.wrapper.ValidationConductorTest.java

public void testPartershipModel() throws IOException {
    ModelConfig modelConfig = CommonUtils.loadModelConfig(
            "/Users/zhanhu/temp/partnership_varselect/ModelConfig.json", RawSourceData.SourceType.LOCAL);
    List<ColumnConfig> columnConfigList = CommonUtils.loadColumnConfigList(
            "/Users/zhanhu/temp/partnership_varselect/ColumnConfig.json", RawSourceData.SourceType.LOCAL);

    List<Integer> columnIdList = new ArrayList<Integer>();
    boolean hasCandidates = CommonUtils.hasCandidateColumns(columnConfigList);
    for (ColumnConfig columnConfig : columnConfigList) {
        if (CommonUtils.isGoodCandidate(columnConfig, hasCandidates)) {
            columnIdList.add(columnConfig.getColumnNum());
        }/*from  ww w.ja v  a 2  s.  c o  m*/
    }

    TrainingDataSet trainingDataSet = new TrainingDataSet(columnIdList);
    List<String> recordsList = IOUtils
            .readLines(new FileInputStream("/Users/zhanhu/temp/partnership_varselect/part-m-00479"));
    for (String record : recordsList) {
        addNormalizedRecordIntoTrainDataSet(modelConfig, columnConfigList, trainingDataSet, record);
    }

    Set<Integer> workingList = new HashSet<Integer>();
    for (Integer columnId : trainingDataSet.getDataColumnIdList()) {
        workingList.clear();
        workingList.add(columnId);
        ValidationConductor conductor = new ValidationConductor(modelConfig, columnConfigList, workingList,
                trainingDataSet);

        double error = conductor.runValidate();
        System.out.println("The error is - " + error + ", for columnId - " + columnId);
    }
}

From source file:com.spectralogic.ds3client.metadata.MetadataAccessImpl_Test.java

@Test
public void testGettingMetadata() throws IOException, InterruptedException {
    final String tempPathPrefix = null;
    final Path tempDirectory = Files.createTempDirectory(Paths.get("."), tempPathPrefix);

    final String fileName = "Gracie.txt";

    try {/*from www.j a v  a2s  . co  m*/
        final Path filePath = Files.createFile(Paths.get(tempDirectory.toString(), fileName));

        if (!Platform.isWindows()) {
            final PosixFileAttributes attributes = Files.readAttributes(filePath, PosixFileAttributes.class);
            final Set<PosixFilePermission> permissions = attributes.permissions();
            permissions.clear();
            permissions.add(PosixFilePermission.OWNER_READ);
            permissions.add(PosixFilePermission.OWNER_WRITE);
            Files.setPosixFilePermissions(filePath, permissions);
        }

        final ImmutableMap.Builder<String, Path> fileMapper = ImmutableMap.builder();
        fileMapper.put(filePath.toString(), filePath);
        final Map<String, String> metadata = new MetadataAccessImpl(fileMapper.build())
                .getMetadataValue(filePath.toString());

        if (Platform.isWindows()) {
            assertEquals(metadata.size(), 13);
        } else {
            assertEquals(metadata.size(), 10);
        }

        if (Platform.isMac()) {
            assertTrue(metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_OS)
                    .toLowerCase().startsWith(Platform.MAC_SYSTEM_NAME));
        } else if (Platform.isLinux()) {
            assertTrue(metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_OS)
                    .toLowerCase().startsWith(Platform.LINUX_SYSTEM_NAME));
        } else if (Platform.isWindows()) {
            assertTrue(metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_OS)
                    .toLowerCase().startsWith(Platform.WINDOWS_SYSTEM_NAME));
        }

        if (Platform.isWindows()) {
            assertEquals("A",
                    metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_FLAGS));
        } else {
            assertEquals("100600",
                    metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_MODE));
            assertEquals("600(rw-------)",
                    metadata.get(MetadataKeyConstants.METADATA_PREFIX + MetadataKeyConstants.KEY_PERMISSION));
        }
    } finally {
        FileUtils.deleteDirectory(tempDirectory.toFile());
    }
}

From source file:ml.shifu.shifu.core.dvarsel.wrapper.ValidationConductorTest.java

@Test
public void testRunValidate() throws IOException {
    ModelConfig modelConfig = CommonUtils.loadModelConfig(
            "src/test/resources/example/cancer-judgement/ModelStore/ModelSet1/ModelConfig.json",
            RawSourceData.SourceType.LOCAL);
    List<ColumnConfig> columnConfigList = CommonUtils.loadColumnConfigList(
            "src/test/resources/example/cancer-judgement/ModelStore/ModelSet1/ColumnConfig.json",
            RawSourceData.SourceType.LOCAL);

    List<Integer> columnIdList = new ArrayList<Integer>();
    boolean hasCandidates = CommonUtils.hasCandidateColumns(columnConfigList);
    for (ColumnConfig columnConfig : columnConfigList) {
        if (columnConfig.isCandidate(hasCandidates)) {
            columnIdList.add(columnConfig.getColumnNum());
        }/*from ww w  .  j  ava2 s  .co m*/
    }

    TrainingDataSet trainingDataSet = new TrainingDataSet(columnIdList);
    List<String> recordsList = IOUtils.readLines(
            new FileInputStream("src/test/resources/example/cancer-judgement/DataStore/DataSet1/part-00"));
    for (String record : recordsList) {
        addRecordIntoTrainDataSet(modelConfig, columnConfigList, trainingDataSet, record);
    }

    Set<Integer> workingList = new HashSet<Integer>();
    for (Integer columnId : trainingDataSet.getDataColumnIdList()) {
        workingList.clear();
        workingList.add(columnId);
        ValidationConductor conductor = new ValidationConductor(modelConfig, columnConfigList, workingList,
                trainingDataSet);

        double error = conductor.runValidate();
        System.out.println("The error is - " + error + ", for columnId - " + columnId);
    }
}

From source file:com.sonymobile.jenkins.plugins.lenientshutdown.PluginImpl.java

/**
 * Actually sets the node offline or prepares it to be leniently and then later offline.
 *
 * @param computer the computer./*from ww w.  j a va 2 s .c  om*/
 */
public void setNodeOffline(final Computer computer) {
    if (computer == null) {
        return;
    }
    final Node node = computer.getNode();
    if (node == null) {
        return;
    }
    if (QueueUtils.isBuilding(computer) || QueueUtils.hasNodeExclusiveItemInQueue(computer)) {
        //Doing some work; we want to take offline leniently
        final String nodeName = node.getNodeName();
        toggleNodeShuttingDown(nodeName);
        setOfflineByUser(nodeName, User.current());

        ExecutorService service = new SecurityContextExecutorService(Executors.newSingleThreadExecutor());
        service.submit(new Runnable() {
            @Override
            public void run() {
                Set<Long> permittedQueuedItemIds = getPermittedQueuedItemIds(nodeName);
                permittedQueuedItemIds.clear();
                permittedQueuedItemIds.addAll(QueueUtils.getPermittedQueueItemIds(nodeName));
                permittedQueuedItemIds.addAll(QueueUtils.getRunninProjectsQueueIDs(nodeName));
            }
        });

    } else { //No builds; we can take offline directly
        User currentUser = User.current();
        if (currentUser == null) {
            currentUser = User.getUnknown();
        }
        computer.setTemporarilyOffline(true, new LenientOfflineCause(currentUser));
    }
}

From source file:com.l2jfree.network.mmocore.AbstractSelectorThread.java

@Override
public final void run() {
    // main loop//from w ww  . j  a  v  a  2  s  .co  m
    for (;;) {
        final long begin = System.nanoTime();

        try {
            cleanup();

            // check for shutdown
            if (isShuttingDown()) {
                close();
                return;
            }

            try {
                if (getSelector().selectNow() > 0) {
                    Set<SelectionKey> keys = getSelector().selectedKeys();

                    for (SelectionKey key : keys) {
                        handle(key);
                    }

                    keys.clear();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }

            cleanup();
        } finally {
            RunnableStatsManager.handleStats(getClass(), "selectNow()", System.nanoTime() - begin);
        }

        try {
            Thread.sleep(getSleepTime());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

static <E> Set<E> ungrowableSet(final Set<E> s) {
    return new Set<E>() {

        @Override/*from  w  w w  .j  a v a2s .  c o m*/
        public int size() {
            return s.size();
        }

        @Override
        public boolean isEmpty() {
            return s.isEmpty();
        }

        @Override
        public boolean contains(Object o) {
            return s.contains(o);
        }

        @Override
        public Object[] toArray() {
            return s.toArray();
        }

        @Override
        public <T> T[] toArray(T[] a) {
            return s.toArray(a);
        }

        @Override
        public String toString() {
            return s.toString();
        }

        @Override
        public Iterator<E> iterator() {
            return s.iterator();
        }

        @Override
        public boolean equals(Object o) {
            return s.equals(o);
        }

        @Override
        public int hashCode() {
            return s.hashCode();
        }

        @Override
        public void clear() {
            s.clear();
        }

        @Override
        public boolean remove(Object o) {
            return s.remove(o);
        }

        @Override
        public boolean containsAll(Collection<?> coll) {
            return s.containsAll(coll);
        }

        @Override
        public boolean removeAll(Collection<?> coll) {
            return s.removeAll(coll);
        }

        @Override
        public boolean retainAll(Collection<?> coll) {
            return s.retainAll(coll);
        }

        @Override
        public boolean add(E o) {
            throw new UnsupportedOperationException();
        }

        @Override
        public boolean addAll(Collection<? extends E> coll) {
            throw new UnsupportedOperationException();
        }

    };

}

From source file:com.chadekin.jadys.syntax.from.impl.FromClauseBuilderImpl.java

private void attachRelatedActiveAliases(Set<String> aliases) {
    Set<String> foundAliases = Sets.newHashSet(aliases);
    while (!foundAliases.isEmpty()) {
        Set<String> result = Sets.difference(findRelatedAlias(foundAliases), aliases);
        foundAliases.clear();
        foundAliases.addAll(result);//from  ww  w.j av a  2s. c om
        aliases.addAll(result);
    }
}

From source file:org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.java

/**
 * It filters out brokers which owns topic higher than configured threshold at
 * {@link ServiceConfiguration.loadBalancerBrokerMaxTopics}. <br/>
 * if all the brokers own topic higher than threshold then it resets the list with original broker candidates
 *
 * @param brokerCandidateCache/*from   w ww.  ja  va2  s  .c o  m*/
 * @param loadData
 * @param loadBalancerBrokerMaxTopics
 */
public static void filterBrokersWithLargeTopicCount(Set<String> brokerCandidateCache, LoadData loadData,
        int loadBalancerBrokerMaxTopics) {
    Set<String> filteredBrokerCandidates = brokerCandidateCache.stream().filter((broker) -> {
        BrokerData brokerData = loadData.getBrokerData().get(broker);
        long totalTopics = brokerData != null && brokerData.getPreallocatedBundleData() != null
                ? brokerData.getPreallocatedBundleData().values().stream()
                        .mapToLong((preAllocatedBundle) -> preAllocatedBundle.getTopics()).sum()
                        + brokerData.getLocalData().getNumTopics()
                : 0;
        return totalTopics <= loadBalancerBrokerMaxTopics;
    }).collect(Collectors.toSet());

    if (!filteredBrokerCandidates.isEmpty()) {
        brokerCandidateCache.clear();
        brokerCandidateCache.addAll(filteredBrokerCandidates);
    }
}