Example usage for java.util ArrayDeque ArrayDeque

List of usage examples for java.util ArrayDeque ArrayDeque

Introduction

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

Prototype

public ArrayDeque() 

Source Link

Document

Constructs an empty array deque with an initial capacity sufficient to hold 16 elements.

Usage

From source file:com.espertech.esper.core.EPRuntimeImpl.java

private void processMatches(EventBean event) {
    // get matching filters
    ArrayBackedCollection<FilterHandle> matches = matchesArrayThreadLocal.get();
    long version = services.getFilterService().evaluate(event, matches, engineFilterAndDispatchTimeContext);

    if (ThreadLogUtil.ENABLED_TRACE) {
        ThreadLogUtil.trace("Found matches for underlying ", matches.size(), event.getUnderlying());
    }/*from   www .j  av a 2 s .c om*/

    if (matches.size() == 0) {
        if (unmatchedListener != null) {
            unmatchedListener.update(event);
        }
        return;
    }

    Map<EPStatementHandle, ArrayDeque<FilterHandleCallback>> stmtCallbacks = matchesPerStmtThreadLocal.get();
    Object[] matchArray = matches.getArray();
    int entryCount = matches.size();

    for (int i = 0; i < entryCount; i++) {
        EPStatementHandleCallback handleCallback = (EPStatementHandleCallback) matchArray[i];
        EPStatementHandle handle = handleCallback.getEpStatementHandle();

        // Self-joins require that the internal dispatch happens after all streams are evaluated.
        // Priority or preemptive settings also require special ordering.
        if (handle.isCanSelfJoin() || isPrioritized) {
            ArrayDeque<FilterHandleCallback> callbacks = stmtCallbacks.get(handle);
            if (callbacks == null) {
                callbacks = new ArrayDeque<FilterHandleCallback>();
                stmtCallbacks.put(handle, callbacks);
            }
            callbacks.add(handleCallback.getFilterCallback());
            continue;
        }

        if ((MetricReportingPath.isMetricsEnabled) && (handle.getMetricsHandle().isEnabled())) {
            long cpuTimeBefore = MetricUtil.getCPUCurrentThread();
            long wallTimeBefore = MetricUtil.getWall();

            processStatementFilterSingle(handle, handleCallback, event, version);

            long wallTimeAfter = MetricUtil.getWall();
            long cpuTimeAfter = MetricUtil.getCPUCurrentThread();
            long deltaCPU = cpuTimeAfter - cpuTimeBefore;
            long deltaWall = wallTimeAfter - wallTimeBefore;
            services.getMetricsReportingService().accountTime(handle.getMetricsHandle(), deltaCPU, deltaWall,
                    1);
        } else {
            if ((ThreadingOption.isThreadingEnabled) && (services.getThreadingService().isRouteThreading())) {
                services.getThreadingService()
                        .submitRoute(new RouteUnitSingle(this, handleCallback, event, version));
            } else {
                processStatementFilterSingle(handle, handleCallback, event, version);
            }
        }
    }
    matches.clear();
    if (stmtCallbacks.isEmpty()) {
        return;
    }

    for (Map.Entry<EPStatementHandle, ArrayDeque<FilterHandleCallback>> entry : stmtCallbacks.entrySet()) {
        EPStatementHandle handle = entry.getKey();
        ArrayDeque<FilterHandleCallback> callbackList = entry.getValue();

        if ((MetricReportingPath.isMetricsEnabled) && (handle.getMetricsHandle().isEnabled())) {
            long cpuTimeBefore = MetricUtil.getCPUCurrentThread();
            long wallTimeBefore = MetricUtil.getWall();

            processStatementFilterMultiple(handle, callbackList, event, version);

            long wallTimeAfter = MetricUtil.getWall();
            long cpuTimeAfter = MetricUtil.getCPUCurrentThread();
            long deltaCPU = cpuTimeAfter - cpuTimeBefore;
            long deltaWall = wallTimeAfter - wallTimeBefore;
            services.getMetricsReportingService().accountTime(handle.getMetricsHandle(), deltaCPU, deltaWall,
                    callbackList.size());
        } else {
            if ((ThreadingOption.isThreadingEnabled) && (services.getThreadingService().isRouteThreading())) {
                services.getThreadingService()
                        .submitRoute(new RouteUnitMultiple(this, callbackList, event, handle, version));
            } else {
                processStatementFilterMultiple(handle, callbackList, event, version);
            }

            if ((isPrioritized) && (handle.isPreemptive())) {
                break;
            }
        }
    }
    stmtCallbacks.clear();
}

