Example usage for java.util Deque add

List of usage examples for java.util Deque add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque) 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:com.spotify.helios.agent.QueueingHistoryWriter.java

private void add(TaskStatusEvent item) throws InterruptedException {
    // If too many "globally", toss them
    while (count.get() >= MAX_TOTAL_SIZE) {
        getNext();//from  ww w.  java 2 s .co  m
    }

    final JobId key = item.getStatus().getJob().getId();
    final Deque<TaskStatusEvent> deque = getDeque(key);

    synchronized (deque) {
        // if too many in the particular deque, toss them
        while (deque.size() >= MAX_QUEUE_SIZE) {
            deque.remove();
            count.decrementAndGet();
        }
        deque.add(item);
        count.incrementAndGet();
    }

    try {
        backingStore.set(items);
    } catch (ClosedByInterruptException e) {
        log.debug("Writing task status event to backing store was interrupted");
    } catch (IOException e) { // We are best effort after all...
        log.warn("Failed to write task status event to backing store", e);
    }
}

From source file:uniol.apt.adt.automaton.FiniteAutomatonUtility.java

static private Set<State> followEpsilons(Set<State> states) {
    Set<State> result = new HashSet<>(states);
    Deque<State> unhandled = new LinkedList<>(result);
    while (!unhandled.isEmpty()) {
        State state = unhandled.removeFirst();
        for (State newState : state.getFollowingStates(Symbol.EPSILON)) {
            if (result.add(newState))
                unhandled.add(newState);
        }/*w w  w .  j a v a  2s. c  o m*/
    }

    return result;
}

From source file:specminers.evaluation.RandoopGeneratedTestParser.java

private void loadTestMethods() {
    this.testMethods = new LinkedList<>();
    this.testMethodDetails = new HashMap<>();
    String testMethodRegularExpressionDeclaration = "^public\\svoid\\stest(\\d+)\\(\\).+$";

    Deque<String> openBraces = new ArrayDeque<>();
    String currentMethod = null;//from  w  w  w.j  a  v  a  2s .c  o m
    List<String> statementsBeforeTryCatch = null;
    String currentClass = "";
    boolean foundTryCatchForCurrentTestMethod = false;
    String firstVarFound = "";
    String varRegex = "var\\d+\\W";
    Pattern p = Pattern.compile(varRegex);

    for (int i = 0; i < lines.size(); i++) {
        String line = lines.get(i);

        if (line.matches(testMethodRegularExpressionDeclaration)) {
            openBraces.add("{");
            currentMethod = StringHelper.extractSingleValueWithRegex(line,
                    testMethodRegularExpressionDeclaration, 1);
            statementsBeforeTryCatch = new LinkedList<>();
            foundTryCatchForCurrentTestMethod = false;
        } else {
            if (currentMethod != null) {
                if (line.contains("try {")) {
                    foundTryCatchForCurrentTestMethod = true;
                }

                if (!line.contains("if (debug) { System.out.println();")) {
                    Matcher m = p.matcher(line);

                    if (m.find()) {
                        if (!foundTryCatchForCurrentTestMethod) {
                            if (StringUtils.isEmpty(firstVarFound)) {
                                firstVarFound = m.group(0).trim();
                            }

                            if (line.contains(firstVarFound)) {

                                if (line.contains(firstVarFound + " = new java.")) {
                                    int startIndex = line.indexOf("new") + 3;
                                    int endIndex = line.indexOf("(", startIndex);
                                    try {
                                        currentClass = line.substring(startIndex, endIndex);
                                        statementsBeforeTryCatch.add((currentClass + ".<init>()").trim());
                                    } catch (StringIndexOutOfBoundsException ex) {
                                        System.out.println("Error parsing line " + line + " startIndex "
                                                + startIndex + " endIndex " + endIndex + " from java file "
                                                + javaFile.getAbsolutePath() + " current test method test"
                                                + currentMethod);
                                    }
                                } else {
                                    if (line.contains(firstVarFound + ".")) {
                                        int startIndex = line.indexOf(firstVarFound + ".") + 4;
                                        int endIndex = line.lastIndexOf("(");
                                        String calledMethod = "";
                                        calledMethod = line.substring(startIndex, endIndex);
                                        statementsBeforeTryCatch.add(currentClass + calledMethod
                                                + (calledMethod.endsWith("(") ? "" : "(") + ")");

                                    }
                                }
                            }
                        }
                    }
                    for (int j = 0; j < line.length(); j++) {
                        if (line.charAt(j) == '{') {
                            openBraces.add("{");
                        }
                        if (line.charAt(j) == '}') {
                            if (!openBraces.isEmpty()) {
                                openBraces.pop();
                            }
                        }
                    }
                }

                if (openBraces.isEmpty()) {
                    String testMethodStatements = statementsBeforeTryCatch.stream().map(st -> st.trim())
                            .collect(Collectors.joining(""));
                    Map<String, String> currentTestDetails = new HashMap<>();
                    currentTestDetails.put("foundTryCatch", foundTryCatchForCurrentTestMethod + "");
                    currentTestDetails.put("statementsBeforeTryCatch", testMethodStatements);

                    if (StringUtils.isNotBlank(currentMethod)) {
                        testMethodDetails.put(currentMethod, currentTestDetails);
                    }

                    currentMethod = null;
                    statementsBeforeTryCatch.clear();
                    ;
                    foundTryCatchForCurrentTestMethod = false;
                    firstVarFound = null;
                    // Prepare for new method
                }
            }
        }
    }

}

