使用Smack库构建,认证和解析 [英] building, authenticating, and parsing with the Smack library

查看:91
本文介绍了使用Smack库构建,认证和解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用smack库连接到Firebase Cloud Messaging. 我对Smack API的了解不多.阅读Firebase文档后,我看到该连接必须经过身份验证,并且在应用服务器"和Cloud Connection Server之间有一系列的来回响应.根据文档,我必须创建一个Sasl Plain身份验证.我不知道该怎么实现.但是在阅读了其他StackOverFlow用户的一些帖子后,我看到必须创建一个身份验证类.具体来说,我正在查看有关使用机制X-OAUTH2的Gtalk XMPP SASL身份验证失败?"的答案和评论. CCS和应用程序服务器"之间的这些响应包含在和标记中.我不知道如何使用Smack来获取或建立这些响应.我确实使用XMPP建立了连接,并且尝试将addAsyncStanzListener设置到XMPP连接中,希望从CCS获得一些响应.但是,什么也没有.在此链接

I am trying to connect to Firebase Cloud Messaging by using smack library. I don't have much knowledge of the Smack API. After reading the Firebase docs, I see that the connection must be authenticated and there are a series of responses back and forth between "app server" and Cloud Connection Servers. According to the docs, I must create a Sasl Plain authentication. I don't know how to implement this. But after reading some posts by other StackOverFlow users I see that I must create an authentication class. Specifically, I was reviewing the answers and comments on "Gtalk XMPP SASL authentication failed using mechanism X-OAUTH2?" These responses that are between CCS and the "app server" are enclosed in and tags. I dont know how to use Smack to get or build these responses. I do have my connection set up with XMPP, and I've tried setting a addAsyncStanzListener to my XMPP connection with the hopes of getting some of these responses from CCS. But, nothing comes in. The responses between "app server" and CCS could be found in this link https://firebase.google.com/docs/cloud-messaging/server#connecting

这里有没有人知道如何从这里继续.我认为Smack的文档记录不充分,对XMPP的了解很少,这会使情况变得更糟.有所有这些类,包,扩展,IQ类,XML拉解析器等.

Does anyone here know how to proceed from here. I think that Smack is not well documented and having little knowledge of XMPP makes it even worse. There are all these classes, Packets, extensions, IQ class, XML pull parsers etc.

设置中的任何粗糙结构都是理想的选择.

Any rough structure on the set up would be ideal.

谢谢

推荐答案

以下是与Firebase一起使用的服务器代码的摘要.如果您想更详细地了解,请尝试以下博客文章(这是我弄清楚如何最终使一切正常工作的方式): http://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/

Here is a snippet of my server code that I use with Firebase. If you want to understand in more detail try this blog post (it is how I figured out how to get everything to work in the end): http://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/

要使以下代码正常工作,您需要转到Firebase控制台并转到项目设置

In order to get the code below to work you will need to go to the Firebase console and go to project settings


从这里开始,您将需要记下服务器密钥和发件人ID,并将其替换为下面的代码片段(位于代码底部附近),并将其另存为SmackCcsClient.class.


From here you will need to take note of your Server Key and Sender ID and replace it in the code snippet below (it is near the bottom of the code) and save it in your path as SmackCcsClient.class

这样做之后,您可以通过命令promt编译并运行服务器:

After doing that you can compile and run your server through the command promt:

// Set up java file (replace PATH_TO_WHERE_YOUR_CLASS_IS with your own path and make sure to put the json and smack JARs there as well
javac -d PATH_TO_WHERE_YOUR_CLASS_IS -sourcepath src -cp PATH_TO_WHERE_YOUR_CLASS_IS\json-simple-1.1.1.jar;PATH_TO_WHERE_YOUR_CLASS_IS\smack-3.4.1-0cec571.jar PATH_TO_WHERE_YOUR_CLASS_IS\SmackCcsClient.java

// Run 
java -cp PATH_TO_WHERE_YOUR_CLASS_IS;PATH_TO_WHERE_YOUR_CLASS_IS\json-simple-1.1.1.jar;PATH_TO_WHERE_YOUR_CLASS_IS\smack-3.4.1-0cec571.jar SmackCcsClient

/*

SmackCcsClient:

SmackCcsClient:

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketInterceptor;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.DefaultPacketExtension;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.provider.PacketExtensionProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.util.StringUtils;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
import org.xmlpull.v1.XmlPullParser;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.*;
import javax.net.ssl.SSLSocketFactory;

/**
 * Sample Smack implementation of a client for GCM Cloud Connection Server.
 *
 * For illustration purposes only.
 */
public class SmackCcsClient {

    static final String REG_ID_STORE = "gcmchat.txt";   

    static final String MESSAGE_KEY = "SM";
    Logger logger = Logger.getLogger("SmackCcsClient");

    public static final String GCM_SERVER = "fcm-xmpp.googleapis.com";
    public static final int GCM_PORT = 5235;

    public static final String GCM_ELEMENT_NAME = "gcm";
    public static final String GCM_NAMESPACE = "google:mobile:data";

    static Random random = new Random();
    XMPPConnection connection;
    ConnectionConfiguration config;

    /**
     * XMPP Packet Extension for GCM Cloud Connection Server.
     */
    class GcmPacketExtension extends DefaultPacketExtension {
        String json;

        public GcmPacketExtension(String json) {
            super(GCM_ELEMENT_NAME, GCM_NAMESPACE);
            this.json = json;
        }

        public String getJson() {
            return json;
        }

        @Override
        public String toXML() {
            return String.format("<%s xmlns=\"%s\">%s</%s>", GCM_ELEMENT_NAME,
                    GCM_NAMESPACE, json, GCM_ELEMENT_NAME);
        }

        @SuppressWarnings("unused")
        public Packet toPacket() {
            return new Message() {
                // Must override toXML() because it includes a <body>
                @Override
                public String toXML() {

                    StringBuilder buf = new StringBuilder();
                    buf.append("<message");
                    if (getXmlns() != null) {
                        buf.append(" xmlns=\"").append(getXmlns()).append("\"");
                    }
                    if (getLanguage() != null) {
                        buf.append(" xml:lang=\"").append(getLanguage())
                                .append("\"");
                    }
                    if (getPacketID() != null) {
                        buf.append(" id=\"").append(getPacketID()).append("\"");
                    }
                    if (getTo() != null) {
                        buf.append(" to=\"")
                                .append(StringUtils.escapeForXML(getTo()))
                                .append("\"");
                    }
                    if (getFrom() != null) {
                        buf.append(" from=\"")
                                .append(StringUtils.escapeForXML(getFrom()))
                                .append("\"");
                    }
                    buf.append(">");
                    buf.append(GcmPacketExtension.this.toXML());
                    buf.append("</message>");
                    return buf.toString();
                }
            };
        }
    }

    public SmackCcsClient() {
        // Add GcmPacketExtension
        ProviderManager.getInstance().addExtensionProvider(GCM_ELEMENT_NAME,
                GCM_NAMESPACE, new PacketExtensionProvider() {

                    @Override
                    public PacketExtension parseExtension(XmlPullParser parser)
                            throws Exception {
                        String json = parser.nextText();
                        GcmPacketExtension packet = new GcmPacketExtension(json);
                        return packet;
                    }
                });
    }

    /**
     * Returns a random message id to uniquely identify a message.
     *
     * <p>
     * Note: This is generated by a pseudo random number generator for
     * illustration purpose, and is not guaranteed to be unique.
     *
     */
    public String getRandomMessageId() {
        return "m-" + Long.toString(random.nextLong());
    }

    /**
     * Sends a downstream GCM message.
     */
    public void send(String jsonRequest) {
        Packet request = new GcmPacketExtension(jsonRequest).toPacket();
        connection.sendPacket(request);
    }