From source file:co.paralleluniverse.galaxy.core.Cache.java

@Override
@SuppressWarnings({ "BoxedValueEquality" })
public void receive(Message message) {
    if (recursive.get() != Boolean.TRUE) {
        recursive.set(Boolean.TRUE);
        try {//w ww  .j a  va  2s .  com
            LOG.debug("Received: {}", message);
            receive1(message);
            receiveShortCircuit();
        } finally {
            recursive.remove();
        }
    } else { // short-circuit
        LOG.debug("Received short-circuit: {}", message);
        Queue<Message> ms = shortCircuitMessage.get();
        if (ms == null) {
            ms = new ArrayDeque<Message>();
            shortCircuitMessage.set(ms);
        }
        ms.add(message);
    }
}

From source file:org.voltdb.iv2.LeaderAppointer.java

private boolean isClusterKSafe(Set<Integer> hostsOnRing) {
    boolean retval = true;
    List<String> partitionDirs = null;

    ImmutableSortedSet.Builder<KSafetyStats.StatsPoint> lackingReplication = ImmutableSortedSet.naturalOrder();

    try {/*from  w  ww  .j  ava2s .  c o m*/
        partitionDirs = m_zk.getChildren(VoltZK.leaders_initiators, null);
    } catch (Exception e) {
        VoltDB.crashLocalVoltDB("Unable to read partitions from ZK", true, e);
    }

    //Don't fetch the values serially do it asynchronously
    Queue<ZKUtil.ByteArrayCallback> dataCallbacks = new ArrayDeque<ZKUtil.ByteArrayCallback>();
    Queue<ZKUtil.ChildrenCallback> childrenCallbacks = new ArrayDeque<ZKUtil.ChildrenCallback>();
    for (String partitionDir : partitionDirs) {
        String dir = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
        try {
            ZKUtil.ByteArrayCallback callback = new ZKUtil.ByteArrayCallback();
            m_zk.getData(dir, false, callback, null);
            dataCallbacks.offer(callback);
            ZKUtil.ChildrenCallback childrenCallback = new ZKUtil.ChildrenCallback();
            m_zk.getChildren(dir, false, childrenCallback, null);
            childrenCallbacks.offer(childrenCallback);
        } catch (Exception e) {
            VoltDB.crashLocalVoltDB("Unable to read replicas in ZK dir: " + dir, true, e);
        }
    }
    final long statTs = System.currentTimeMillis();
    for (String partitionDir : partitionDirs) {
        int pid = LeaderElector.getPartitionFromElectionDir(partitionDir);

        String dir = ZKUtil.joinZKPath(VoltZK.leaders_initiators, partitionDir);
        try {
            // The data of the partition dir indicates whether the partition has finished
            // initializing or not. If not, the replicas may still be in the process of
            // adding themselves to the dir. So don't check for k-safety if that's the case.
            byte[] partitionState = dataCallbacks.poll().getData();
            boolean isInitializing = false;
            if (partitionState != null && partitionState.length == 1) {
                isInitializing = partitionState[0] == LeaderElector.INITIALIZING;
            }

            List<String> replicas = childrenCallbacks.poll().getChildren();
            if (pid == MpInitiator.MP_INIT_PID)
                continue;
            final boolean partitionNotOnHashRing = partitionNotOnHashRing(pid);
            if (!isInitializing && replicas.isEmpty()) {
                //These partitions can fail, just cleanup and remove the partition from the system
                if (partitionNotOnHashRing) {
                    removeAndCleanupPartition(pid);
                    continue;
                }
                tmLog.fatal("K-Safety violation: No replicas found for partition: " + pid);
                retval = false;
            } else if (!partitionNotOnHashRing) {
                //Record host ids for all partitions that are on the ring
                //so they are considered for partition detection
                for (String replica : replicas) {
                    final String split[] = replica.split("/");
                    final long hsId = Long.valueOf(split[split.length - 1].split("_")[0]);
                    final int hostId = CoreUtils.getHostIdFromHSId(hsId);
                    hostsOnRing.add(hostId);
                }
            }
            if (!isInitializing && !partitionNotOnHashRing) {
                lackingReplication
                        .add(new KSafetyStats.StatsPoint(statTs, pid, m_kfactor + 1 - replicas.size()));
            }
        } catch (Exception e) {
            VoltDB.crashLocalVoltDB("Unable to read replicas in ZK dir: " + dir, true, e);
        }
    }
    m_stats.setSafetySet(lackingReplication.build());

    return retval;
}

