Example usage for java.util Queue add

List of usage examples for java.util Queue add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

Usage

From source file:org.onebusaway.uk.network_rail.gtfs_realtime.graph.PositionBerthToStanoxGraphMain.java

private void interpolateBerthLocations() {
    int index = 0;
    for (RawBerthNode rootNode : _berthNodesToLocations.keySet()) {
        if (index % 100 == 0) {
            _log.info("node=" + index + "/" + _berthNodesToLocations.keySet().size());
        }//from  w  ww.ja va2 s. c o m
        index++;
        Location fromLocation = _berthNodesToLocations.get(rootNode);
        Queue<OrderedRawBerthNode> queue = new PriorityQueue<OrderedRawBerthNode>();
        queue.add(new OrderedRawBerthNode(rootNode, null, 0.0));

        Map<RawBerthNode, RawBerthNode> parents = new HashMap<RawBerthNode, RawBerthNode>();
        Set<RawBerthNode> visited = new HashSet<RawBerthNode>();

        while (!queue.isEmpty()) {
            OrderedRawBerthNode currentNode = queue.poll();
            RawBerthNode node = currentNode.getNode();
            if (!visited.add(node)) {
                continue;
            }

            parents.put(node, currentNode.getParent());
            Location toLocation = _berthNodesToLocations.get(node);
            if (currentNode.getParent() != null && toLocation != null) {

                List<RawBerthNode> path = new ArrayList<RawBerthNode>();
                RawBerthNode last = node;
                while (last != null) {
                    path.add(last);
                    last = parents.get(last);
                }

                if (path.size() <= 2) {
                    break;
                }
                Collections.reverse(path);
                BerthPath berthPath = new BerthPath(path, currentNode.getDistance());
                double d = fromLocation.getDistance(toLocation);
                if (d > 30000) {
                    continue;
                }
                RailwayPath railwayPath = _railwayShapeService.getPath(fromLocation.getPoint(),
                        toLocation.getPoint());
                if (railwayPath != null) {
                    snapBerthsToRailwayPath(berthPath, railwayPath);
                }
                break;
            } else {
                for (Map.Entry<RawBerthNode, List<Integer>> entry : node.getOutgoing().entrySet()) {
                    RawBerthNode outgoing = entry.getKey();
                    int avgDuration = RawNode.average(entry.getValue());
                    queue.add(new OrderedRawBerthNode(outgoing, node, currentNode.getDistance() + avgDuration));
                }
            }
        }
    }
}

From source file:com.barchart.http.server.TestHttpServer.java

@Test
public void testTooManyConnections() throws Exception {

    final Queue<Integer> status = new LinkedBlockingQueue<Integer>();

    final Runnable r = new Runnable() {
        @Override// w ww. j  a  va2s  . c om
        public void run() {
            try {
                final HttpResponse response = client
                        .execute(new HttpGet("http://localhost:" + port + "/client-disconnect"));
                status.add(response.getStatusLine().getStatusCode());
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    };

    final Thread t1 = new Thread(r);
    t1.start();

    final Thread t2 = new Thread(r);
    t2.start();

    t1.join();
    t2.join();

    assertEquals(2, status.size());
    assertTrue(status.contains(200));
    assertTrue(status.contains(503));

}

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);
        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);
        }//from  ww w .  j  a  va 2s.c om
        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:org.openengsb.labs.paxexam.karaf.container.internal.KarafTestContainer.java

/**
 * Since we might get quite deep use a simple breath first search algorithm
 *///from   w w  w.  java 2s .  c  om
private File searchKarafBase(File targetFolder) {
    Queue<File> searchNext = new LinkedList<File>();
    searchNext.add(targetFolder);
    while (!searchNext.isEmpty()) {
        File head = searchNext.poll();
        if (!head.isDirectory()) {
            continue;
        }
        boolean system = false;
        boolean etc = false;
        for (File file : head.listFiles()) {
            if (file.isDirectory() && file.getName().equals("system")) {
                system = true;
            }
            if (file.isDirectory() && file.getName().equals("etc")) {
                etc = true;
            }
        }
        if (system && etc) {
            return head;
        }
        searchNext.addAll(Arrays.asList(head.listFiles()));
    }
    throw new IllegalStateException("No karaf base dir found in extracted distribution.");
}