From source file:org.jasig.resource.aggr.ResourcesAggregatorImpl.java

/**
 * Iterate over the list of {@link BasicInclude} sub-classes using the {@link AggregatorCallback#willAggregate(BasicInclude, BasicInclude)}
 * and {@link AggregatorCallback#aggregate(Deque)} to generate an aggregated list of {@link BasicInclude} sub-classes.
 *///from   w w w.  j a  v a 2s .  co m
protected <T extends BasicInclude> List<T> aggregateBasicIncludes(List<T> original,
        AggregatorCallback<T> callback) throws IOException {
    final List<T> result = new LinkedList<T>();
    final Deque<T> currentAggregateList = new LinkedList<T>();
    for (final T originalElement : original) {
        // handle first loop iteration
        if (currentAggregateList.isEmpty()) {
            currentAggregateList.add(originalElement);
        } else {
            // test if 'originalElement' will aggregate with head element in currentAggregate 
            final T baseElement = currentAggregateList.getFirst();
            if (callback.willAggregate(originalElement, baseElement)) {
                // matches current criteria, add to currentAggregate
                currentAggregateList.add(originalElement);
            } else {
                // doesn't match criteria
                // generate new single aggregate from currentAggregateList
                final T aggregate = callback.aggregate(currentAggregateList);
                if (null != aggregate) {
                    // push result
                    result.add(aggregate);
                } else {
                    this.logger
                            .warn("Generated 0 byte aggregate from: " + generatePathList(currentAggregateList));
                }

                // zero out currentAggregateList
                currentAggregateList.clear();

                // add originalElement to empty list
                currentAggregateList.add(originalElement);
            }
        }
    }

    // flush the currentAggregateList
    if (currentAggregateList.size() > 0) {
        final T aggregate = callback.aggregate(currentAggregateList);
        if (null != aggregate) {
            result.add(aggregate);
        } else {
            this.logger.warn("Generated 0 byte aggregate from: " + generatePathList(currentAggregateList));
        }
    }

    return result;
}

From source file:org.marketcetera.marketdata.core.webservice.impl.MarketDataServiceImpl.java

/**
 * Gets the most recent snapshot for the given attributes.
 *
 * @param inInstrument an <code>Instrument</code> value
 * @param inContent a <code>Content</code> value
 * @param inProvider a <code>String</code> value or <code>null</code>
 * @return a <code>Deque&lt;Event&gt;</code> value
 *//*  w ww . j a va 2s .c o m*/
