Example usage for java.util Queue isEmpty

List of usage examples for java.util Queue isEmpty

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this collection contains no elements.

Usage

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

protected void computeTargetShare(CurriculumClassification clasf, Collection<CurriculumCourse> courses,
        CurriculumCourseGroupsProvider course2groups, CurModel model) {
    for (CurriculumCourse c1 : courses) {
        double x1 = clasf.getNrStudents() * c1.getPercShare();
        Set<CurriculumCourse>[] group = new HashSet[] { new HashSet<CurriculumCourse>(),
                new HashSet<CurriculumCourse>() };
        Queue<CurriculumCourse> queue = new LinkedList<CurriculumCourse>();
        queue.add(c1);//from  w  w  w .j a  va2  s.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 = clasf.getNrStudents() * c2.getPercShare();
            if (c1.getUniqueId() >= c2.getUniqueId())
                continue;
            double share = 0;
            Set<WeightedStudentId> s1 = iProjectedDemands.getDemands(c1.getCourse());
            Set<WeightedStudentId> s2 = iProjectedDemands.getDemands(c2.getCourse());
            double sharedStudents = 0, lastLike = 0;
            if (s1 != null && !s1.isEmpty() && s2 != null && !s2.isEmpty()) {
                for (WeightedStudentId s : s1) {
                    if (s.match(clasf)) {
                        lastLike += s.getWeight();
                        if (s2.contains(s))
                            sharedStudents += s.getWeight();
                    }
                }
            }
            if (lastLike > 0) {
                double requested = c1.getPercShare() * clasf.getNrStudents();
                share = (requested / lastLike) * sharedStudents;
            } else {
                share = c1.getPercShare() * c2.getPercShare() * clasf.getNrStudents();
            }
            boolean opt = group[0].contains(c2);
            boolean req = !opt && group[1].contains(c2);
            model.setTargetShare(c1.getCourse().getUniqueId(), c2.getCourse().getUniqueId(),
                    opt ? 0.0 : req ? Math.min(x1, x2) : share, false);
        }
    }
}

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/*w  w w . j  av  a2  s.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:com.github.rinde.rinsim.core.model.road.GraphRoadModel.java

@Override
protected MoveProgress doFollowPath(MovingRoadUser object, Queue<Point> path, TimeLapse time) {
    final Loc objLoc = verifyLocation(objLocs.get(object));
    Loc tempLoc = objLoc;/*from w w  w. j a v  a2 s  .co m*/
    final MoveProgress.Builder mpBuilder = MoveProgress.builder(unitConversion, time);

    boolean cont = true;
    long timeLeft = time.getTimeLeft();
    while (timeLeft > 0 && !path.isEmpty() && cont) {
        checkMoveValidity(tempLoc, path.peek());
        // speed in internal speed unit
        final double speed = getMaxSpeed(object, tempLoc, path.peek());
        checkState(speed >= 0, "Found a bug in getMaxSpeed, return value must be >= 0, but is %s.", speed);
        // distance that can be traveled in current conn with timeleft
        final double travelableDistance = computeTravelableDistance(tempLoc, path.peek(), speed, timeLeft,
                time.getTimeUnit());
        checkState(travelableDistance >= 0d,
                "Found a bug in computeTravelableDistance, return value must be >= 0," + " but is %s.",
                travelableDistance);
        final double connLength = unitConversion.toInDist(computeDistanceOnConnection(tempLoc, path.peek()));
        checkState(connLength >= 0d,
                "Found a bug in computeDistanceOnConnection, return value must be " + ">= 0, but is %s.",
                connLength);

        double traveledDistance;
        if (travelableDistance >= connLength) {
            // jump to next node in path (this may be a node or a point on a
            // connection)
            tempLoc = verifyLocation(asLoc(path.remove()));
            traveledDistance = connLength;
            mpBuilder.addNode(tempLoc);
        } else {
            // travelableDistance < connLength
            cont = false;
            traveledDistance = travelableDistance;
            final Connection<?> conn = getConnection(tempLoc, path.peek());
            tempLoc = verifyLocation(
                    newLoc(conn, tempLoc.relativePos + unitConversion.toExDist(travelableDistance)));
        }
        mpBuilder.addDistance(traveledDistance);
        final long timeSpent = DoubleMath.roundToLong(
                unitConversion.toExTime(traveledDistance / speed, time.getTimeUnit()), RoundingMode.HALF_DOWN);
        timeLeft -= timeSpent;
    }
    time.consume(time.getTimeLeft() - timeLeft);
    // update location and construct a MoveProgress object
    objLocs.put(object, tempLoc);
    return mpBuilder.build();
}

