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:tigase.hinest.HinestRegister.java

/**{@inheritDoc}
 *
 * <br><br>/* w w w  .  j  a v a  2s . c  om*/
 *
 *             TODO: Implement registration form configurable and loading
 *             all the fields from the registration form TODO: rewrite the
 *             plugin using the XMPPProcessorAbstract API
 */
@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());
    }

    if (!initConfig && settings != null) {
        if (settings.containsKey(DEV_DOMAIN_KEY)) {
            DEV_DOMAIN = (String) settings.get(DEV_DOMAIN_KEY);
        }
        if (settings.containsKey(USR_DOMAIN_KEY)) {
            USR_DOMAIN = (String) settings.get(USR_DOMAIN_KEY);
        }
    }

    //linlinno
    if (checkInfoList == null) {
        checkInfoList = new CheckInfoList();
    } else {
        if (checkInfoList.getSize() > MAX_CHECKINFOLIST_SIZE) {
            checkInfoList.deleteExpiredNode(
                    System.currentTimeMillis() - 1000 * 60 * CheckCodeTool.CHECK_CODE_TIMEOUT);
        }
    }

    if (session == null) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Session is null, ignoring");
        }

        return;
    } // end of if (session == null)

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

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

        // I think it does not make sense to check the 'to', just the
        // connection
        // ID
        // if ((id.equals(session.getDomain()) ||
        // id.equals(session.getUserId().toString()))
        // && packet.getFrom().equals(session.getConnectionId())) {
        // Wrong thinking. The user may send an request from his own account
        // to register with a transport or any other service, then the
        // connection
        // ID matches the session id but this is still not a request to the
        // local
        // server. The TO address must be checked too.....
        // if (packet.getPacketFrom().equals(session.getConnectionId())) {
        if ((packet.getPacketFrom() != null) && packet.getPacketFrom().equals(session.getConnectionId())
                && (!session.isAuthorized()
                        || (session.isUserId(id) || session.isLocalDomain(id.toString(), false)))) {

            // We want to allow password change but not user registration if
            // registration is disabled. The only way to tell apart
            // registration
            // from password change is to check whether the user is
            // authenticated.
            // For authenticated user the request means password change,
            // otherwise
            // registration attempt.
            // Account deregistration is also called under authenticated
            // session, so
            // it should be blocked here if registration for domain is
            // disabled.
            // Assuming if user cannot register account he cannot also
            // deregister account
            Element request = packet.getElement();
            boolean remove = request.findChildStaticStr(IQ_QUERY_REMOVE_PATH) != null;

            if (!session.isAuthorized() || remove) {
                if (!isRegistrationAllowedForConnection(packet.getFrom())) {
                    results.offer(Authorization.NOT_ALLOWED.getResponseMessage(packet,
                            "Registration is not allowed for this connection.", true));
                    ++statsInvalidRegistrations;
                    return;
                }

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

            Authorization result = Authorization.NOT_AUTHORIZED;
            StanzaType type = packet.getType();

            switch (type) {
            case set:

                // Is it registration cancel request?
                Element elem = request.findChildStaticStr(IQ_QUERY_REMOVE_PATH);

                if (elem != null) {

                    // Yes this is registration cancel request
                    // According to JEP-0077 there must not be any
                    // more subelements apart from <remove/>
                    elem = request.findChildStaticStr(Iq.IQ_QUERY_PATH);
                    if (elem.getChildren().size() > 1) {
                        result = Authorization.BAD_REQUEST;
                    } else {
                        try {
                            result = session.unregister(packet.getStanzaFrom().toString());

                            Packet ok_result = packet.okResult((String) null, 0);

                            // We have to set SYSTEM priority for the packet
                            // here,
                            // otherwise the network connection is closed
                            // before the
                            // client received a response
                            ok_result.setPriority(Priority.SYSTEM);
                            results.offer(ok_result);

                            Packet close_cmd = Command.CLOSE.getPacket(session.getSMComponentId(),
                                    session.getConnectionId(), StanzaType.set, session.nextStanzaId());

                            close_cmd.setPacketTo(session.getConnectionId());
                            close_cmd.setPriority(Priority.LOWEST);
                            results.offer(close_cmd);
                        } catch (NotAuthorizedException e) {
                            results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
                                    "You must authorize session first.", true));
                        } // end of try-catch
                    }
                } else {
                    String user_name;
                    String password;
                    String email;
                    String phone;//linlinno
                    String check_code;
                    if (signedFormRequired) {
                        final String expectedToken = UUID
                                .nameUUIDFromBytes(
                                        (session.getConnectionId() + "|" + session.getSessionId()).getBytes())
                                .toString();

                        FormSignatureVerifier verifier = new FormSignatureVerifier(oauthConsumerKey,
                                oauthConsumerSecret);
                        Element queryEl = request.getChild("query", "jabber:iq:register");
                        Element formEl = queryEl == null ? null : queryEl.getChild("x", "jabber:x:data");
                        if (formEl == null) {
                            results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
                                    "Use Signed Registration Form", true));
                            ++statsInvalidRegistrations;
                            return;
                        }
                        Form form = new Form(formEl);
                        if (!expectedToken.equals(form.getAsString("oauth_token"))) {
                            log.finest("Received oauth_token is different that sent one.");
                            results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
                                    "Unknown oauth_token", true));
                            ++statsInvalidRegistrations;
                            return;
                        }
                        if (!oauthConsumerKey.equals(form.getAsString("oauth_consumer_key"))) {
                            log.finest("Unknown oauth_consumer_key");
                            results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
                                    "Unknown oauth_consumer_key", true));
                            ++statsInvalidRegistrations;
                            return;
                        }
                        try {
                            long timestamp = verifier.verify(packet.getStanzaTo(), form);
                            user_name = form.getAsString("username");
                            password = form.getAsString("password");
                            email = form.getAsString("email");
                            phone = form.getAsString("phone");//linlinno
                            check_code = form.getAsString("checkcode");
                        } catch (FormSignerException e) {
                            log.fine("Form Signature Validation Problem: " + e.getMessage());
                            results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet,
                                    "Invalid form signature", true));
                            ++statsInvalidRegistrations;
                            return;
                        }
                    } else {
                        // No, so assuming this is registration of a new
                        // user or change registration details for existing
                        // user
                        user_name = request.getChildCDataStaticStr(IQ_QUERY_USERNAME_PATH);
                        password = request.getChildCDataStaticStr(IQ_QUERY_PASSWORD_PATH);
                        email = request.getChildCDataStaticStr(IQ_QUERY_EMAIL_PATH);
                        phone = request.getChildCDataStaticStr(IQ_QUERY_PHONE_PATH);//linlinno
                        check_code = request.getChildCDataStaticStr(IQ_QUERY_CHECKCODE_PATH);
                    }
                    String pass_enc = null;
                    if (null != password) {
                        pass_enc = XMLUtils.unescape(password);
                    }

                    //linlinno
                    HinestLog.debug("usrname:" + user_name);
                    HinestLog.debug("passwd:" + pass_enc);
                    HinestLog.debug("phone:" + phone);
                    HinestLog.debug("email:" + email);
                    HinestLog.debug("checkcode:" + check_code);

                    Map<String, String> reg_params = new LinkedHashMap<String, String>();

                    if ((email != null) && !email.trim().isEmpty()) {
                        reg_params.put("email", email);
                    }

                    if ((phone != null) && !phone.trim().isEmpty()) {
                        reg_params.put("phone", phone);
                    }

                    //??to do
                    HinestLog.debug("check check code~~~~to do");

                    BareJID to = packet.getStanzaTo().getBareJID();

                    HinestLog.debug("register set:" + to.getDomain());
                    HinestLog.debug("auth statte:" + session.getAuthState().getErrorCode());

                    if (session.getAuthState() != Authorization.AUTHORIZED && (to != null)
                            && to.getDomain().equals(USR_DOMAIN)) {
                        // user create new account
                        HinestLog.debug("user create new account...");
                        Map<String, String> checkInfo = checkInfoList.getCheckInfo(phone,
                                System.currentTimeMillis() - 1000 * 60 * CheckCodeTool.CHECK_CODE_TIMEOUT);
                        checkInfoList.displayAllNodes();
                        if (checkInfo != null) {

                            String checkCode = checkInfo.get("checkCode");
                            // ??
                            if (checkCode.equals(check_code)) {
                                result = session.register(user_name, pass_enc, reg_params);

                            } else {
                                result = Authorization.CHECKCODE_CHECK_FAIL;
                            }

                        } else {
                            result = Authorization.CHECKCODE_CHECK_FAIL;
                        }
                    } else if (session.getAuthState() == Authorization.AUTHORIZED && (to != null)
                            && to.getDomain().equals(USR_DOMAIN)) {
                        //usr change pwd
                        HinestLog.debug("usr change pwd...");
                        result = session.register(user_name, pass_enc, reg_params);
                    } else if (to != null && to.getDomain().equals(DEV_DOMAIN)) {
                        // dev
                        HinestLog.debug("dev...");
                        result = session.register(user_name, pass_enc, reg_params);
                    } else {
                        result = Authorization.NOT_ALLOWED;
                    }

                    if (result == Authorization.AUTHORIZED) {
                        results.offer(result.getResponseMessage(packet, null, false));
                    } else {
                        ++statsInvalidRegistrations;
                        results.offer(
                                result.getResponseMessage(packet, "Unsuccessful registration attempt", true));
                    }
                }

                break;

            case get: {

                //linlinno
                boolean getCheckCode = request.findChildStaticStr(IQ_QUERY_GETCHECKCODE_PATH) != null;

                if (getCheckCode) {

                    String phone = request.getChildCDataStaticStr(IQ_QUERY_GETCHECKCODE_PATH);
                    String checkCode = CheckCodeTool.createCheckCode(CheckCodeTool.CHECK_CODE_LENGTH);
                    HinestLog.debug(packet.toString());

                    boolean ret = CheckCodeTool.sendCheckCode(phone, checkCode);

                    System.out.println("phone:" + phone + ", checkcode:" + checkCode);

                    if (ret) {

                        //???????
                        HinestLog.debug("phone:" + phone);
                        HinestLog.debug("checkcode:" + checkCode);
                        HinestLog.debug("record phone,checkcode,createtime~~~~to do");

                        checkInfoList.addFirstNode(phone, checkCode, System.currentTimeMillis());

                        checkInfoList.displayAllNodes();

                        results.offer(packet.okResult((String) null, 0));

                    } else {
                        results.offer(Authorization.CHECKCODE_SEND_FAIL.getResponseMessage(packet,
                                "Send check code fail", true));
                    }

                    return;
                }

                if (signedFormRequired) {
                    results.offer(packet.okResult(prepareRegistrationForm(session), 0));
                } else {

                    BareJID to = packet.getStanzaTo().getBareJID();

                    HinestLog.debug("register get:" + to.getDomain());

                    if ((to != null) && to.getDomain().equals(USR_DOMAIN)) {
                        //linlinno
                        results.offer(packet.okResult("<instructions>"
                                + "Choose a user name and password for use with this service."
                                + "Please provide also your e-mail address." + "</instructions>" + "<username/>"
                                + "<password/>" + "<email/>" + "<phone/>" + "<checkcode/>", 1));
                    } else {
                        results.offer(packet.okResult(
                                "<instructions>" + "Choose a user name and password for use with this service."
                                        + "Please provide also your e-mail address." + "</instructions>"
                                        + "<username/>" + "<password/>" + "<email/>",
                                1));
                    }

                }

                break;
            }
            case result:

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

                pack_res.setPacketTo(session.getConnectionId());
                results.offer(pack_res);

                break;

            default:
                results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect",
                        true));

                break;
            } // end of switch (type)
        } 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 (TigaseStringprepException ex) {
        results.offer(Authorization.JID_MALFORMED.getResponseMessage(packet,
                "Incorrect user name, stringprep processing failed.", true));
    } 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));
    } // end of try-catch
}