private Deque<Event> doGetSnapshot(Instrument inInstrument, Content inContent, String inProvider) {
    Event event = marketDataManager.requestMarketDataSnapshot(inInstrument, inContent, inProvider);
    if (event == null) {
        return new LinkedList<>();
    }
    Deque<Event> eventsToReturn = Lists.newLinkedList();
    if (event instanceof AggregateEvent) {
        eventsToReturn.addAll(((AggregateEvent) event).decompose());
    } else {
        eventsToReturn.add(event);
    }
    return eventsToReturn;
}

From source file:org.marketcetera.marketdata.core.webservice.impl.MarketDataServiceImpl.java

/**
 * Gets the requested page of the most recent snapshot for the given attribute.
 *
 * @param inInstrument an <code>Instrument</code> value
 * @param inContent a <code>Content</code> value
 * @param inProvider a <code>String</code> value or <code>null</code>
 * @param inPageRequest a <code>PageRequest</code> value
 * @return a <code>Deque&lt;Event&gt;</code> value
 *//*from  www  . j av a 2  s. c  om*/
private Deque<Event> doGetSnapshotPage(Instrument inInstrument, Content inContent, String inProvider,
        PageRequest inPageRequest) {
    Event event = marketDataManager.requestMarketDataSnapshot(inInstrument, inContent, inProvider);
    if (event == null) {
        return new LinkedList<>();
    }
    Deque<Event> eventsToReturn = Lists.newLinkedList();
    if (event instanceof AggregateEvent) {
        eventsToReturn.addAll(((AggregateEvent) event).decompose());
    } else {
        eventsToReturn.add(event);
    }
    // TODO pick out page
    return eventsToReturn;
}

From source file:com.ebay.pulsar.metric.processor.MetricProcessor.java

@Override
public void sendEvent(JetstreamEvent event) throws EventException {
    incrementEventRecievedCounter();//from  w ww  . j  a  va2s .  c  o  m
    String eventType = event.getEventType();

    Deque<DataPoint> dataByType = dataBuffer.get(eventType);
    if (dataByType == null) {
        dataByType = new ConcurrentLinkedDeque<DataPoint>();
        dataBuffer.put(eventType, dataByType);
    }

    Long currentTimestamp = System.currentTimeMillis();
    boolean isNewBatchOfEvents = false;

    if (dataByType.size() > 0
            && event.get("context_id") != dataByType.getLast().getEvents().peek().get("context_id"))
        isNewBatchOfEvents = true;

    //Flush old batchs
    if (isNewBatchOfEvents) {
        broadcastEventsByType(eventType, dataByType);
        incrementEventSentCounter();
    }

    if (dataByType.size() == 0 || isNewBatchOfEvents) {
        DataPoint dataPoint = new DataPoint(currentTimestamp);
        dataByType.add(dataPoint);
    }

    dataByType.getLast().addEvent(event);
    int maxLength = GENERIC_MAX_POINT;
    if (eventType.equalsIgnoreCase("MC_Metric") || eventType.equalsIgnoreCase("TwitterEventCount")) {
        maxLength = PAGE_VIEWS_POINT;
    }
    if (dataByType.size() > maxLength) {
        dataByType.removeFirst();
    }
}

From source file:ict.ocrabase.main.java.client.bulkload.LoadHFiles.java

/**
 * Walk the given directory for all HFiles, and return a Queue
 * containing all such files./*ww w. j a  va  2  s. co m*/
 */
private Deque<LoadQueueItem> discoverLoadQueue(Path hfofDir) throws IOException {
    FileSystem fs = hfofDir.getFileSystem(getConf());

    if (!fs.exists(hfofDir)) {
        throw new FileNotFoundException("HFileOutputFormat dir " + hfofDir + " not found");
    }

    FileStatus[] familyDirStatuses = fs.listStatus(hfofDir);
    if (familyDirStatuses == null) {
        throw new FileNotFoundException("No families found in " + hfofDir);
    }

    Deque<LoadQueueItem> ret = new LinkedList<LoadQueueItem>();
    for (FileStatus stat : familyDirStatuses) {
        if (!stat.isDir()) {
            LOG.warn("Skipping non-directory " + stat.getPath());
            continue;
        }
        Path familyDir = stat.getPath();
        // Skip _logs, etc
        if (familyDir.getName().startsWith("_"))
            continue;
        byte[] family = familyDir.getName().getBytes();
        Path[] hfiles = FileUtil.stat2Paths(fs.listStatus(familyDir));
        for (Path hfile : hfiles) {
            if (hfile.getName().startsWith("_"))
                continue;
            ret.add(new LoadQueueItem(family, hfile));
        }
    }
    return ret;
}