From source file:org.betaconceptframework.astroboa.engine.definition.visitor.CmsPropertyVisitor.java

private Deque<XSType> collectAllSuperTypesIncludingProvidedElement(XSElementDecl element) {

    Deque<XSType> types = new ArrayDeque<XSType>();

    XSType currentElement = element.getType();

    boolean elementIsContentObjectType = false;

    while (!elementIsContentObjectType) {

        elementIsContentObjectType = currentElement.getName() != null
                && CmsDefinitionItem.contentObjectType.equals(ItemUtils.createNewItem(null,
                        currentElement.getTargetNamespace(), currentElement.getName()));

        if (elementIsContentObjectType) {

            if (currentElement.isComplexType()) {
                types.push(currentElement);
            }//from  w  w  w  . jav  a2 s  .c om

            break; //Need to go no further
        } else {

            //Method getBaseType is always non-null.
            //According to the documentation, 
            //"Note that if this type represents xs:anyType, this method returns itself. "
            //Threrefore break loop if we come across to such case
            if (currentElement == currentElement.getBaseType()) {
                break;
            } else {
                if (currentElement.isComplexType()) {
                    types.push(currentElement);
                }

                currentElement = currentElement.getBaseType();
            }
        }
    }

    return types;

}

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;/*  w w w . j a  v  a 2  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);
    }
}

From source file:com.espertech.esper.core.EPRuntimeImpl.java

private ArrayDeque<FilterHandle> getCallbackList(EventBean event, String statementId) {
    ArrayDeque<FilterHandle> callbacks = new ArrayDeque<FilterHandle>();
    services.getFilterService().evaluate(event, callbacks, engineFilterAndDispatchTimeContext, statementId);
    return callbacks;
}

From source file:loci.formats.in.LIFReader.java

private void translateMetadata(Element root) throws FormatException {
    Element realRoot = (Element) root.getChildNodes().item(0);

    NodeList toPrune = getNodes(realRoot, "LDM_Block_Sequential_Master");
    if (toPrune != null) {
        for (int i = 0; i < toPrune.getLength(); i++) {
            Element prune = (Element) toPrune.item(i);
            Element parent = (Element) prune.getParentNode();
            parent.removeChild(prune);/*from  www .  j av  a 2 s .c  om*/
        }
    }

    NodeList images = getNodes(realRoot, "Image");
    List<Element> imageNodes = new ArrayList<Element>();
    Long[] oldOffsets = null;
    if (images.getLength() > offsets.size()) {
        oldOffsets = offsets.toArray(new Long[offsets.size()]);
        offsets.clear();
    }

    int nextOffset = 0;
    for (int i = 0; i < images.getLength(); i++) {
        Element image = (Element) images.item(i);
        Element grandparent = (Element) image.getParentNode();
        if (grandparent == null) {
            continue;
        }
        grandparent = (Element) grandparent.getParentNode();
        if (grandparent == null) {
            continue;
        }
        if (!"ProcessingHistory".equals(grandparent.getNodeName())) {
            // image is being referenced from an event list
            imageNodes.add(image);
            if (oldOffsets != null && nextOffset < oldOffsets.length) {
                offsets.add(oldOffsets[nextOffset]);
            }
        }
        grandparent = (Element) grandparent.getParentNode();
        if (grandparent == null) {
            continue;
        }
        grandparent = (Element) grandparent.getParentNode();
        if (grandparent != null) {
            if (!"Image".equals(grandparent.getNodeName())) {
                nextOffset++;
            }
        }
    }

    tileCount = new int[imageNodes.size()];
    Arrays.fill(tileCount, 1);
    core = new ArrayList<CoreMetadata>(imageNodes.size());
    acquiredDate = new double[imageNodes.size()];
    descriptions = new String[imageNodes.size()];
    laserWavelength = new List[imageNodes.size()];
    laserIntensity = new List[imageNodes.size()];
    laserActive = new List[imageNodes.size()];
    laserFrap = new List[imageNodes.size()];
    timestamps = new double[imageNodes.size()][];
    activeDetector = new List[imageNodes.size()];
    serialNumber = new String[imageNodes.size()];
    lensNA = new Double[imageNodes.size()];
    magnification = new Double[imageNodes.size()];
    immersions = new String[imageNodes.size()];
    corrections = new String[imageNodes.size()];
    objectiveModels = new String[imageNodes.size()];
    posX = new Length[imageNodes.size()];
    posY = new Length[imageNodes.size()];
    posZ = new Length[imageNodes.size()];
    refractiveIndex = new Double[imageNodes.size()];
    cutIns = new List[imageNodes.size()];
    cutOuts = new List[imageNodes.size()];
    filterModels = new List[imageNodes.size()];
    microscopeModels = new String[imageNodes.size()];
    detectorModels = new List[imageNodes.size()];
    detectorIndexes = new HashMap[imageNodes.size()];
    zSteps = new Double[imageNodes.size()];
    tSteps = new Double[imageNodes.size()];
    pinholes = new Double[imageNodes.size()];
    zooms = new Double[imageNodes.size()];

    expTimes = new Double[imageNodes.size()][];
    gains = new Double[imageNodes.size()][];
    detectorOffsets = new Double[imageNodes.size()][];
    channelNames = new String[imageNodes.size()][];
    exWaves = new Double[imageNodes.size()][];
    imageROIs = new ROI[imageNodes.size()][];
    imageNames = new String[imageNodes.size()];

    core.clear();
    for (int i = 0; i < imageNodes.size(); i++) {
        Element image = imageNodes.get(i);

        CoreMetadata ms = new CoreMetadata();
        core.add(ms);

        int index = core.size() - 1;
        setSeries(index);

        translateImageNames(image, index);
        translateImageNodes(image, index);
        translateAttachmentNodes(image, index);
        translateScannerSettings(image, index);
        translateFilterSettings(image, index);
        translateTimestamps(image, index);
        translateLaserLines(image, index);
        translateROIs(image, index);
        translateSingleROIs(image, index);
        translateDetectors(image, index);

        final Deque<String> nameStack = new ArrayDeque<String>();
        populateOriginalMetadata(image, nameStack);
        addUserCommentMeta(image, i);
    }
    setSeries(0);

    int totalSeries = 0;
    for (int count : tileCount) {
        totalSeries += count;
    }
    ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>();
    for (int i = 0; i < core.size(); i++) {
        for (int tile = 0; tile < tileCount[i]; tile++) {
            newCore.add(core.get(i));
        }
    }
    core = newCore;
}