From source file:candr.yoclip.Parser.java

/**
 * Creates a {@code ParsedOptionParameter} for the argument at the head of the queue. The value of the parsed option will contain the argument
 * value. The parsed option parameter will contain an error if the bean does not have an arguments annotation..
 *
 * @param parameters The current queue of command parameters.
 * @return a parsed option parameter or {@code null} if the parameters queue is empty.
 *///w  ww . j  a  va 2s.c  o  m
protected ParsedOption<T> getParsedArgument(final Queue<String> parameters) {

    ParsedOption<T> parsedOption = null;

    if (!parameters.isEmpty()) {

        final ParserOption<T> arguments = getParserOptions().getArguments();
        final String parameter = parameters.remove();

        if (null != arguments) {
            parsedOption = new ParsedOption<T>(arguments, parameter);
        } else {
            parsedOption = new ParsedOption<T>(getParserOptions().getName() + " does not have arguments.");
        }
    }

    return parsedOption;
}

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);// www  .j  av  a2 s. co 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.apache.hadoop.corona.SchedulerForType.java

/**
 * Find the most over-scheduled session in the most over-scheduled pool.
 * Kill tasks from this session.//from   w w  w .  j ava 2 s  .  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: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   w  ww .  j  a  v  a 2 s .co  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.apache.hadoop.corona.SchedulerForType.java

/**
 * Try match one request to one node//from ww  w. j  a  v  a2s  .co m
 *
 * @param nodeWait Time to wait for node locality
 * @param rackWait Time to wait for rack locality
 * @return The pair contains a session id and a granted resource
 *         or null when no task can be scheduled
 */
private ScheduledPair scheduleOneTask(long nodeWait, long rackWait) {
    if (!nodeManager.existRunnableNodes(type)) {
        return null;
    }

    Queue<PoolGroupSchedulable> poolGroupQueue = poolGroupManager.getScheduleQueue();
    while (!poolGroupQueue.isEmpty()) {
        PoolGroupSchedulable poolGroup = poolGroupQueue.poll();
        if (poolGroup.reachedMaximum()) {
            continue;
        }
        // Get the appropriate pool from the pool group to schedule, then
        // schedule the best session
        Queue<PoolSchedulable> poolQueue = poolGroup.getScheduleQueue();
        while (!poolQueue.isEmpty()) {
            PoolSchedulable pool = poolQueue.poll();
            if (pool.reachedMaximum()) {
                continue;
            }
            Queue<SessionSchedulable> sessionQueue = pool.getScheduleQueue();
            while (!sessionQueue.isEmpty()) {
                SessionSchedulable schedulable = sessionQueue.poll();
                Session session = schedulable.getSession();
                long now = ClusterManager.clock.getTime();
                MatchedPair pair = doMatch(schedulable, now, nodeWait, rackWait);
                synchronized (session) {
                    if (session.isDeleted()) {
                        continue;
                    }
                    if (pair != null) {
                        ResourceGrant grant = commitMatchedResource(session, pair);
                        if (grant != null) {
                            poolGroup.incGranted(1);
                            pool.incGranted(1);
                            schedulable.incGranted(1);
                            // Put back to the queue only if we scheduled successfully
                            poolGroupQueue.add(poolGroup);
                            poolQueue.add(pool);
                            sessionQueue.add(schedulable);
                            return new ScheduledPair(session.getSessionId().toString(), grant);
                        }
                    }
                }
            }
        }
    }
    return null;
}

From source file:it.geosolutions.geobatch.actions.commons.CollectorAction.java

