Example usage for java.util Set iterator

List of usage examples for java.util Set iterator

Introduction

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

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this set.

Usage

From source file:com.nesscomputing.syslog4j.Syslog.java

/**
 * shutdown() gracefully shuts down all defined Syslog protocols,
 * which includes flushing all queues and connections and finally
 * clearing all instances (including those initialized by default).
 *//* www  .j a v a 2s. c o m*/
public synchronized static void shutdown() {
    Set<String> protocols = instances.keySet();

    if (protocols.size() > 0) {
        Iterator<String> i = protocols.iterator();

        SyslogUtility.sleep(SyslogConstants.THREAD_LOOP_INTERVAL_DEFAULT);

        while (i.hasNext()) {
            String protocol = i.next();

            SyslogIF syslog = instances.get(protocol);

            syslog.shutdown();
        }

        instances.clear();
    }
}

From source file:grakn.core.util.GraqlTestUtil.java

public static Thing getInstance(TransactionOLTP tx, String id) {
    Set<Thing> things = tx.getAttributesByValue(id).stream().flatMap(Attribute::owners).collect(toSet());
    if (things.size() != 1) {
        throw new IllegalStateException("Multiple things with given resource value");
    }//from   w  ww . ja v a 2  s .  co m
    return things.iterator().next();
}

From source file:gov.nih.nci.ncicb.cadsr.common.util.SessionUtils.java

public static void setPreviousSessionValues(HttpServletRequest request) {
    String previousSessionId = request.getParameter(CaDSRConstants.PREVIOUS_SESSION_ID);
    log.error("SessionUtil.setPreviousSessionValues at :" + TimeUtils.getEasternTime());

    synchronized (sessionObjectCache) {
        log.error("SessionUtil.setPreviousSessionValues(synchronized Start) at :" + TimeUtils.getEasternTime());
        if (previousSessionId != null) {
            Map map = (Map) SessionUtils.sessionObjectCache.get(previousSessionId);
            Set keys = (Set) map.get(CaDSRConstants.GLOBAL_SESSION_KEYS);
            Map objectMap = (Map) map.get(CaDSRConstants.GLOBAL_SESSION_MAP);
            if (keys != null && objectMap != null) {
                Iterator keyIt = keys.iterator();
                while (keyIt.hasNext()) {
                    String key = (String) keyIt.next();
                    Object obj = objectMap.get(key);
                    request.getSession().setAttribute(key, obj);
                }// w  ww  .  j ava  2 s  . c om
            }
            log.error(
                    "SessionUtil.setPreviousSessionValues(synchronized End) at :" + TimeUtils.getEasternTime());
        }
    }
    log.error("SessionUtil.setPreviousSessionValues end at :" + TimeUtils.getEasternTime());
}

From source file:edu.uci.ics.jung.graph.impl.BipartiteGraph.java

/**
 * Creates a one-part graph from a bipartite graph by folding
 * Vertices from one class into a second class. This function
 * creates a new UndirectedGraph (with vertex set V') in which: <br>
 * <ul>/*from  w  ww .j  av a2s .c  o m*/
 * <li> each vertex in V' has an equivalent V in bpg.getAllVertices( class ) </li>
 * <li> an edge E' joins V'1 and V'2 iff there is a path of length 2 from
 * V1 to V2 (by way of some third vertex in the other class, VXs) </li>
 * <li> each edge E' is annotated with the set of vertices VXs </li>
 * </ul>
 * 
 * In social network analysis and related fields, this operation transforms
 * an actor-by-event chart into an actor-by-actor chart.
 * 
 * @param bpg      The bipartite graph to be folded
 * @param vertexSet      Chooses the set of vertices to be brought into
 *                the new Graph.
 * @return   an UndirectedSparseGraph.
 */