From source file:com.espertech.esper.core.service.EPRuntimeImpl.java

private ArrayDeque<FilterHandle> getCallbackList(EventBean theEvent, String statementId) {
    ArrayDeque<FilterHandle> callbacks = new ArrayDeque<FilterHandle>();
    services.getFilterService().evaluate(theEvent, callbacks, statementId);
    return callbacks;
}

From source file:org.olat.core.util.i18n.I18nManager.java

/**
 * Internal helper to resolve keys within the given value. The optional
 * currentProperties can be used to improve performance when looking up
 * something in the current properties file
 * //from  www  .j  av  a 2  s  .co  m
 * @param locale
 * @param bundleName
 * @param key
 * @param currentProperties
 * @param overlayEnabled true: lookup first in overlay; false: don't lookup in overlay
 * @param recursionLevel
 * @param recursionLevel the current recursion level. Incremented within this
 *          method
 * @return the resolved value
 */
private String resolveValuesInternalKeys(Locale locale, String bundleName, String key,
        Properties currentProperties, boolean overlayEnabled, int recursionLevel, String value) {
    if (recursionLevel > 9) {
        log.warn("Terminating resolving of properties after 10 levels, stopped in bundle::" + bundleName
                + " and key::" + key);
        return value;
    }
    recursionLevel++;

    StringBuilder resolvedValue = new StringBuilder();
    int lastPos = 0;
    Matcher matcher = resolvingKeyPattern.matcher(value);
    while (matcher.find()) {
        resolvedValue.append(value.substring(lastPos, matcher.start()));
        String toResolvedBundle = matcher.group(1);
        String toResolvedKey = matcher.group(2);
        if (toResolvedBundle == null || toResolvedBundle.equals("")) {
            // $:my.key is valid syntax, points to $current.bundle:my.key
            toResolvedBundle = bundleName;
        }
        if (toResolvedBundle.equals(bundleName) && currentProperties != null) {
            // Resolve within bundle
            String resolvedKey = currentProperties.getProperty(toResolvedKey);
            if (resolvedKey == null) {
                // Not found, use original (added in next iteration)
                lastPos = matcher.start();
            } else {
                resolvedValue.append(resolveValuesInternalKeys(locale, bundleName, toResolvedKey,
                        currentProperties, overlayEnabled, recursionLevel, resolvedKey));
                lastPos = matcher.end();
            }
        } else {
            // Resolve using other bundle
            String resolvedKey = getLocalizedString(toResolvedBundle, toResolvedKey, null, locale,
                    overlayEnabled, true, true, true, false, recursionLevel);
            if (StringHelper.containsNonWhitespace(resolvedKey)) {
                resolvedValue.append(resolvedKey);
                lastPos = matcher.end();
            } else {
                // Not found, use original (added in next iteration)
                lastPos = matcher.start();
            }
        }
        // add resolved key to references index
        if (cachingEnabled) {
            String identifyer = buildI18nItemIdentifyer(toResolvedBundle, toResolvedKey);

            Deque<String> referencingBundles = referencingBundlesIndex.get(identifyer);
            if (referencingBundles == null) {
                Deque<String> newReferencingBundles = new ArrayDeque<>();
                referencingBundles = referencingBundlesIndex.putIfAbsent(identifyer, newReferencingBundles);
                if (referencingBundles == null) {
                    referencingBundles = newReferencingBundles;
                }
            }
            referencingBundles.add(bundleName);

        }
    }
    // Add rest of value
    resolvedValue.append(value.substring(lastPos));
    return resolvedValue.toString();
}