/**
 * Removes TemplateModelEvents from the queue and put
 *///from   w  w w  .j  a v a 2 s.c  om
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {

    listenerForwarder.started();
    listenerForwarder.setTask("build the output absolute file name");

    // return
    final Queue<EventObject> ret = new LinkedList<EventObject>();

    listenerForwarder.setTask("Building/getting the root data structure");

    if (conf.getWildcard() == null) {
        LOGGER.warn("Null wildcard: using default\'*\'");
        conf.setWildcard("*");
    }

    it.geosolutions.tools.io.file.Collector collector = new it.geosolutions.tools.io.file.Collector(
            new WildcardFileFilter(conf.getWildcard(), IOCase.INSENSITIVE), conf.getDeep());
    while (!events.isEmpty()) {

        final EventObject event = events.remove();
        if (event == null) {
            // TODO LOG
            continue;
        }
        File source = null;
        if (event.getSource() instanceof File) {
            source = ((File) event.getSource());
        }

        if (source == null || !source.exists()) {
            // LOG
            continue;
        }
        listenerForwarder.setTask("Collecting from" + source);

        List<File> files = collector.collect(source);
        if (files == null) {
            return ret;
        }
        for (File file : files) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Collected file: " + file);
            }
            ret.add(new FileSystemEvent(file, FileSystemEventType.FILE_ADDED));
        }

    }
    listenerForwarder.completed();
    return ret;
}

From source file:password.pwm.util.report.ReportService.java

private void updateCacheFromLdap() throws ChaiUnavailableException, ChaiOperationException,
        PwmOperationalException, PwmUnrecoverableException {
    LOGGER.debug(PwmConstants.REPORTING_SESSION_LABEL,
            "beginning process to updating user cache records from ldap");
    if (status != STATUS.OPEN) {
        return;/*from   w w  w  . ja v a 2  s  .  c o  m*/
    }
    cancelFlag = false;
    reportStatus = new ReportStatusInfo(settings.getSettingsHash());
    reportStatus.setInProgress(true);
    reportStatus.setStartDate(new Date());
    try {
        final Queue<UserIdentity> allUsers = new LinkedList<>(getListOfUsers());
        reportStatus.setTotal(allUsers.size());
        while (status == STATUS.OPEN && !allUsers.isEmpty() && !cancelFlag) {
            final long startUpdateTime = System.currentTimeMillis();
            final UserIdentity userIdentity = allUsers.poll();
            try {
                if (updateCache(userIdentity)) {
                    reportStatus.setUpdated(reportStatus.getUpdated() + 1);
                }
            } catch (Exception e) {
                String errorMsg = "error while updating report cache for " + userIdentity.toString()
                        + ", cause: ";
                errorMsg += e instanceof PwmException ? ((PwmException) e).getErrorInformation().toDebugStr()
                        : e.getMessage();
                final ErrorInformation errorInformation;
                errorInformation = new ErrorInformation(PwmError.ERROR_REPORTING_ERROR, errorMsg);
                LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, errorInformation.toDebugStr());
                reportStatus.setLastError(errorInformation);
                reportStatus.setErrors(reportStatus.getErrors() + 1);
            }
            reportStatus.setCount(reportStatus.getCount() + 1);
            reportStatus.getEventRateMeter().markEvents(1);
            final long totalUpdateTime = System.currentTimeMillis() - startUpdateTime;
            if (settings.isAutoCalcRest()) {
                avgTracker.addSample(totalUpdateTime);
                Helper.pause(avgTracker.avgAsLong());
            } else {
                Helper.pause(settings.getRestTime().getTotalMilliseconds());
            }
        }
        if (cancelFlag) {
            reportStatus.setLastError(
                    new ErrorInformation(PwmError.ERROR_SERVICE_NOT_AVAILABLE, "report cancelled by operator"));
        }
    } finally {
        reportStatus.setFinishDate(new Date());
        reportStatus.setInProgress(false);
    }
    LOGGER.debug(PwmConstants.REPORTING_SESSION_LABEL,
            "update user cache process completed: " + JsonUtil.serialize(reportStatus));
}