From source file:org.apache.karaf.tooling.exam.container.internal.KarafTestContainer.java

/**
 * Since we might get quite deep use a simple breath first search algorithm
 *///from w  ww .  j av a 2s .  com
private File searchKarafBase(File _targetFolder) {
    Queue<File> searchNext = new LinkedList<File>();
    searchNext.add(_targetFolder);
    while (!searchNext.isEmpty()) {
        File head = searchNext.poll();
        if (!head.isDirectory()) {
            continue;
        }
        boolean isSystem = false;
        boolean etc = false;
        for (File file : head.listFiles()) {
            if (file.isDirectory() && file.getName().equals("system")) {
                isSystem = true;
            }
            if (file.isDirectory() && file.getName().equals("etc")) {
                etc = true;
            }
        }
        if (isSystem && etc) {
            return head;
        }
        searchNext.addAll(Arrays.asList(head.listFiles()));
    }
    throw new IllegalStateException("No karaf base dir found in extracted distribution.");
}

From source file:de.huberlin.wbi.hiway.logstats.LogParser.java

private void expandHiwayEvents() throws JSONException {
    Queue<JsonReportEntry> execQ = new LinkedList<>();
    Map<String, JsonReportEntry> allocatedMap = new HashMap<>();
    Queue<JsonReportEntry> completedQ = new LinkedList<>();

    for (JsonReportEntry entry : entries) {
        switch (entry.getKey()) {
        case JsonReportEntry.KEY_INVOC_EXEC:
            execQ.add(entry);
            break;
        case JsonReportEntry.KEY_INVOC_TIME:
            JsonReportEntry completed = completedQ.remove();
            JSONObject value = completed.getValueJsonObj();
            JsonReportEntry allocated = allocatedMap.get(value.getString("container-id"));
            expandEntry(completed, entry);
            expandEntry(allocated, entry);
            break;
        case HiwayDBI.KEY_HIWAY_EVENT:
            value = entry.getValueJsonObj();
            switch (value.getString("type")) {
            case "container-requested":
                expandEntry(entry, execQ.remove());
                break;
            case "container-allocated":
                allocatedMap.put(value.getString("container-id"), entry);
                break;
            case "container-completed":
                completedQ.add(entry);//  w w w .  j a v a2 s . com
                break;
            default:
            }
            break;
        default:
        }
    }
}

From source file:com.navercorp.pinpoint.web.calltree.span.CallTreeIteratorTest.java

private Queue<Integer> parseExpected(String expectedValues) {
    if (expectedValues == null) {
        return null;
    }/*from w w w  . ja va2  s  .  c  o m*/

    String[] tokens = expectedValues.split(",");
    Queue<Integer> expected = new LinkedBlockingQueue<Integer>();
    for (String token : tokens) {
        expected.add(Integer.parseInt(token.trim()));
    }

    return expected;
}

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);
        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);
        }//from w ww . ja  v a 2  s . c  om
        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:azkaban.jobtype.AzkabanPigListener.java

