Example usage for java.util Queue offer

List of usage examples for java.util Queue offer

Introduction

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

Prototype

boolean offer(E e);

Source Link

Document

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.

Usage

From source file:org.kontalk.xmppserver.KontalkIqRegister.java

@Override
public boolean onProbeResult(ProbeInfo info, Object userData, Queue<Packet> results) {
    if (log.isLoggable(Level.FINEST)) {
        log.finest("probe result: " + info);
    }//  ww  w  .j  a v a  2 s  .c o m

    RegistrationInfo regInfo = (RegistrationInfo) userData;
    Set<BareJID> storage = info.getStorage();
    if (storage != null && storage.size() > 0) {
        results.offer(errorUserExists(regInfo.packet));
    } else {
        SessionManager sm = (SessionManager) XMPPServer.getComponent("sess-man");
        try {
            Packet result = startVerification(sm.getDefVHostItem().getDomain(), regInfo.packet,
                    regInfo.connectionId, regInfo.jid, regInfo.phone, regInfo.fallback, regInfo.challenge);
            if (result != null) {
                result.setPacketTo(regInfo.connectionId);
                results.offer(result);
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "error starting verification", e);
            // TODO notify client
        }
    }
    return true;
}

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 {/*ww w. ja  v  a 2 s.  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.polymap.model2.engine.EntityRepositoryImpl.java

public EntityRepositoryImpl(final Configuration config) {
    this.config = config;

    // init store
    getStore().init(new StoreRuntimeContextImpl());

    // init infos
    log.debug("Initialializing Composite types:");
    Queue<Class<? extends Composite>> queue = new LinkedList();
    queue.addAll(Arrays.asList(config.entities.get()));

    while (!queue.isEmpty()) {
        Class<? extends Composite> type = queue.poll();
        if (!infos.containsKey(type)) {
            log.debug("    Composite type: " + type);
            CompositeInfoImpl info = new CompositeInfoImpl(type);
            infos.put(type, info);/*  w w w.j a  v  a2s  .c  o m*/

            // init static TYPE variable
            try {
                Field field = type.getDeclaredField("TYPE");
                field.setAccessible(true);
                field.set(null, Expressions.template(type, this));
            } catch (NoSuchFieldException e) {
            } catch (SecurityException | IllegalAccessException e) {
                throw new ModelRuntimeException(e);
            }

            // mixins
            queue.addAll(info.getMixins());

            // Composite properties
            for (PropertyInfo propInfo : info.getProperties()) {
                if (Composite.class.isAssignableFrom(propInfo.getType())) {
                    queue.offer(propInfo.getType());
                }
            }
        }
    }
}

From source file:Graph.java

public void bfs(Queue<Node> q) {
    clearState();//ww w  .  j  a  v a2  s . c o  m
    for (Node n : nodes) {
        n.setState(q.contains(n) ? GRAY : WHITE);
    }
    for (Edge e : edges) {
        e.setMode(UNKNOWN);
    }
    for (Node n : q) {
        n.setDistance(0);
        n.setPredecessor(null);
    }
    while (!q.isEmpty()) {
        Node n = q.remove();
        List<Node> out = findNextNodes(n);
        for (Node m : out) {
            Edge e = findEdge(n, m);
            if (e != null) {
                if (m.getState() == WHITE) {
                    e.setMode(TREE);
                } else if (m.getState() == GRAY) {
                    e.setMode(BACK);
                }
            }
            if (!m.isVisited()) {
                m.setDistance(n.getDistance() + 1);
                m.setPredecessor(n);
                m.setState(GRAY);
                q.offer(m);
            }
        }
        n.setState(BLACK);
    }
    searchState = STATE_BFS;
}

From source file:com.koda.integ.hbase.storage.FileExtStorage.java

/**
 * Put file back to the pool/*  w  w w . j a v  a  2  s . com*/
 * TODO: race condition
 *
 * @param id the id
 * @param file the file
 */
