Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.36 KB | None | 0 0
  1. // 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
  2. javac -d PATH_TO_WHERE_YOUR_CLASS_IS -sourcepath src -cp PATH_TO_WHERE_YOUR_CLASS_ISjson-simple-1.1.1.jar;PATH_TO_WHERE_YOUR_CLASS_ISsmack-3.4.1-0cec571.jar PATH_TO_WHERE_YOUR_CLASS_ISSmackCcsClient.java
  3.  
  4. // Run
  5. java -cp PATH_TO_WHERE_YOUR_CLASS_IS;PATH_TO_WHERE_YOUR_CLASS_ISjson-simple-1.1.1.jar;PATH_TO_WHERE_YOUR_CLASS_ISsmack-3.4.1-0cec571.jar SmackCcsClient
  6.  
  7. import org.jivesoftware.smack.ConnectionConfiguration;
  8. import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
  9. import org.jivesoftware.smack.ConnectionListener;
  10. import org.jivesoftware.smack.PacketInterceptor;
  11. import org.jivesoftware.smack.PacketListener;
  12. import org.jivesoftware.smack.XMPPConnection;
  13. import org.jivesoftware.smack.XMPPException;
  14. import org.jivesoftware.smack.filter.PacketTypeFilter;
  15. import org.jivesoftware.smack.packet.DefaultPacketExtension;
  16. import org.jivesoftware.smack.packet.Message;
  17. import org.jivesoftware.smack.packet.Packet;
  18. import org.jivesoftware.smack.packet.PacketExtension;
  19. import org.jivesoftware.smack.provider.PacketExtensionProvider;
  20. import org.jivesoftware.smack.provider.ProviderManager;
  21. import org.jivesoftware.smack.util.StringUtils;
  22. import org.json.simple.JSONValue;
  23. import org.json.simple.parser.ParseException;
  24. import org.xmlpull.v1.XmlPullParser;
  25.  
  26. import java.util.HashMap;
  27. import java.util.Map;
  28. import java.util.Random;
  29. import java.util.logging.Level;
  30. import java.util.logging.Logger;
  31. import java.io.*;
  32. import javax.net.ssl.SSLSocketFactory;
  33.  
  34. /**
  35. * Sample Smack implementation of a client for GCM Cloud Connection Server.
  36. *
  37. * For illustration purposes only.
  38. */
  39. public class SmackCcsClient {
  40.  
  41. static final String REG_ID_STORE = "gcmchat.txt";
  42.  
  43. static final String MESSAGE_KEY = "SM";
  44. Logger logger = Logger.getLogger("SmackCcsClient");
  45.  
  46. public static final String GCM_SERVER = "fcm-xmpp.googleapis.com";
  47. public static final int GCM_PORT = 5235;
  48.  
  49. public static final String GCM_ELEMENT_NAME = "gcm";
  50. public static final String GCM_NAMESPACE = "google:mobile:data";
  51.  
  52. static Random random = new Random();
  53. XMPPConnection connection;
  54. ConnectionConfiguration config;
  55.  
  56. /**
  57. * XMPP Packet Extension for GCM Cloud Connection Server.
  58. */
  59. class GcmPacketExtension extends DefaultPacketExtension {
  60. String json;
  61.  
  62. public GcmPacketExtension(String json) {
  63. super(GCM_ELEMENT_NAME, GCM_NAMESPACE);
  64. this.json = json;
  65. }
  66.  
  67. public String getJson() {
  68. return json;
  69. }
  70.  
  71. @Override
  72. public String toXML() {
  73. return String.format("<%s xmlns="%s">%s</%s>", GCM_ELEMENT_NAME,
  74. GCM_NAMESPACE, json, GCM_ELEMENT_NAME);
  75. }
  76.  
  77. @SuppressWarnings("unused")
  78. public Packet toPacket() {
  79. return new Message() {
  80. // Must override toXML() because it includes a <body>
  81. @Override
  82. public String toXML() {
  83.  
  84. StringBuilder buf = new StringBuilder();
  85. buf.append("<message");
  86. if (getXmlns() != null) {
  87. buf.append(" xmlns="").append(getXmlns()).append(""");
  88. }
  89. if (getLanguage() != null) {
  90. buf.append(" xml:lang="").append(getLanguage())
  91. .append(""");
  92. }
  93. if (getPacketID() != null) {
  94. buf.append(" id="").append(getPacketID()).append(""");
  95. }
  96. if (getTo() != null) {
  97. buf.append(" to="")
  98. .append(StringUtils.escapeForXML(getTo()))
  99. .append(""");
  100. }
  101. if (getFrom() != null) {
  102. buf.append(" from="")
  103. .append(StringUtils.escapeForXML(getFrom()))
  104. .append(""");
  105. }
  106. buf.append(">");
  107. buf.append(GcmPacketExtension.this.toXML());
  108. buf.append("</message>");
  109. return buf.toString();
  110. }
  111. };
  112. }
  113. }
  114.  
  115. public SmackCcsClient() {
  116. // Add GcmPacketExtension
  117. ProviderManager.getInstance().addExtensionProvider(GCM_ELEMENT_NAME,
  118. GCM_NAMESPACE, new PacketExtensionProvider() {
  119.  
  120. @Override
  121. public PacketExtension parseExtension(XmlPullParser parser)
  122. throws Exception {
  123. String json = parser.nextText();
  124. GcmPacketExtension packet = new GcmPacketExtension(json);
  125. return packet;
  126. }
  127. });
  128. }
  129.  
  130. /**
  131. * Returns a random message id to uniquely identify a message.
  132. *
  133. * <p>
  134. * Note: This is generated by a pseudo random number generator for
  135. * illustration purpose, and is not guaranteed to be unique.
  136. *
  137. */
  138. public String getRandomMessageId() {
  139. return "m-" + Long.toString(random.nextLong());
  140. }
  141.  
  142. /**
  143. * Sends a downstream GCM message.
  144. */
  145. public void send(String jsonRequest) {
  146. Packet request = new GcmPacketExtension(jsonRequest).toPacket();
  147. connection.sendPacket(request);
  148. }
  149.  
  150. /**
  151. * Handles an upstream data message from a device application.
  152. *
  153. * <p>
  154. * This sample echo server sends an echo message back to the device.
  155. * Subclasses should override this method to process an upstream message.
  156. */
  157. public void handleIncomingDataMessage(Map<String, Object> jsonObject) {
  158.  
  159. String from = jsonObject.get("from").toString();
  160.  
  161. // PackageName of the application that sent this message.
  162. String category = jsonObject.get("category").toString();
  163.  
  164. // Use the packageName as the collapseKey in the echo packet
  165. String collapseKey = "echo:CollapseKey";
  166. @SuppressWarnings("unchecked")
  167. Map<String, String> payload = (Map<String, String>) jsonObject
  168. .get("data");
  169.  
  170.  
  171.  
  172. String messageText = payload.get("message_text");
  173. String messageFrom = payload.get("message_userfrom");
  174. String messageTime = payload.get("message_timestamp");
  175. String toUser = payload.get("message_recipient");
  176.  
  177. payload.put("message_text", messageText);
  178. payload.put("message_userfrom", messageFrom);
  179. payload.put("message_timestamp", messageTime);
  180.  
  181. String message = createJsonMessage(toUser, getRandomMessageId(),
  182. payload, collapseKey, null, false);
  183. send(message);
  184.  
  185. }
  186.  
  187. /**
  188. * Handles an ACK.
  189. *
  190. * <p>
  191. * By default, it only logs a INFO message, but subclasses could override it
  192. * to properly handle ACKS.
  193. */
  194. public void handleAckReceipt(Map<String, Object> jsonObject) {
  195. String messageId = jsonObject.get("message_id").toString();
  196. String from = jsonObject.get("from").toString();
  197. logger.log(Level.INFO, "handleAckReceipt() from: " + from
  198. + ", messageId: " + messageId);
  199. }
  200.  
  201. /**
  202. * Handles a NACK.
  203. *
  204. * <p>
  205. * By default, it only logs a INFO message, but subclasses could override it
  206. * to properly handle NACKS.
  207. */
  208. public void handleNackReceipt(Map<String, Object> jsonObject) {
  209. String messageId = jsonObject.get("message_id").toString();
  210. String from = jsonObject.get("from").toString();
  211. logger.log(Level.INFO, "handleNackReceipt() from: " + from
  212. + ", messageId: " + messageId);
  213. }
  214.  
  215. /**
  216. * Creates a JSON encoded GCM message.
  217. *
  218. * @param to
  219. * RegistrationId of the target device (Required).
  220. * @param messageId
  221. * Unique messageId for which CCS will send an "ack/nack"
  222. * (Required).
  223. * @param payload
  224. * Message content intended for the application. (Optional).
  225. * @param collapseKey
  226. * GCM collapse_key parameter (Optional).
  227. * @param timeToLive
  228. * GCM time_to_live parameter (Optional).
  229. * @param delayWhileIdle
  230. * GCM delay_while_idle parameter (Optional).
  231. * @return JSON encoded GCM message.
  232. */
  233. public static String createJsonMessage(String to, String messageId,
  234. Map<String, String> payload, String collapseKey, Long timeToLive,
  235. Boolean delayWhileIdle) {
  236. Map<String, Object> message = new HashMap<String, Object>();
  237. message.put("to", to);
  238. if (collapseKey != null) {
  239. message.put("collapse_key", collapseKey);
  240. }
  241. if (timeToLive != null) {
  242. message.put("time_to_live", timeToLive);
  243. }
  244. if (delayWhileIdle != null && delayWhileIdle) {
  245. message.put("delay_while_idle", true);
  246. }
  247. message.put("message_id", messageId);
  248. message.put("data", payload);
  249. return JSONValue.toJSONString(message);
  250. }
  251.  
  252. /**
  253. * Creates a JSON encoded ACK message for an upstream message received from
  254. * an application.
  255. *
  256. * @param to
  257. * RegistrationId of the device who sent the upstream message.
  258. * @param messageId
  259. * messageId of the upstream message to be acknowledged to CCS.
  260. * @return JSON encoded ack.
  261. */
  262. public static String createJsonAck(String to, String messageId) {
  263. Map<String, Object> message = new HashMap<String, Object>();
  264. message.put("message_type", "ack");
  265. message.put("to", to);
  266. message.put("message_id", messageId);
  267. return JSONValue.toJSONString(message);
  268. }
  269.  
  270. /**
  271. * Connects to GCM Cloud Connection Server using the supplied credentials.
  272. *
  273. * @param username
  274. * GCM_SENDER_ID@gcm.googleapis.com
  275. * @param password
  276. * API Key
  277. * @throws XMPPException
  278. */
  279. public void connect(String username, String password) throws XMPPException {
  280. config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT);
  281. config.setSecurityMode(SecurityMode.enabled);
  282. config.setReconnectionAllowed(true);
  283. config.setRosterLoadedAtLogin(false);
  284. config.setSendPresence(false);
  285. config.setSocketFactory(SSLSocketFactory.getDefault());
  286.  
  287. // NOTE: Set to true to launch a window with information about packets
  288. // sent and received
  289. config.setDebuggerEnabled(true);
  290.  
  291. // -Dsmack.debugEnabled=true
  292. XMPPConnection.DEBUG_ENABLED = true;
  293.  
  294. connection = new XMPPConnection(config);
  295. connection.connect();
  296.  
  297. connection.addConnectionListener(new ConnectionListener() {
  298.  
  299. @Override
  300. public void reconnectionSuccessful() {
  301. logger.info("Reconnecting..");
  302. }
  303.  
  304. @Override
  305. public void reconnectionFailed(Exception e) {
  306. logger.log(Level.INFO, "Reconnection failed.. ", e);
  307. }
  308.  
  309. @Override
  310. public void reconnectingIn(int seconds) {
  311. logger.log(Level.INFO, "Reconnecting in %d secs", seconds);
  312. }
  313.  
  314. @Override
  315. public void connectionClosedOnError(Exception e) {
  316. logger.log(Level.INFO, "Connection closed on error.");
  317. }
  318.  
  319. @Override
  320. public void connectionClosed() {
  321. logger.info("Connection closed.");
  322. }
  323. });
  324.  
  325. // Handle incoming packets
  326. connection.addPacketListener(new PacketListener() {
  327.  
  328. @Override
  329. public void processPacket(Packet packet) {
  330. logger.log(Level.INFO, "Received: " + packet.toXML());
  331. Message incomingMessage = (Message) packet;
  332. GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage
  333. .getExtension(GCM_NAMESPACE);
  334. String json = gcmPacket.getJson();
  335. try {
  336. @SuppressWarnings("unchecked")
  337. Map<String, Object> jsonObject = (Map<String, Object>) JSONValue
  338. .parseWithException(json);
  339.  
  340. // present for "ack"/"nack", null otherwise
  341. Object messageType = jsonObject.get("message_type");
  342.  
  343. if (messageType == null) {
  344. // Normal upstream data message
  345. handleIncomingDataMessage(jsonObject);
  346.  
  347. // Send ACK to CCS
  348. String messageId = jsonObject.get("message_id")
  349. .toString();
  350. String from = jsonObject.get("from").toString();
  351. String ack = createJsonAck(from, messageId);
  352. send(ack);
  353. } else if ("ack".equals(messageType.toString())) {
  354. // Process Ack
  355. handleAckReceipt(jsonObject);
  356. } else if ("nack".equals(messageType.toString())) {
  357. // Process Nack
  358. handleNackReceipt(jsonObject);
  359. } else {
  360. logger.log(Level.WARNING,
  361. "Unrecognized message type (%s)",
  362. messageType.toString());
  363. }
  364. } catch (ParseException e) {
  365. logger.log(Level.SEVERE, "Error parsing JSON " + json, e);
  366. } catch (Exception e) {
  367. logger.log(Level.SEVERE, "Couldn't send echo.", e);
  368. }
  369. }
  370. }, new PacketTypeFilter(Message.class));
  371.  
  372. // Log all outgoing packets
  373. connection.addPacketInterceptor(new PacketInterceptor() {
  374. @Override
  375. public void interceptPacket(Packet packet) {
  376. logger.log(Level.INFO, "Sent: {0}", packet.toXML());
  377. }
  378. }, new PacketTypeFilter(Message.class));
  379.  
  380. connection.login(username, password);
  381. }
  382.  
  383. public void writeToFile(String name, String regId) throws IOException {
  384. Map<String, String> regIdMap = readFromFile();
  385. regIdMap.put(name, regId);
  386. PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
  387. REG_ID_STORE, false)));
  388. for (Map.Entry<String, String> entry : regIdMap.entrySet()) {
  389. out.println(entry.getKey() + "," + entry.getValue());
  390. }
  391. out.println(name + "," + regId);
  392. out.close();
  393.  
  394. }
  395.  
  396. public Map<String, String> readFromFile() {
  397. Map<String, String> regIdMap = null;
  398. try {
  399. BufferedReader br = new BufferedReader(new FileReader(REG_ID_STORE));
  400. String regIdLine = "";
  401. regIdMap = new HashMap<String, String>();
  402. while ((regIdLine = br.readLine()) != null) {
  403. String[] regArr = regIdLine.split(",");
  404. regIdMap.put(regArr[0], regArr[1]);
  405. }
  406. br.close();
  407. } catch(IOException ioe) {
  408. }
  409. return regIdMap;
  410. }
  411.  
  412. public static void main(String [] args) {
  413. final String userName = "Sender ID" + "@gcm.googleapis.com";
  414. final String password = "Server key";
  415.  
  416. SmackCcsClient ccsClient = new SmackCcsClient();
  417.  
  418. try {
  419. ccsClient.connect(userName, password);
  420. } catch (XMPPException e) {
  421. e.printStackTrace();
  422. }
  423. }
  424. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement