Example usage for java.util Queue poll

List of usage examples for java.util Queue poll

Introduction

In this page you can find the example usage for java.util Queue poll.

Prototype

E poll();

Source Link

Document

Retrieves and removes the head of this queue, or returns null if this queue is empty.

Usage

From source file:eu.europeana.enrichment.common.Utils.java

private static Set<String> getClassNamesPackage(String pckgname) throws ClassNotFoundException, IOException {
    // This will hold a list of directories matching the pckgname. There may
    // be//from  w  ww  . ja  va 2s.  c  o  m
    // more than one if a package is split over multiple jars/paths
    Queue<File> directories = new LinkedList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        String path = pckgname.replace('.', '/');
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(path);
        while (resources.hasMoreElements()) {
            directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname);
    }

    Set<String> classes = new HashSet<String>();
    // For every directory identified capture all the .class files
    while (!directories.isEmpty()) {
        File directory = directories.poll();
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                // we are only interested in .class files
                if (file.getCanonicalPath().endsWith(".class")) {
                    String fileName = file.getPath().substring(directory.getPath().length() + 1);
                    pckgname = file.getPath()
                            .substring(file.getPath().indexOf(File.separator + "nl" + File.separator) + 1);
                    pckgname = pckgname.substring(0, pckgname.lastIndexOf(File.separator))
                            .replaceAll("\\" + File.separator, ".");
                    // if (!fileName.matches("(.+)\\$\\d\\.class"))
                    // removes the .class extension
                    classes.add(fileName.substring(0, fileName.length() - 6));
                }
                // Add subdirs
                if (file.isDirectory()) {
                    directories.add(file);
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}

From source file:org.rhq.core.plugin.testutil.AbstractAgentPluginTest.java

/**
 * Test that executes all the no arg operations for all the subresources of a provided resource.
 * Notes:/*from  ww w  .ja v a  2 s . com*/
 * 1) no operations are executed on the root resource provided.
 * 2) if a resource is ignored then all of subresource of that resources are ignored
 *
 * @param rootResource root resource
 * @param ignoredResources resources to be ignored
 * @param ignoredOperations operations to be ignored
 * @throws PluginContainerException
 */
protected void executeNoArgOperations(Resource rootResource, List<String> ignoredResources,
        List<String> ignoredOperations) throws PluginContainerException {

    ignoredResources = (ignoredResources == null) ? new ArrayList<String>() : ignoredResources;
    ignoredOperations = (ignoredOperations == null) ? new ArrayList<String>() : ignoredOperations;

    Queue<Resource> unparsedResources = new LinkedList<Resource>();
    addCommitedChildrenToCollection(unparsedResources, rootResource, ignoredResources);

    while (!unparsedResources.isEmpty()) {
        Resource resourceUnderTest = unparsedResources.poll();

        addCommitedChildrenToCollection(unparsedResources, resourceUnderTest, ignoredResources);

        for (OperationDefinition operationUnderTest : resourceUnderTest.getResourceType()
                .getOperationDefinitions()) {
            if (!ignoredOperations.contains(operationUnderTest.getName())) {
                if (operationUnderTest.getParametersConfigurationDefinition() == null || operationUnderTest
                        .getParametersConfigurationDefinition().getPropertyDefinitions().isEmpty()) {
                    this.invokeOperationAndAssertSuccess(resourceUnderTest, operationUnderTest.getName(),
                            new Configuration());
                }
            }
        }
    }
}

From source file:org.unitime.timetable.solver.curricula.CurriculaRequestsCourseDemands.java