From source file:de.uni_koblenz.jgralab.utilities.rsa.Rsa2Tg.java

/**
 * breadth first search over SpecializesIncidenceClass edges for closest
 * superclass with correct rolename/*from  www  .  j a  v a 2s.  c  o m*/
 * 
 * @param inc
 * @param rolename
 * @return
 */
private IncidenceClass findClosestSuperclassWithRolename(IncidenceClass inc, String rolename) {
    IncidenceClass sup = null;
    Queue<IncidenceClass> q = new LinkedList<IncidenceClass>();
    LocalBooleanGraphMarker m = new LocalBooleanGraphMarker(sg);
    m.mark(inc);
    q.offer(inc);
    while (!q.isEmpty()) {
        IncidenceClass curr = q.poll();
        m.mark(curr);
        if ((curr != inc) && rolename.equals(curr.get_roleName())) {
            sup = curr;
            break;
        }
        for (SpecializesIncidenceClass sic : curr.getIncidentEdges(SpecializesIncidenceClass.class,
                de.uni_koblenz.jgralab.Direction.VERTEX_TO_EDGE)) {
            IncidenceClass i = (IncidenceClass) sic.getOmega();
            if (!m.isMarked(i)) {
                m.mark(i);
                q.offer(i);
            }
        }

    }
    return sup;
}