    /**
     * Handles an upstream data message from a device application.
     *
     * <p>
     * This sample echo server sends an echo message back to the device.
     * Subclasses should override this method to process an upstream message.
     */
    public void handleIncomingDataMessage(Map<String, Object> jsonObject) {

        String from = jsonObject.get("from").toString();

        // PackageName of the application that sent this message.
        String category = jsonObject.get("category").toString();

        // Use the packageName as the collapseKey in the echo packet
        String collapseKey = "echo:CollapseKey";
        @SuppressWarnings("unchecked")
        Map<String, String> payload = (Map<String, String>) jsonObject
                .get("data");



            String messageText = payload.get("message_text");
            String messageFrom = payload.get("message_userfrom");
            String messageTime = payload.get("message_timestamp");
            String toUser = payload.get("message_recipient");

            payload.put("message_text", messageText);
            payload.put("message_userfrom", messageFrom);           
            payload.put("message_timestamp", messageTime);

            String message = createJsonMessage(toUser, getRandomMessageId(),
                    payload, collapseKey, null, false);
            send(message);

    }

    /**
     * Handles an ACK.
     *
     * <p>
     * By default, it only logs a INFO message, but subclasses could override it
     * to properly handle ACKS.
     */
    public void handleAckReceipt(Map<String, Object> jsonObject) {
        String messageId = jsonObject.get("message_id").toString();
        String from = jsonObject.get("from").toString();
        logger.log(Level.INFO, "handleAckReceipt() from: " + from
                + ", messageId: " + messageId);
    }

    /**
     * Handles a NACK.
     *
     * <p>
     * By default, it only logs a INFO message, but subclasses could override it
     * to properly handle NACKS.
     */
    public void handleNackReceipt(Map<String, Object> jsonObject) {
        String messageId = jsonObject.get("message_id").toString();
        String from = jsonObject.get("from").toString();
        logger.log(Level.INFO, "handleNackReceipt() from: " + from
                + ", messageId: " + messageId);
    }

    /**
     * Creates a JSON encoded GCM message.
     *
     * @param to
     *            RegistrationId of the target device (Required).
     * @param messageId
     *            Unique messageId for which CCS will send an "ack/nack"
     *            (Required).
     * @param payload
     *            Message content intended for the application. (Optional).
     * @param collapseKey
     *            GCM collapse_key parameter (Optional).
     * @param timeToLive
     *            GCM time_to_live parameter (Optional).
     * @param delayWhileIdle
     *            GCM delay_while_idle parameter (Optional).
     * @return JSON encoded GCM message.
     */
    public static String createJsonMessage(String to, String messageId,
            Map<String, String> payload, String collapseKey, Long timeToLive,
            Boolean delayWhileIdle) {
        Map<String, Object> message = new HashMap<String, Object>();
        message.put("to", to);
        if (collapseKey != null) {
            message.put("collapse_key", collapseKey);
        }
        if (timeToLive != null) {
            message.put("time_to_live", timeToLive);
        }
        if (delayWhileIdle != null && delayWhileIdle) {
            message.put("delay_while_idle", true);
        }
        message.put("message_id", messageId);
        message.put("data", payload);
        return JSONValue.toJSONString(message);
    }

    /**
     * Creates a JSON encoded ACK message for an upstream message received from
     * an application.
     *
     * @param to
     *            RegistrationId of the device who sent the upstream message.
     * @param messageId
     *            messageId of the upstream message to be acknowledged to CCS.
     * @return JSON encoded ack.
     */
    public static String createJsonAck(String to, String messageId) {
        Map<String, Object> message = new HashMap<String, Object>();
        message.put("message_type", "ack");
        message.put("to", to);
        message.put("message_id", messageId);
        return JSONValue.toJSONString(message);
    }

    /**
     * Connects to GCM Cloud Connection Server using the supplied credentials.
     *
     * @param username
     *            GCM_SENDER_ID@gcm.googleapis.com
     * @param password
     *            API Key
     * @throws XMPPException
     */
    public void connect(String username, String password) throws XMPPException {
        config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT);
        config.setSecurityMode(SecurityMode.enabled);
        config.setReconnectionAllowed(true);
        config.setRosterLoadedAtLogin(false);
        config.setSendPresence(false);
        config.setSocketFactory(SSLSocketFactory.getDefault());