public static Graph fold(BipartiteGraph bpg, Choice vertexSet) {
    Graph newGraph = new UndirectedSparseGraph();
    Set vertices = bpg.getAllVertices(vertexSet);
    for (Iterator iter = vertices.iterator(); iter.hasNext();) {
        BipartiteVertex v = (BipartiteVertex) iter.next();
        v.copy(newGraph);
    }

    Set coveredNodes = new HashSet();

    for (Iterator iter = vertices.iterator(); iter.hasNext();) {
        BipartiteVertex v = (BipartiteVertex) iter.next();
        coveredNodes.add(v);

        // the set of all Bs that touch this A
        Set hyperEdges = v.getNeighbors();

        // this will ultimately contain a mapping from
        // the next adjacent "A" to the list of "B"s that support that
        // connection (that is, all Bs that run between this A and its neighbor
        MultiMap mm = new MultiHashMap();
        for (Iterator iterator = hyperEdges.iterator(); iterator.hasNext();) {
            Vertex hyperEdge = (Vertex) iterator.next();
            addAll(mm, hyperEdge.getNeighbors(), hyperEdge);
        }
        for (Iterator iterator = mm.keySet().iterator(); iterator.hasNext();) {
            Vertex aVertex = (Vertex) iterator.next();

            if (coveredNodes.contains(aVertex))
                continue;

            Edge newEdge = GraphUtils.addEdge(newGraph, (Vertex) v.getEqualVertex(newGraph),
                    (Vertex) aVertex.getEqualVertex(newGraph));
            newEdge.addUserDatum(BIPARTITE_USER_TAG, mm.get(aVertex), UserData.SHARED);
        }
    }
    return newGraph;
}

From source file:com.examples.with.different.packagename.ClassHierarchyIncludingInterfaces.java

public static Iterable<Class<?>> hierarchy(final Class<?> type, final Interfaces interfacesBehavior) {
    final Iterable<Class<?>> classes = new Iterable<Class<?>>() {

        @Override//  w ww. j av  a2 s .  c  om
        public Iterator<Class<?>> iterator() {
            final MutableObject<Class<?>> next = new MutableObject<Class<?>>(type);
            return new Iterator<Class<?>>() {

                @Override
                public boolean hasNext() {
                    return next.getValue() != null;
                }

                @Override
                public Class<?> next() {
                    final Class<?> result = next.getValue();
                    next.setValue(result.getSuperclass());
                    return result;
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }

            };
        }

    };
    if (interfacesBehavior != Interfaces.INCLUDE) {
        return classes;
    }
    return new Iterable<Class<?>>() {

        @Override
        public Iterator<Class<?>> iterator() {
            final Set<Class<?>> seenInterfaces = new HashSet<Class<?>>();
            final Iterator<Class<?>> wrapped = classes.iterator();

            return new Iterator<Class<?>>() {
                Iterator<Class<?>> interfaces = Collections.<Class<?>>emptySet().iterator();

                @Override
                public boolean hasNext() {
                    return interfaces.hasNext() || wrapped.hasNext();
                }

                @Override
                public Class<?> next() {
                    if (interfaces.hasNext()) {
                        final Class<?> nextInterface = interfaces.next();
                        seenInterfaces.add(nextInterface);
                        return nextInterface;
                    }
                    final Class<?> nextSuperclass = wrapped.next();
                    final Set<Class<?>> currentInterfaces = new LinkedHashSet<Class<?>>();
                    walkInterfaces(currentInterfaces, nextSuperclass);
                    interfaces = currentInterfaces.iterator();
                    return nextSuperclass;
                }

                private void walkInterfaces(final Set<Class<?>> addTo, final Class<?> c) {
                    for (final Class<?> iface : c.getInterfaces()) {
                        if (!seenInterfaces.contains(iface)) {
                            addTo.add(iface);
                        }
                        walkInterfaces(addTo, iface);
                    }
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }

            };
        }
    };
}

From source file:it.jnrpe.server.CJNRPEServer.java

/**
 * Generates a simple configuration file
 * @param cl The command line/*  w  ww  . j a  va2 s  .co m*/
 */