protected void computeTargetShare(CurriculumClassification clasf, Collection<CurriculumCourse> courses,
        CurriculumCourseGroupsProvider course2groups, int nrStudents, double factor, double w, CurModel model) {
    for (CurriculumCourse c1 : courses) {
        double x1 = model.getCourse(c1.getCourse().getUniqueId()).getOriginalMaxSize();
        Set<CurriculumCourse>[] group = new HashSet[] { new HashSet<CurriculumCourse>(),
                new HashSet<CurriculumCourse>() };
        Queue<CurriculumCourse> queue = new LinkedList<CurriculumCourse>();
        queue.add(c1);//from ww  w .  ja va2s.c o  m
        Set<CurriculumCourseGroup> done = new HashSet<CurriculumCourseGroup>();
        while (!queue.isEmpty()) {
            CurriculumCourse c = queue.poll();
            for (CurriculumCourseGroup g : course2groups.getGroups(c))
                if (done.add(g))
                    for (CurriculumCourse x : courses)
                        if (!x.equals(c) && !x.equals(c1) && course2groups.getGroups(x).contains(g)
                                && group[group[0].contains(c) ? 0 : g.getType()].add(x))
                            queue.add(x);
        }
        for (CurriculumCourse c2 : courses) {
            double x2 = model.getCourse(c2.getCourse().getUniqueId()).getOriginalMaxSize();
            boolean opt = group[0].contains(c2);
            boolean req = !opt && group[1].contains(c2);
            double defaultShare = (opt ? 0.0
                    : req ? Math.min(x1, x2) : c1.getPercShare() * c2.getPercShare() * nrStudents);
            if (c1.getUniqueId() >= c2.getUniqueId())
                continue;
            double share = defaultShare;
            Set<WeightedStudentId> s1 = iStudentCourseRequests.getDemands(c1.getCourse());
            Set<WeightedStudentId> s2 = iStudentCourseRequests.getDemands(c2.getCourse());
            int sharedStudents = 0, registered = 0;
            if (s1 != null && !s1.isEmpty() && s2 != null && !s2.isEmpty()) {
                for (WeightedStudentId s : s1) {
                    if (s.match(clasf)) {
                        registered++;
                        if (s2.contains(s))
                            sharedStudents++;
                    }
                }
            }
            if (registered == 0) {
                share = (1.0 - w) * defaultShare;
            } else {
                share = w * (x1 / registered) * sharedStudents + (1.0 - w) * defaultShare;
            }
            model.setTargetShare(c1.getCourse().getUniqueId(), c2.getCourse().getUniqueId(), share, false);
        }
    }
}

From source file:org.hyperic.hq.product.JDBCMeasurementPlugin.java

protected Connection getCachedConnection(String url, String user, String pass) throws SQLException {
    String cacheKey = calculateKey(url, user, pass);
    Connection conn;//from   ww w . jav a 2s.  co  m
    Queue<Connection> pool;

    synchronized (connectionPools) {
        pool = connectionPools.get(cacheKey);
        if (pool == null) {
            pool = new ConcurrentLinkedQueue<Connection>();
            connectionPools.put(cacheKey, pool);
            log.debug("[getCC] Pool for '" + cacheKey + "' created");
        }
    }

    int count = 0;
    while (((conn = pool.poll()) == null) && (count++ < 5)) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            log.error(ex, ex);
        }
    }

    if (conn == null) {
        conn = getConnection(url, user, pass);
        log.debug("[getCC] Connection for '" + cacheKey + "' created (pool.size=" + pool.size() + ")");
    }
    log.debug("[getCC] Connection for '" + cacheKey + "' used (pool.size=" + pool.size() + ")");
    return conn;
}

From source file:eu.annocultor.common.Utils.java