From source file:org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.java

private void walkASTMarkTABREF(ASTNode ast, Set<String> cteAlias) throws SemanticException {
    Queue<Node> queue = new LinkedList<>();
    queue.add(ast);//  w  w w  . j a v  a 2s  .c o  m
    Map<HivePrivilegeObject, MaskAndFilterInfo> basicInfos = new LinkedHashMap<>();
    while (!queue.isEmpty()) {
        ASTNode astNode = (ASTNode) queue.poll();
        if (astNode.getToken().getType() == HiveParser.TOK_TABREF) {
            int aliasIndex = 0;
            StringBuilder additionalTabInfo = new StringBuilder();
            for (int index = 1; index < astNode.getChildCount(); index++) {
                ASTNode ct = (ASTNode) astNode.getChild(index);
                if (ct.getToken().getType() == HiveParser.TOK_TABLEBUCKETSAMPLE
                        || ct.getToken().getType() == HiveParser.TOK_TABLESPLITSAMPLE
                        || ct.getToken().getType() == HiveParser.TOK_TABLEPROPERTIES) {
                    additionalTabInfo.append(ctx.getTokenRewriteStream().toString(ct.getTokenStartIndex(),
                            ct.getTokenStopIndex()));
                } else {
                    aliasIndex = index;
                }
            }

            ASTNode tableTree = (ASTNode) (astNode.getChild(0));

            String tabIdName = getUnescapedName(tableTree);

            String alias;
            if (aliasIndex != 0) {
                alias = unescapeIdentifier(astNode.getChild(aliasIndex).getText());
            } else {
                alias = getUnescapedUnqualifiedTableName(tableTree);
            }

            // We need to know if it is CTE or not.
            // A CTE may have the same name as a table.
            // For example,
            // with select TAB1 [masking] as TAB2
            // select * from TAB2 [no masking]
            if (cteAlias.contains(tabIdName)) {
                continue;
            }

            String replacementText = null;
            Table table = null;
            try {
                table = getTableObjectByName(tabIdName);
            } catch (HiveException e) {
                // Table may not be found when materialization of CTE is on.
                LOG.info("Table " + tabIdName + " is not found in walkASTMarkTABREF.");
                continue;
            }

            List<String> colNames = new ArrayList<>();
            List<String> colTypes = new ArrayList<>();
            for (FieldSchema col : table.getAllCols()) {
                colNames.add(col.getName());
                colTypes.add(col.getType());
            }

            basicInfos.put(new HivePrivilegeObject(table.getDbName(), table.getTableName(), colNames),
                    new MaskAndFilterInfo(colTypes, additionalTabInfo.toString(), alias, astNode,
                            table.isView()));
        }
        if (astNode.getChildCount() > 0 && !ignoredTokens.contains(astNode.getToken().getType())) {
            for (Node child : astNode.getChildren()) {
                queue.offer(child);
            }
        }
    }
    List<HivePrivilegeObject> basicPrivObjs = new ArrayList<>();
    basicPrivObjs.addAll(basicInfos.keySet());
    List<HivePrivilegeObject> needRewritePrivObjs = tableMask.applyRowFilterAndColumnMasking(basicPrivObjs);
    if (needRewritePrivObjs != null && !needRewritePrivObjs.isEmpty()) {
        for (HivePrivilegeObject privObj : needRewritePrivObjs) {
            MaskAndFilterInfo info = basicInfos.get(privObj);
            String replacementText = tableMask.create(privObj, info);
            if (replacementText != null) {
                // We don't support masking/filtering against ACID query at the moment
                if (ctx.getIsUpdateDeleteMerge()) {
                    throw new SemanticException(ErrorMsg.MASKING_FILTERING_ON_ACID_NOT_SUPPORTED,
                            privObj.getDbname(), privObj.getObjectName());
                }
                tableMask.setNeedsRewrite(true);
                tableMask.addTranslation(info.astNode, replacementText);
            }
        }
    }
}