        // NOTE: Set to true to launch a window with information about packets
        // sent and received
        config.setDebuggerEnabled(true);

        // -Dsmack.debugEnabled=true
        XMPPConnection.DEBUG_ENABLED = true;

        connection = new XMPPConnection(config);
        connection.connect();

        connection.addConnectionListener(new ConnectionListener() {

            @Override
            public void reconnectionSuccessful() {
                logger.info("Reconnecting..");
            }

            @Override
            public void reconnectionFailed(Exception e) {
                logger.log(Level.INFO, "Reconnection failed.. ", e);
            }

            @Override
            public void reconnectingIn(int seconds) {
                logger.log(Level.INFO, "Reconnecting in %d secs", seconds);
            }

            @Override
            public void connectionClosedOnError(Exception e) {
                logger.log(Level.INFO, "Connection closed on error.");
            }

            @Override
            public void connectionClosed() {
                logger.info("Connection closed.");
            }
        });

        // Handle incoming packets
        connection.addPacketListener(new PacketListener() {

            @Override
            public void processPacket(Packet packet) {
                logger.log(Level.INFO, "Received: " + packet.toXML());
                Message incomingMessage = (Message) packet;
                GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage
                        .getExtension(GCM_NAMESPACE);
                String json = gcmPacket.getJson();
                try {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> jsonObject = (Map<String, Object>) JSONValue
                            .parseWithException(json);

                    // present for "ack"/"nack", null otherwise
                    Object messageType = jsonObject.get("message_type");

                    if (messageType == null) {
                        // Normal upstream data message
                        handleIncomingDataMessage(jsonObject);

                        // Send ACK to CCS
                        String messageId = jsonObject.get("message_id")
                                .toString();
                        String from = jsonObject.get("from").toString();
                        String ack = createJsonAck(from, messageId);
                        send(ack);
                    } else if ("ack".equals(messageType.toString())) {
                        // Process Ack
                        handleAckReceipt(jsonObject);
                    } else if ("nack".equals(messageType.toString())) {
                        // Process Nack
                        handleNackReceipt(jsonObject);
                    } else {
                        logger.log(Level.WARNING,
                                "Unrecognized message type (%s)",
                                messageType.toString());
                    }
                } catch (ParseException e) {
                    logger.log(Level.SEVERE, "Error parsing JSON " + json, e);
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "Couldn't send echo.", e);
                }
            }
        }, new PacketTypeFilter(Message.class));

        // Log all outgoing packets
        connection.addPacketInterceptor(new PacketInterceptor() {
            @Override
            public void interceptPacket(Packet packet) {
                logger.log(Level.INFO, "Sent: {0}", packet.toXML());
            }
        }, new PacketTypeFilter(Message.class));

        connection.login(username, password);
    }

    public void writeToFile(String name, String regId) throws IOException {
        Map<String, String> regIdMap = readFromFile();
        regIdMap.put(name, regId);
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
                REG_ID_STORE, false)));
        for (Map.Entry<String, String> entry : regIdMap.entrySet()) {
            out.println(entry.getKey() + "," + entry.getValue());
        }
        out.println(name + "," + regId);
        out.close();

    }

    public Map<String, String> readFromFile() {
    Map<String, String> regIdMap = null;
    try {
        BufferedReader br = new BufferedReader(new FileReader(REG_ID_STORE));
        String regIdLine = "";
        regIdMap = new HashMap<String, String>();
        while ((regIdLine = br.readLine()) != null) {
            String[] regArr = regIdLine.split(",");
            regIdMap.put(regArr[0], regArr[1]);
        }
        br.close();
    } catch(IOException ioe) {
    }
        return regIdMap;
    }

 public static void main(String [] args) {
    final String userName = "Sender ID" + "@gcm.googleapis.com";
    final String password = "Server key";

    SmackCcsClient ccsClient = new SmackCcsClient();

    try {
      ccsClient.connect(userName, password);
    } catch (XMPPException e) {
      e.printStackTrace();
    }
}
}

这篇关于使用Smack库构建,认证和解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