@Override
public void initialPlanNotification(String scriptId, MROperPlan plan) {
    logger.info("**********initialPlanNotification!**********");

    // First pass: generate dagNodeNameMap.
    Map<OperatorKey, MapReduceOper> planKeys = plan.getKeys();
    for (Map.Entry<OperatorKey, MapReduceOper> entry : planKeys.entrySet()) {
        String nodeName = entry.getKey().toString();
        String[] aliases = toArray(ScriptState.get().getAlias(entry.getValue()).trim());
        String[] features = toArray(ScriptState.get().getPigFeature(entry.getValue()).trim());

        PigJobDagNode node = new PigJobDagNode(nodeName, aliases, features);
        this.dagNodeNameMap.put(node.getName(), node);

        // This shows how we can get the basic info about all nameless jobs 
        // before any execute. We can traverse the plan to build a DAG of this 
        // info.// w  w  w  .  j  av  a 2s  . c om
        logger.info("initialPlanNotification: aliases: " + StringUtils.join(aliases, ",") + ", name: "
                + node.getName() + ", features: " + StringUtils.join(features, ","));
    }

    // Second pass: connect the edges
    for (Map.Entry<OperatorKey, MapReduceOper> entry : planKeys.entrySet()) {
        PigJobDagNode node = this.dagNodeNameMap.get(entry.getKey().toString());
        List<String> successorNodeList = new ArrayList<String>();
        List<MapReduceOper> successors = plan.getSuccessors(entry.getValue());
        if (successors != null) {
            for (MapReduceOper successor : successors) {
                PigJobDagNode successorNode = this.dagNodeNameMap.get(successor.getOperatorKey().toString());
                successorNodeList.add(successorNode.getName());
                successorNode.addParent(node);
            }
        }
        node.setSuccessors(successorNodeList);
    }

    // Third pass: find roots.
    Queue<PigJobDagNode> parentQueue = new LinkedList<PigJobDagNode>();
    Queue<PigJobDagNode> childQueue = new LinkedList<PigJobDagNode>();
    for (Map.Entry<String, PigJobDagNode> entry : this.dagNodeNameMap.entrySet()) {
        PigJobDagNode node = entry.getValue();
        if (node.getParents().isEmpty()) {
            node.setLevel(0);
            parentQueue.add(node);
        }
    }

    // Final pass: BFS to set levels.
    int level = 0;
    Set<PigJobDagNode> visited = new HashSet<PigJobDagNode>();
    while (parentQueue.peek() != null) {
        PigJobDagNode node = null;
        while ((node = parentQueue.poll()) != null) {
            if (visited.contains(node)) {
                continue;
            }
            node.setLevel(level);
            for (String jobName : node.getSuccessors()) {
                PigJobDagNode successorNode = this.dagNodeNameMap.get(jobName);
                childQueue.add(successorNode);
            }
        }

        Queue<PigJobDagNode> tmp = childQueue;
        childQueue = parentQueue;
        parentQueue = tmp;
        ++level;
    }

    updateJsonFile();
}

From source file:org.siddhiesb.transport.passthru.DeliveryAgent.java

/**
 * This method queues the message for delivery. If a connection is already existing for
 * the destination epr, the message will be delivered immediately. Otherwise message has
 * to wait until a connection is established. In this case this method will inform the
 * system about the need for a connection.
 *
 * @param commonContext the message context to be sent
 *//*from  w w  w .j  a v  a  2 s.  c o  m*/
public void submit(CommonContext commonContext) {
    try {

        String toAddress = (String) commonContext.getProperty(CommonAPIConstants.ENDPOINT);
        URL url = new URL(toAddress);
        String scheme = url.getProtocol() != null ? url.getProtocol() : "http";
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equalsIgnoreCase(target.getSchemeName());

        HttpHost proxy = null; //proxyConfig.selectProxy(target);

        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }

        // first we queue the message
        Queue<CommonContext> queue = null;
        lock.lock();
        try {
            queue = waitingMessages.get(route);
            if (queue == null) {
                queue = new ConcurrentLinkedQueue<CommonContext>();
                waitingMessages.put(route, queue);
            }
            if (queue.size() == maxWaitingMessages) {
                CommonContext msgCtx = queue.poll();
            }

            queue.add(commonContext);
        } finally {
            lock.unlock();
        }

        NHttpClientConnection conn = targetConnections.getConnection(route);
        if (conn != null) {
            conn.resetInput();
            conn.resetOutput();
            CommonContext commonContext1 = queue.poll();

            if (commonContext1 != null) {
                tryNextMessage(commonContext1, route, conn);
            }
        }

    } catch (MalformedURLException e) {
        handleException("Malformed URL in the target EPR", e);
    }
}