private static void generateScheletonConfig(String sFilePath) {
    CStreamManager mgr = new CStreamManager();
    try {
        PrintWriter w = (PrintWriter) mgr
                .handle(new PrintWriter(new BufferedOutputStream(new FileOutputStream(new File(sFilePath)))));
        w.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        w.println("<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
                + "xsi:noNamespaceSchemaLocation=\"http://jnrpe.sourceforge.net/jnrpeConfig.xsd\">");
        w.println("  <!-- Main Server Configuration -->");
        w.println("  <server accept-params=\"true\">");
        w.println("  <!-- The following configuration, will bind to");
        w.println("  the 127.0.0.1 and will allow only local requests -->");
        w.println("    <bind address=\"127.0.0.1:5666\" SSL=\"false\"/>");
        w.println("    <allow ip=\"127.0.0.1\"/>");
        w.println("    <!-- The directory where all plugins resides");
        w.println("         is ./plugins - inside this directory you'll");
        w.println("         have one directory for each plugin. -->");
        w.println("    <plugin path=\"./plugins\"/>");
        w.println("  </server>");
        w.println("  <commands>");

        CPluginFactory factory = CPluginFactory.getInstance();

        Set vPlugins = factory.getPluginList();

        //for (String sPluginName : vPlugins)
        for (Iterator iter = vPlugins.iterator(); iter.hasNext();) {
            String sPluginName = (String) iter.next();
            CPluginProxy pp = factory.getPlugin(sPluginName);
            w.println("    <command name=\"" + sPluginName + "\" plugin_name=\"" + sPluginName + "\">");
            Collection vOptions = pp.getOptions();
            int i = 1;

            w.println("        <!-- WARNING!! -->");
            w.println(
                    "        <!-- Generated argument list, won't take care of mutually exclusive arguments! -->");
            for (Iterator iterator = vOptions.iterator(); iterator.hasNext();) {
                COption opt = (COption) iterator.next();
                w.print("        <arg name=\"" + opt.getLongOpt() + "\" ");
                if (opt.hasArgs())
                    w.print(" value=\"" + "$ARG" + i++ + "$\" ");
                w.println("/>");
            }
            w.println("    </command>");
        }

        w.println("  </commands>");
        w.println("</config>");
    } catch (Exception e) {
        System.out.println("ERROR GENERATING CONFIGURATION FILE : " + e.getMessage());
        System.exit(-1);
    } finally {
        mgr.closeAll();
    }

    System.out.println("FILE GENERATED SUCCESSFULLY");
    System.exit(0);
}

From source file:massbank.extend.ChemicalFormulaUtils.java

/**
 * qfL?/*from  ww  w. j  av  a2s .c om*/
 */
public static String swapFormula(String formula) {

    // fL?? C, H ?~At@xbg?
    String[] atomSequece = new String[] { "C", "H", "Cl", "F", "I", "N", "O", "P", "S", "Si" };
    Map<String, Integer> atomList = getAtomList(formula);
    String swapFormula = "";
    Set keys = atomList.keySet();
    for (int i = 0; i < atomSequece.length; i++) {
        for (Iterator iterator = keys.iterator(); iterator.hasNext();) {

            String atom = (String) iterator.next();
            int num = atomList.get(atom);

            if (atom.equals(atomSequece[i])) {
                swapFormula += atom;
                // ?1???A??
                if (num > 1) {
                    swapFormula += String.valueOf(num);
                }
                break;
            }
        }
    }
    return swapFormula;
}

From source file:Main.java

/**
 * <p>Generate reverse result</p>
 * @param allResult all result//from  w w w .  j av  a2 s  . com
 * @param partResult part result
 * @return reverse result
 */
public static <T extends Object> List<T> getReverseResult(Set<T> allResult, Set<T> partResult) {
    List<T> resultList = new ArrayList<T>();
    Map<T, T> map = new HashMap<T, T>();
    if (partResult != null) {
        for (T obj : partResult) {
            map.put(obj, obj);
        }
    }
    if (allResult != null) {
        Iterator<T> itor = allResult.iterator();
        while (itor.hasNext()) {
            T obj = itor.next();
            if (map.containsKey(obj)) {
                itor.remove();
            } else {
                resultList.add(obj);
            }
        }
    }
    return resultList;
}

From source file:com.javaid.bolaky.carpool.service.acl.userregistration.impl.UserRegistrationAclTranslator.java