private void putFile(int id, RandomAccessFile file) {
    Queue<RandomAccessFile> fileReaders = readers.get(id);
    boolean result = false;

    if (fileReaders == null) {
        // This means that file has been deleted
        result = false;
    } else {
        result = fileReaders.offer(file);
        // Put back if present
        // Make sure that file has not been deleted
        if (readers.replace(id, fileReaders) == null) {
            result = false;
            // clear queue
            fileReaders.clear();
        }

    }
    if (result == false) {
        try {
            file.close();
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}

From source file:org.kontalk.xmppserver.KontalkIqRegister.java

private void rolloverContinue(XMPPResourceConnection session, byte[] publicKeyData, Packet packet,
        Queue<Packet> results)
        throws IOException, PGPException, TigaseDBException, PacketErrorTypeException, NotAuthorizedException {

    PGPPublicKey key = loadPublicKey(publicKeyData);
    // verify user id
    BareJID jid = verifyPublicKey(session, key);
    if (jid != null) {
        byte[] signedKey = signPublicKey(session, publicKeyData);
        Packet response = register(session, packet, jid, key.getFingerprint(), signedKey);

        // send signed key in response
        packet.processedBy(ID);//from w w  w  .ja v a 2  s.  com
        results.offer(response);
    } else {
        results.offer(Authorization.FORBIDDEN.getResponseMessage(packet, ERROR_INVALID_PUBKEY, false));
    }
}

From source file:org.kuali.rice.krad.uif.lifecycle.ViewLifecyclePhaseBase.java

/**
 * Initializes all lifecycle phase successors.
 *
 * @param successors The successor queue.
 *///from w  w  w  . j a  va  2 s .c om
protected void initializeAllLifecycleSuccessors(Queue<ViewLifecyclePhase> successors) {
    LifecycleElement element = getElement();

    String nestedPathPrefix;
    Component nestedParent;
    if (element instanceof Component) {
        nestedParent = (Component) element;
        nestedPathPrefix = "";
    } else {
        nestedParent = getParent();
        nestedPathPrefix = getParentPath() + ".";
    }

    for (Map.Entry<String, LifecycleElement> nestedElementEntry : ViewLifecycleUtils
            .getElementsForLifecycle(element, getViewPhase()).entrySet()) {
        String nestedPath = nestedPathPrefix + nestedElementEntry.getKey();
        LifecycleElement nestedElement = nestedElementEntry.getValue();

        if (nestedElement != null && !getEndViewStatus().equals(nestedElement.getViewStatus())) {
            ViewLifecyclePhase nestedPhase = initializeSuccessor(nestedElement, nestedPath, nestedParent);
            successors.offer(nestedPhase);
        }
    }
}

From source file:com.datatorrent.stram.webapp.TypeGraph.java

private void removeSubGraph(TypeGraphVertex v) {

    // Can't recursively remove because it will get into concurrent modification
    // Use queue to delete all nodes
    Queue<TypeGraphVertex> removingQueue = new LinkedList<>();
    removingQueue.add(v);//  w  w w.j  av  a 2  s .  com
    while (!removingQueue.isEmpty()) {
        TypeGraphVertex tgv = removingQueue.poll();
        if (typeGraph.get(tgv.typeName) == null) {
            // skip node that's been removed already.
            // It comes from common descendants
            continue;
        }
        // put all the descendants to waiting queue
        for (TypeGraphVertex child : tgv.descendants) {
            removingQueue.offer(child);
        }
        // remove from global hashmap
        typeGraph.remove(tgv.typeName);
        // remove from instantiable descendants list of all the (in)direct ancestors
        if (!tgv.allInstantiableDescendants.isEmpty() && !tgv.ancestors.isEmpty()) {
            for (TypeGraphVertex p : tgv.ancestors) {
                removeFromInstantiableDescendants(p, tgv.allInstantiableDescendants);
            }
        }
        // cut links from parent to child
        for (TypeGraphVertex parent : tgv.ancestors) {
            parent.descendants.remove(tgv);
        }
        // cut links form child to parent
        tgv.ancestors.clear();
    }
}

From source file:org.kontalk.xmppserver.KontalkIqRegister.java

@Override
public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
        Queue<Packet> results, Map<String, Object> settings) throws XMPPException {
    if (log.isLoggable(Level.FINEST)) {
        log.finest("Processing packet: " + packet.toString());
    }//  w w w  .  ja  v a 2 s  .  c o  m
    if (session == null) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Session is null, ignoring");
        }

        return;
    }

    BareJID id = session.getDomainAsJID().getBareJID();

    if (packet.getStanzaTo() != null) {
        id = packet.getStanzaTo().getBareJID();
    }
    try {

        if ((packet.getPacketFrom() != null) && packet.getPacketFrom().equals(session.getConnectionId())
                && (!session.isAuthorized()
                        || (session.isUserId(id) || session.isLocalDomain(id.toString(), false)))) {

            Element request = packet.getElement();

            if (!session.isAuthorized()) {
                if (!session.getDomain().isRegisterEnabled()) {
                    results.offer(Authorization.NOT_ALLOWED.getResponseMessage(packet,
                            "Registration is not allowed for this domain.", true));
                    ++statsInvalidRegistrations;
                    return;
                }
            }

            StanzaType type = packet.getType();

            switch (type) {
            case set: {
                // FIXME handle all the cases according to the FORM_TYPE

                Element query = request.getChild(Iq.QUERY_NAME, XMLNSS[0]);
                Element formElement = (query != null) ? query.getChild(IQ_FORM_ELEM_NAME, IQ_FORM_XMLNS) : null;
                if (formElement != null) {
                    Form form = new Form(formElement);

                    // phone number: verification code
                    String phone = form.getAsString(FORM_FIELD_PHONE);
                    if (!session.isAuthorized() && phone != null) {
                        boolean force;
                        try {
                            force = form.getAsBoolean(FORM_FIELD_FORCE);
                        } catch (NullPointerException e) {
                            force = false;
                        }
                        boolean fallback;
                        try {
                            fallback = form.getAsBoolean(FORM_FIELD_FALLBACK);
                        } catch (NullPointerException e) {
                            fallback = false;
                        }
                        String challenge;
                        try {
                            challenge = form.getAsString(FORM_FIELD_CHALLENGE);
                        } catch (NullPointerException e) {
                            challenge = null;
                        }

                        Packet response = registerPhone(session, packet, phone, force, fallback, challenge,
                                results);
                        statsRegistrationAttempts++;
                        packet.processedBy(ID);
                        if (response != null)
                            results.offer(response);
                        break;
                    }

                    // verification code: key submission
                    String code = form.getAsString(FORM_FIELD_CODE);
                    // get public key block from client certificate
                    byte[] publicKeyData = getPublicKey(session);

                    if (!session.isAuthorized()) {

                        // load public key
                        PGPPublicKey key = loadPublicKey(publicKeyData);
                        // verify user id
                        BareJID jid = verifyPublicKey(session, key);

                        if (verifyCode(session, jid, code)) {
                            byte[] signedKey = signPublicKey(session, publicKeyData);

                            Packet response = register(session, packet, jid, key.getFingerprint(), signedKey);
                            statsRegisteredUsers++;
                            packet.processedBy(ID);
                            results.offer(response);
                        } else {
                            // invalid verification code
                            results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
                                    ERROR_INVALID_CODE, true));
                        }

                        // clear throttling
                        clearThrottling(jid, session.getConnectionId());

                        break;
                    }

                    if (session.isAuthorized()) {
                        // private key storage
                        String privateKey = form.getAsString(FORM_FIELD_PRIVATEKEY);
                        if (privateKey != null) {
                            Packet response = storePrivateKey(session, repo, packet, privateKey);
                            packet.processedBy(ID);
                            results.offer(response);
                            break;
                        } else {
                            // public key + revoked key: key rollover or upgrade from legacy
                            String oldFingerprint;
                            try {
                                oldFingerprint = KontalkAuth.getUserFingerprint(session);
                            } catch (UserNotFoundException e) {
                                oldFingerprint = null;
                                log.log(Level.INFO, "user not found: {0}", session);
                            }

                            if (oldFingerprint != null) {
                                // do not use public key from certificate
                                publicKeyData = null;

                                // user already has a key, check if revoked key fingerprint matches
                                String publicKey = form.getAsString(FORM_FIELD_PUBLICKEY);
                                String revoked = form.getAsString(FORM_FIELD_REVOKED);
                                if (publicKey != null && revoked != null) {
                                    publicKeyData = Base64.decode(publicKey);
                                    byte[] revokedData = Base64.decode(revoked);
                                    KontalkKeyring keyring = getKeyring(session);
                                    if (!keyring.revoked(revokedData, oldFingerprint)) {
                                        // invalid revocation key
                                        log.log(Level.INFO, "Invalid revocation key for user {0}",
                                                session.getBareJID());
                                        results.offer(Authorization.FORBIDDEN.getResponseMessage(packet,
                                                ERROR_INVALID_REVOKED, false));
                                        break;
                                    }
                                }
                            }

                            // user has no key or revocation key was fine, accept the new key
                            if (publicKeyData != null) {
                                rolloverContinue(session, publicKeyData, packet, results);
                                break;
                            }
                        }
                    }
                }

                // bad request
                results.offer(
                        Authorization.BAD_REQUEST.getResponseMessage(packet, ERROR_MALFORMED_REQUEST, true));
                break;
            }

            case get: {
                Element query = request.getChild(Iq.QUERY_NAME, XMLNSS[0]);
                Element account = query.getChild(IQ_ACCOUNT_ELEM_NAME, IQ_ACCOUNT_XMLNS);
                if (account != null) {
                    String token = account.getChildCData(new String[] { IQ_ACCOUNT_ELEM_NAME,
                            IQ_ACCOUNT_PRIVATEKEY_ELEM_NAME, IQ_ACCOUNT_TOKEN_ELEM_NAME });

                    if (StringUtils.isNotEmpty(token)) {
                        Packet response = retrievePrivateKey(session, repo, packet, token);
                        response.processedBy(ID);
                        results.offer(response);
                        break;
                    }
                }

                // instructions form
                results.offer(buildInstructionsForm(packet));
                break;
            }
            default:
                results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect",
                        true));

                break;
            }
        } else {
            if (session.isUserId(id)) {

                // It might be a registration request from transport for
                // example...
                Packet pack_res = packet.copyElementOnly();

                pack_res.setPacketTo(session.getConnectionId());
                results.offer(pack_res);
            } else {
                results.offer(packet.copyElementOnly());
            }
        }
    } catch (NotAuthorizedException e) {
        results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
                "You are not authorized to change registration settings.\n" + e.getMessage(), true));
    } catch (TigaseDBException e) {
        log.warning("Database problem: " + e);
        results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet,
                "Database access problem, please contact administrator.", true));
    }
    // generated from PGP
    catch (IOException e) {
        log.warning("Unknown error: " + e);
        results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet,
                "Internal PGP error. Please contact administrator.", true));
    } catch (PGPException e) {
        e.printStackTrace(System.err);
        log.warning("PGP problem: " + e);
        results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, ERROR_INVALID_PUBKEY, true));
    }
}

From source file:de.xaniox.heavyspleef.core.game.Game.java

public void flushQueue() {
    Queue<SpleefPlayer> failedToQueue = Lists.newLinkedList();

    //Flush the queue
    while (!queuedPlayers.isEmpty()) {
        SpleefPlayer player = queuedPlayers.poll();
        if (!player.isOnline()) {
            continue;
        }/*from www .j  av a2 s .  com*/

        PlayerQueueFlushEvent event = new PlayerQueueFlushEvent(this, player);
        eventBus.callEvent(event);

        PlayerQueueFlushEvent.FlushResult result = event.getResult();
        if (result == PlayerQueueFlushEvent.FlushResult.ALLOW) {
            PlayerPreJoinGameEvent joinEvent = new PlayerPreJoinGameEvent(this, player);
            eventBus.callEvent(joinEvent);

            if (joinEvent.getJoinResult() != JoinResult.TEMPORARY_DENY) {
                join(player, joinEvent);
                continue;
            }
        }

        failedToQueue.offer(player);
    }

    queuedPlayers.addAll(failedToQueue);
}