private static Set<String> getClassNamesPackage(String pckgname) throws ClassNotFoundException, IOException {
    // This will hold a list of directories matching the pckgname. There may be
    // more than one if a package is split over multiple jars/paths
    Queue<File> directories = new LinkedList<File>();
    try {/*from   ww  w . ja  va2  s  . c  o m*/
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        String path = pckgname.replace('.', '/');
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(path);
        while (resources.hasMoreElements()) {
            directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname);
    }

    Set<String> classes = new HashSet<String>();
    // For every directory identified capture all the .class files
    while (!directories.isEmpty()) {
        File directory = directories.poll();
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                // we are only interested in .class files
                if (file.getCanonicalPath().endsWith(".class")) {
                    String fileName = file.getPath().substring(directory.getPath().length() + 1);
                    pckgname = file.getPath()
                            .substring(file.getPath().indexOf(File.separator + "nl" + File.separator) + 1);
                    pckgname = pckgname.substring(0, pckgname.lastIndexOf(File.separator))
                            .replaceAll("\\" + File.separator, ".");
                    // if (!fileName.matches("(.+)\\$\\d\\.class"))
                    // removes the .class extension
                    classes.add(fileName.substring(0, fileName.length() - 6));
                }
                // Add subdirs
                if (file.isDirectory()) {
                    directories.add(file);
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}

From source file:org.protempa.backend.ksb.protege.ProtegeKnowledgeSourceBackend.java

private Collection<String> collectPropDescendantsInt(boolean inDataSourceOnly, boolean narrower,
        String[] propIds) throws KnowledgeSourceReadException {
    assert propIds != null : "propIds cannot be null";
    Slot inverseIsASlot = this.cm.getSlot("inverseIsA");
    Slot abstractedFromSlot = this.cm.getSlot("abstractedFrom");
    Slot inDataSourceSlot = this.cm.getSlot("inDataSource");
    Set<String> result = new HashSet<>();
    Queue<Instance> queue = new LinkedList<>();
    for (String propId : propIds) {
        Instance instance = this.cm.getInstance(propId);
        if (instance == null) {
            throw new KnowledgeSourceReadException("unknown proposition id " + propId);
        } else {//  ww  w  . ja va 2  s. co m
            queue.add(instance);
        }
    }
    while (!queue.isEmpty()) {
        Instance instance = queue.poll();
        if (inDataSourceOnly) {
            Boolean inDataSource = (Boolean) this.cm.getOwnSlotValue(instance, inDataSourceSlot);
            if (inDataSource != null && inDataSource.booleanValue()) {
                result.add(instance.getName());
            }
        } else {
            result.add(instance.getName());
        }
        Collection<?> inverseIsAs = this.cm.getOwnSlotValues(instance, inverseIsASlot);
        for (Object obj : inverseIsAs) {
            queue.add((Instance) obj);
        }
        Collection<?> abstractedFroms = narrower ? this.cm.getOwnSlotValues(instance, abstractedFromSlot)
                : Collections.emptyList();
        for (Object obj : abstractedFroms) {
            queue.add((Instance) obj);
        }
    }
    return result;
}

From source file:sadl.models.pdrta.PDRTA.java

public void checkConsistency() {

    // Checking that a path for each sequence exists
    for (int i = 0; i < input.getAlphSize(); i++) {
        final Set<Entry<Integer, Interval>> ins = root.getIntervals(i).entrySet();
        for (final Entry<Integer, Interval> eIn : ins) {
            final Set<Entry<Integer, TimedTail>> tails = eIn.getValue().getTails().entries();
            for (final Entry<Integer, TimedTail> eTail : tails) {
                TimedTail t = eTail.getValue();
                PDRTAState source = root, target;
                while (t != null) {
                    assert (source.getInterval(t.getSymbolAlphIndex(), t.getTimeDelay()).getTails()
                            .containsValue(t));
                    target = source.getTarget(t);
                    if (target == null) {
                        throw new IllegalStateException(
                                "The tail (" + input.getSymbol(t.getSymbolAlphIndex()) + "," + t.getTimeDelay()
                                        + ") has no transition from state ((" + source.getIndex() + "))!");
                    }/*  w w w. j a  va2 s  .  co m*/
                    source = target;
                    t = t.getNextTail();
                }
            }
        }
    }

    // Checking that number of states in structure is equal to number of states in map
    int counter = 0;
    final Set<PDRTAState> seen = new HashSet<>();
    seen.add(root);
    final Queue<PDRTAState> q = new LinkedList<>();
    q.add(root);
    while (!q.isEmpty()) {
        final PDRTAState s = q.poll();
        PDRTAState s2 = states.get(s.getIndex());
        if (s != s2) {
            throw new IllegalStateException("State (" + s.getIndex() + ") is not in map!");
        }
        counter++;
        for (int i = 0; i < input.getAlphSize(); i++) {
            final Set<Entry<Integer, Interval>> ins = s.getIntervals(i).entrySet();
            for (final Entry<Integer, Interval> eIn : ins) {
                s2 = eIn.getValue().getTarget();
                if (s2 != null && !seen.contains(s2)) {
                    seen.add(s2);
                    q.add(s2);
                }
            }
        }
    }
    if (counter != states.size()) {
        throw new IllegalStateException(
                "Found " + counter + " sates in structure but " + states.size() + " states are in map!");
    }
}

From source file:org.apache.hadoop.corona.SchedulerForType.java

/**
 * Find the most over-scheduled session in the most over-scheduled pool.
 * Kill tasks from this session./*from w ww.jav  a 2s .  c  o m*/
 * @param maxToPreemt The maximum number of tasks to kill
 * @param maxRunningTime The killed task cannot be older than this time
 * @return The number of tasks actually killed
 */
private int preemptOneSession(int maxToPreemt, long maxRunningTime) {
    Queue<PoolGroupSchedulable> poolGroupQueue = poolGroupManager.getPreemptQueue();
    while (!poolGroupQueue.isEmpty()) {
        PoolGroupSchedulable poolGroup = poolGroupQueue.poll();
        poolGroup.distributeShare();
        Queue<PoolSchedulable> poolQueue = poolGroup.getPreemptQueue();
        while (!poolQueue.isEmpty()) {
            PoolSchedulable pool = poolQueue.poll();
            pool.distributeShare();
            if (!pool.isPreemptable()) {
                continue;
            }
            Queue<SessionSchedulable> sessionQueue = pool.getPreemptQueue();
            while (!sessionQueue.isEmpty()) {
                SessionSchedulable schedulable = sessionQueue.poll();
                try {
                    int overScheduled = (int) (schedulable.getGranted() - schedulable.getShare());
                    if (overScheduled <= 0) {
                        continue;
                    }
                    maxToPreemt = Math.min(maxToPreemt, overScheduled);
                    LOG.info("Trying to preempt " + maxToPreemt + " " + type + " from "
                            + schedulable.getSession().getHandle());
                    int preempted = preemptSession(schedulable, maxToPreemt, maxRunningTime);
                    poolGroup.incGranted(-1 * preempted);
                    pool.incGranted(-1 * preempted);
                    schedulable.incGranted(-1 * preempted);
                    return preempted;
                } catch (InvalidSessionHandle e) {
                    LOG.warn("Invalid session handle:" + schedulable.getSession().getHandle()
                            + " Session may be removed");
                } finally {
                    // Add back the queue so it can be further preempt for other
                    // sessions.
                    poolGroupQueue.add(poolGroup);
                    poolQueue.add(pool);
                }
            }
        }
    }
    return 0;
}

From source file:org.grouplens.grapht.solver.DependencySolver.java

/**
 * Update the dependency graph to include the given desire. An edge from the
 * root node to the desire's resolved satisfaction will exist after this is
 * finished.// w  w  w  .ja  va2  s.c  om
 * 
 * @param desire The desire to include in the graph
 */
public synchronized void resolve(Desire desire) throws ResolutionException {
    logger.info("Resolving desire: {}", desire);

    Queue<Deferral> deferralQueue = new ArrayDeque<Deferral>();

    // before any deferred nodes are processed, we use a synthetic root
    // and null original desire since nothing produced this root
    deferralQueue.add(new Deferral(rootNode(), initialContext()));

    while (!deferralQueue.isEmpty()) {
        Deferral current = deferralQueue.poll();
        DAGNode<Component, Dependency> parent = current.node;
        // deferred nodes are either root - depless - or having deferred dependencies
        assert parent.getOutgoingEdges().isEmpty();

        if (current.node.getLabel().equals(ROOT_SATISFACTION)) {
            Pair<DAGNode<Component, Dependency>, Dependency> rootNode = resolveFully(desire, current.context,
                    deferralQueue);
            // add this to the global graph
            graph = DAGNode.copyBuilder(graph).addEdge(mergePool.merge(rootNode.getLeft()), rootNode.getRight())
                    .build();
        } else if (graph.getReachableNodes().contains(parent)) {
            // the node needs to be re-scanned.  This means that it was not consolidated by
            // a previous merge operation.  This branch only arises with provider injection.
            Satisfaction sat = parent.getLabel().getSatisfaction();
            for (Desire d : sat.getDependencies()) {
                logger.debug("Attempting to resolve deferred dependency {} of {}", d, sat);
                // resolve the dependency
                Pair<DAGNode<Component, Dependency>, Dependency> result = resolveFully(d, current.context,
                        deferralQueue);
                // merge it in
                DAGNode<Component, Dependency> merged = mergePool.merge(result.getLeft());
                // now see if there's a real cycle
                if (merged.getReachableNodes().contains(parent)) {
                    // parent node is referenced from merged, we have a circle!
                    // that means we need a back edge
                    backEdges.put(parent, DAGEdge.create(parent, merged, result.getRight()));
                } else {
                    // an edge from parent to merged does not add a cycle
                    // we have to update graph right away so it's available to merge the next
                    // dependency
                    DAGNode<Component, Dependency> newP = DAGNode.copyBuilder(parent)
                            .addEdge(merged, result.getRight()).build();
                    replaceNode(parent, newP);
                    parent = newP;
                }
            }
        } else {
            // node unreachable - it's a leftover or unneeded deferral
            logger.debug("node {} not in graph, ignoring", parent);
        }
    }
}