public static UserVO convertToUserVO(Person person) {

    UserVO userVO = null;//ww w .jav  a2  s.  c om

    if (person != null) {

        userVO = new UserVO();

        userVO.setUsername(person.getUsername());
        userVO.setAgeGroup(
                person.getAgeGroup() != null ? AgeGroup.convertCode(person.getAgeGroup().getCode()) : null);
        userVO.setFirstname(person.getFirstname());
        userVO.setLastname(person.getLastname());
        userVO.setPassword(person.getPassword());
        userVO.setEmailAddress(
                person.getContactDetails() != null ? person.getContactDetails().getEmailAddresse() : null);
        userVO.setCarOwner(person.isAVehicleOwner());
        userVO.setValidLicense(person.hasValidLicense());
        userVO.setGender(person.getGender().getCode());

        Set<Address> addresses = person.getContactDetails() != null ? person.getContactDetails().getAddresses()
                : null;

        if (addresses != null) {

            Iterator<Address> iterator = addresses.iterator();

            if (iterator.hasNext()) {

                Address address = iterator.next();
                userVO.setCountryCode(address.getCountryCode());
                userVO.setAreaCode(address.getAreaCode());
                userVO.setDistrictCode(address.getDistrictCode());
                userVO.setAddressLine1(address.getAddressLine1());

            }
        }

        userVO.setPhoneNumber(
                person.getContactDetails() != null ? person.getContactDetails().getPhoneNumber() : null);
        userVO.setAllowToReceiveUpdates(
                person.getUserPreferences() != null ? person.getUserPreferences().isAllowToReceiveUpdates()
                        : null);
        userVO.setShareCost(person.canShareCost());
        userVO.setShareDriving(person.canShareDriving());

    }

    return userVO;
}

From source file:com.redhat.rhn.manager.ssm.SsmManager.java

/**
 * Given a list of servers and channels that should be subscribed, determines which
 * channels may be subscribed to by which servers. The mapping returned will be from
 * each server to a list of channels that may be subscribed. This list will not
 * be <code>null</code> but may be empty if no subscriptions are determined to be
 * allowed./*from w w  w .  j  av  a 2  s.  c  om*/
 *
 * @param user        user initiating the subscription
 * @param sysMapping     the map of ChannelActionDAO objects
 * @param allChannels channels to attempt to subscribe each server to; may not
 *                    be <code>null</code>
 * @return mapping of each server to a non-null (but potentially empty) list of
 *         channels that are safe to subscribe it to
 */
public static Map<Long, ChannelActionDAO> verifyChildEntitlements(User user,
        Map<Long, ChannelActionDAO> sysMapping, List<Channel> allChannels) {

    //Load all of the channels in a map for easy lookup
    Map<Long, Channel> idToChan = new HashMap<Long, Channel>();
    for (Channel c : allChannels) {
        idToChan.put(c.getId(), c);
    }

    // Keeps a mapping of how many entitlements are left on each channel. This map
    // will be updated as the processing continues, however changes won't be written
    // to the database until the actual subscriptions are made. This way we can keep
    // a more accurate representation of how many entitlements are left rather than
    // always loading the static value from the DB.
    Map<Channel, Long> channelToAvailableEntitlements = new HashMap<Channel, Long>(allChannels.size());

    for (Long sysid : sysMapping.keySet()) {

        Set<Long> chanIds = sysMapping.get(sysid).getSubscribeChannelIds();
        //Use an iterator so i can remove from the set
        Iterator it = chanIds.iterator();
        while (it.hasNext()) {
            Channel channel = idToChan.get(it.next());
            Long availableEntitlements = channelToAvailableEntitlements.get(channel);

            if (availableEntitlements == null) {
                availableEntitlements = ChannelManager.getAvailableEntitlements(user.getOrg(), channel);
                channelToAvailableEntitlements.put(channel, availableEntitlements);
            }
            //Most likely acustom channel1
            if (availableEntitlements == null) {
                continue;
            }
            if (availableEntitlements > 0) {
                // Update our cached count for what will happen when
                // the subscribe is done
                availableEntitlements = availableEntitlements - 1;
                channelToAvailableEntitlements.put(channel, availableEntitlements);
            } else {
                sysMapping.get(sysid).getSubscribeChannelIds().remove(channel.getId());
                sysMapping.get(sysid).getSubscribeNames().remove(channel.getName());
                if (sysMapping.get(sysid).isEmtpy()) {
                    sysMapping.remove(sysid);
                }
            }
        }
    }
    return sysMapping;
}