From source file:org.apache.hadoop.hbase.master.balancer.StochasticLoadBalancer.java

/**
 * Store the current region loads.//w  w  w  .j ava2 s .  co m
 */
private synchronized void updateRegionLoad() {
    // We create a new hashmap so that regions that are no longer there are removed.
    // However we temporarily need the old loads so we can use them to keep the rolling average.
    Map<String, Deque<RegionLoad>> oldLoads = loads;
    loads = new HashMap<String, Deque<RegionLoad>>();

    for (ServerName sn : clusterStatus.getServers()) {
        ServerLoad sl = clusterStatus.getLoad(sn);
        if (sl == null) {
            continue;
        }
        for (Entry<byte[], RegionLoad> entry : sl.getRegionsLoad().entrySet()) {
            Deque<RegionLoad> rLoads = oldLoads.get(Bytes.toString(entry.getKey()));
            if (rLoads == null) {
                // There was nothing there
                rLoads = new ArrayDeque<RegionLoad>();
            } else if (rLoads.size() >= 15) {
                rLoads.remove();
            }
            rLoads.add(entry.getValue());
            loads.put(Bytes.toString(entry.getKey()), rLoads);

        }
    }

    for (CostFromRegionLoadFunction cost : regionLoadFunctions) {
        cost.setLoads(loads);
    }
}

From source file:amfservices.actions.PGServicesAction.java

public Map<String, Object> takeRandomizePrizeAction(String uid, long now) {
    UserTempData uTempData = UserTempData.getTempData(uid);

    int nTurn = PGHelper.toInteger(uTempData.getData(PGMacro.RAND_PRIZE_TURN));
    PGException.Assert(nTurn > 0, PGError.NOT_ENOUGH_RP_TURN, "You have 0 turn");

    // reduce turn
    --nTurn;//from w w  w  .  ja  va2 s.c o  m
    uTempData.setData(PGMacro.RAND_PRIZE_TURN, nTurn);

    String prizeID = PGConfig.inst().getRandomizePrizes().randomPrize();

    CFRandomizePrize.Prize prizeData = PGConfig.inst().getRandomizePrizes().get(prizeID);
    if (prizeData.isAutoPrize()) {
        PGPrize prize = PrizeFactory.getPrize(prizeData.getPrize());
        EntityContext context = EntityContext.getContext(uid);
        Map<String, Object> pzDesc = prize.award(context, now);
        context.saveToDB();

        // find total gold prized:
        Deque<Map<String, Object>> pzStack = new ArrayDeque();
        int totalGoldPrized = 0;
        pzStack.add(prizeData.getPrize());
        while (!pzStack.isEmpty()) {
            Map<String, Object> pz = pzStack.pollLast();
            for (Map.Entry<String, Object> pzEntry : pz.entrySet()) {
                String pzKey = pzEntry.getKey();
                Object pzVal = pzEntry.getValue();

                if (pzVal instanceof Map) {
                    pzStack.addLast((Map) pzVal);
                } else if ("gold".equals(pzKey)) {
                    totalGoldPrized += PGHelper.toInteger(pzVal);
                }
            }
        }

        if (totalGoldPrized > 0) {
            QuestLogger qLogger = QuestServices.inst().getQuestLogger(uid, now);
            qLogger.log(new GoldDialRecord(totalGoldPrized));
        }

        return AMFBuilder.make(PGMacro.RAND_PRIZE_ID, prizeID, PGMacro.PRIZE, pzDesc);
    } else {
        String giftID = GiftServices.inst().sendGift(Arrays.asList(new String[] { uid }), prizeData.getPrize(),
                now, PGConfig.inst().temp().RandomizePrize_Expire()).getGiftID();

        return AMFBuilder.make(PGMacro.RAND_PRIZE_ID, prizeID, PGMacro.GIFT_ID, giftID);
    }
}