From source file:de.interactive_instruments.ShapeChange.Target.ArcGISWorkspace.ArcGISWorkspace.java

private int establishEAPackageHierarchy(ClassInfo ci, int mainWorkspaceSubPkgId) throws EAException {

    // get path up to but not including the application schema package
    Deque<PackageInfo> pathToAppSchemaAsStack = new ArrayDeque<PackageInfo>();

    if (ci.pkg() != this.appSchemaPkg) {

        PackageInfo pkg = ci.pkg();/*from   w  ww  . j  av  a 2s.co m*/

        while (pkg != null && pkg != this.appSchemaPkg) {

            pathToAppSchemaAsStack.addFirst(pkg);

            pkg = pkg.owner();
        }
    }

    if (pathToAppSchemaAsStack.isEmpty()) {

        // class is situated in app schema package and thus shall be created
        // in main workspace sub-package
        return mainWorkspaceSubPkgId;

    } else {

        // walk down the path, create packages as needed

        Map<PackageInfo, Integer> eaPkgIdByModelPkg = eaPkgIdByModelPkg_byWorkspaceSubPkgId
                .get(mainWorkspaceSubPkgId);

        Integer eaParentPkgId = mainWorkspaceSubPkgId;
        Integer eaPkgId = null;

        while (!pathToAppSchemaAsStack.isEmpty()) {

            PackageInfo pi = pathToAppSchemaAsStack.removeFirst();

            if (eaPkgIdByModelPkg.containsKey(pi)) {

                eaPkgId = eaPkgIdByModelPkg.get(pi);

            } else {

                // create the EA package
                eaPkgId = EAModelUtil.createEAPackage(rep, pi, eaParentPkgId);
                eaPkgIdByModelPkg.put(pi, eaPkgId);
            }

            eaParentPkgId = eaPkgId;
        }

        return eaPkgId;
    }
}