Example usage for org.json.simple JSONValue parseWithException

List of usage examples for org.json.simple JSONValue parseWithException

Introduction

In this page you can find the example usage for org.json.simple JSONValue parseWithException.

Prototype

public static Object parseWithException(String s) throws ParseException 

Source Link

Usage

From source file:com.jadarstudios.rankcapes.bukkit.RankCapesBukkit.java

/**
 * Parses cape pack metadata./*from   w  w  w  .j a  v  a  2s .  co m*/
 *
 * @param input zip input stream of the cape pack.
 */
private void parseMetadata(ZipInputStream input) throws InvalidCapePackException, IOException, ParseException {
    Object root = JSONValue.parseWithException(new InputStreamReader(input));
    JSONObject object = (JSONObject) root;

    CapePackValidator.validatePack(object);

    for (Object key : object.keySet()) {
        if (key instanceof String) {
            this.availableCapes.add((String) key);
        }
    }
}

From source file:eu.edisonproject.training.wsd.BabelNet.java

private List<String> getcandidateWordIDs(String language, String word)
        throws IOException, ParseException, FileNotFoundException, InterruptedException {
    //        if (db == null || db.isClosed()) {
    //            loadCache();
    //        }//  w w w  .  j a  v  a2 s.  co  m
    List<String> ids = getFromWordIDDB(word);
    if (ids != null && ids.size() == 1 && ids.get(0).equals("NON-EXISTING")) {
        return null;
    }
    //        List<String> ids = null;
    language = language.toUpperCase();
    if (ids == null || ids.isEmpty()) {
        ids = new ArrayList<>();
        URL url = new URL(
                "http://babelnet.io/v2/getSynsetIds?word=" + word + "&langs=" + language + "&key=" + this.key);
        LOGGER.log(Level.FINE, url.toString());
        String genreJson = IOUtils.toString(url);
        int count = 0;
        try {
            handleKeyLimitException(genreJson);
        } catch (IOException ex) {
            if (ex.getMessage().contains("Your key is not valid or the daily requests limit has been reached")
                    && count < keys.length - 1) {
                count++;
                return getcandidateWordIDs(language, word);
            } else {
                throw ex;
            }
        }

        Object obj = JSONValue.parseWithException(genreJson);
        if (obj instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) obj;
            for (Object o : jsonArray) {
                JSONObject jo = (JSONObject) o;
                if (jo != null) {
                    String id = (String) jo.get("id");
                    if (id != null) {
                        ids.add(id);
                    }
                }
            }
        } else if (obj instanceof JSONObject) {
            JSONObject jsonObj = (JSONObject) obj;
            String id = (String) jsonObj.get("id");
            if (id != null) {
                ids.add(id);
            }
        }
        //            if (db.isClosed()) {
        //                loadCache();
        //            }

        if (ids.isEmpty()) {
            ids.add("NON-EXISTING");
            putInWordINDB(word, ids);
            return null;
        }
        putInWordINDB(word, ids);
    }
    return ids;
}

From source file:mensajes.SmackCcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 *
 * @param senderId Your GCM project number
 * @param apiKey API Key of your project
 *//*from   w ww .ja v a2  s. c  o  m*/
public void connect(long senderId, String apiKey) throws XMPPException, IOException, SmackException {
    ConnectionConfiguration config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT);
    config.setSecurityMode(SecurityMode.enabled);
    config.setReconnectionAllowed(true);
    config.setRosterLoadedAtLogin(false);
    config.setSendPresence(false);
    config.setSocketFactory(SSLSocketFactory.getDefault());

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

    connection.addConnectionListener(new LoggingConnectionListener());

    // 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
                    handleUpstreamMessage(jsonObject);

                    // Send ACK to CCS
                    String messageId = (String) jsonObject.get("message_id");
                    String from = (String) jsonObject.get("from");
                    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 if ("control".equals(messageType.toString())) {
                    // Process control message
                    handleControlMessage(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, "Failed to process packet", 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(senderId + "@gcm.googleapis.com", apiKey);
}

From source file:cpd4414.assign2.OrderQueueTest.java

@Test
public void testGeneratereportByOrder() throws OrderQueue.IfNoCustomer, OrderQueue.IfNoPurchase,
        OrderQueue.EmptyTimeReceived, OrderQueue.EmptyTimeprocessed, ParseException {

    OrderQueue orderqueue = new OrderQueue();

    Order order = new Order("Cust1", "Name1");
    order.addPurchase(new Purchase(1, 8));
    orderqueue.add(order);//from ww w  .  ja v a  2  s. c o m
    Order order_new = new Order("Cust2", "Name2");
    order_new.addPurchase(new Purchase(2, 4));
    orderqueue.add(order_new);
    Order ordernext = orderqueue.nextOrder();
    orderqueue.process(ordernext);

    orderqueue.methodfulfill(ordernext);

    JSONObject expresult = new JSONObject();
    JSONArray orders = new JSONArray();
    JSONObject o1 = new JSONObject();
    o1.put("customerId", "Cust1");
    o1.put("customerName", "Name1");
    o1.put("timeReceived", new Date().toString());
    o1.put("timeProcessed", new Date().toString());
    o1.put("timeFulfilled", new Date().toString());
    JSONArray pList = new JSONArray();
    JSONObject p1 = new JSONObject();
    p1.put("ProductId", 1);
    p1.put("quantity", 8);
    pList.add(p1);
    o1.put("purchases", pList);
    o1.put("notes", null);
    orders.add(o1);
    JSONObject o2 = new JSONObject();
    o2.put("customerId", "Cust2");
    o2.put("customerName", "Name2");
    o2.put("timeReceived", new Date().toString());
    o2.put("timeProcessed", null);
    o2.put("timeFulfilled", null);
    JSONArray pList1 = new JSONArray();
    JSONObject p2 = new JSONObject();
    p2.put("ProductId", 2);
    p2.put("quantity", 4);
    pList1.add(p2);
    o2.put("purchases", pList1);
    o2.put("notes", null);
    orders.add(o2);
    expresult.put("orders", orders);

    String resultString = orderqueue.generateReport();

    //  JSONObject newsetof = (JSONObject) JSONValue.parseWithException(expresult.toJSONString());
    JSONObject result = (JSONObject) JSONValue.parseWithException(resultString);
    System.out.println(result);
    assertEquals(expresult.toJSONString(), result.toJSONString());

}

From source file:net.maxgigapop.mrs.driver.GenericRESTDriver.java

@Override
@Asynchronous/*from  w ww  .  ja va  2 s.  c om*/
@SuppressWarnings("empty-statement")
public Future<String> pullModel(Long driverInstanceId) {
    DriverInstance driverInstance = DriverInstancePersistenceManager.findById(driverInstanceId);
    if (driverInstance == null) {
        throw new EJBException(String.format("pullModel cannot find driverInance(id=%d)", driverInstanceId));
    }
    String subsystemBaseUrl = driverInstance.getProperty("subsystemBaseUrl");
    if (subsystemBaseUrl == null) {
        throw new EJBException(String.format("%s has no property key=subsystemBaseUrl", driverInstance));
    }
    if (DriverInstancePersistenceManager.getDriverInstanceByTopologyMap() == null
            || !DriverInstancePersistenceManager.getDriverInstanceByTopologyMap()
                    .containsKey(driverInstance.getTopologyUri())) {
        return new AsyncResult<>("INITIALIZING");
    }
    // sync on cached DriverInstance object = once per driverInstance to avoid write multiple vi of same version 
    DriverInstance syncOnDriverInstance = DriverInstancePersistenceManager.getDriverInstanceByTopologyMap()
            .get(driverInstance.getTopologyUri());
    synchronized (syncOnDriverInstance) {
        String version = null;
        String ttlModel = null;
        String creationTimestamp = null;
        try {
            if (driverInstance.getHeadVersionItem() != null) {
                URL url = new URL(
                        subsystemBaseUrl + "/model/" + driverInstance.getHeadVersionItem().getReferenceUUID());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                String status = this.executeHttpMethod(url, conn, "GET", null);
                if (status.toUpperCase().equals("LATEST")) {
                    return new AsyncResult<>("SUCCESS");
                }
            }
            // pull model from REST API
            URL url = new URL(subsystemBaseUrl + "/model");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            String responseStr = this.executeHttpMethod(url, conn, "GET", null);
            JSONObject responseJSON = (JSONObject) JSONValue.parseWithException(responseStr);
            version = responseJSON.get("version").toString();
            if (version == null || version.isEmpty()) {
                throw new EJBException(String.format("%s pulled model from subsystem with null/empty version",
                        driverInstance));
            }
            ttlModel = responseJSON.get("ttlModel").toString();
            if (ttlModel == null || ttlModel.isEmpty()) {
                throw new EJBException(String.format(
                        "%s pulled model from subsystem with null/empty ttlModel content", driverInstance));
            }
            creationTimestamp = responseJSON.get("creationTime").toString();
            if (creationTimestamp == null || creationTimestamp.isEmpty()) {
                throw new EJBException(String
                        .format("%s pulled model from subsystem with null/empty creationTime", driverInstance));
            }
        } catch (IOException ex) {
            throw new EJBException(
                    String.format("%s failed to connect to subsystem with exception (%s)", driverInstance, ex));
        } catch (ParseException ex) {
            throw new EJBException(
                    String.format("%s failed to parse pulled information from subsystem with exception (%s)",
                            driverInstance, ex));
        }
        VersionItem vi = null;
        DriverModel dm = null;
        try {
            // check if this version has been pulled before
            vi = VersionItemPersistenceManager.findByReferenceUUID(version);
            if (vi != null) {
                return new AsyncResult<>("SUCCESS");
            }
            // create new driverDelta and versioItem
            OntModel ontModel = ModelUtil.unmarshalOntModel(ttlModel);
            dm = new DriverModel();
            dm.setCommitted(true);
            dm.setOntModel(ontModel);
            Date creationTime = new Date(Long.parseLong(creationTimestamp));
            dm.setCreationTime(creationTime);
            ModelPersistenceManager.save(dm);
            vi = new VersionItem();
            vi.setModelRef(dm);
            vi.setReferenceUUID(version);
            vi.setDriverInstance(driverInstance);
            VersionItemPersistenceManager.save(vi);
            driverInstance.setHeadVersionItem(vi);
            VersionItemPersistenceManager.save(vi);
            logger.info(String.format("persisted %s", vi));
        } catch (Exception e) {
            try {
                if (dm != null) {
                    ModelPersistenceManager.delete(dm);
                }
                if (vi != null) {
                    VersionItemPersistenceManager.delete(vi);
                }
            } catch (Exception ex) {
                ; // do nothing (logging?)
            }
            throw new EJBException(
                    String.format("pullModel on %s raised exception[%s]", driverInstance, e.getMessage()));
        }
    }
    return new AsyncResult<>("SUCCESS");
}

From source file:jp.aegif.nemaki.rest.GroupResource.java

@PUT
@Path("/{apiType: add|remove}/{id}")
@Produces(MediaType.APPLICATION_JSON)/*from w w  w  . j av  a 2  s  .co m*/
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String updateMembers(@PathParam("repositoryId") String repositoryId, @PathParam("id") String groupId,
        @PathParam("apiType") String apiType, @FormParam(FORM_MEMBER_USERS) String users,
        @FormParam(FORM_MEMBER_GROUPS) String groups, @Context HttpServletRequest httpRequest) {
    boolean status = true;
    JSONObject result = new JSONObject();
    JSONArray errMsg = new JSONArray();

    //Existing Group
    Group group = principalService.getGroupById(repositoryId, groupId);
    if (group == null) {
        status = false;
        addErrMsg(errMsg, ITEM_GROUP, ErrorCode.ERR_NOTFOUND);
    }

    //Parse JSON string from input parameter
    JSONArray usersAry = new JSONArray();
    if (users != null) {
        try {
            usersAry = (JSONArray) JSONValue.parseWithException(users); //JSON parse validation
        } catch (Exception ex) {
            ex.printStackTrace();
            status = false;
            addErrMsg(errMsg, ITEM_MEMBER_USERS, ErrorCode.ERR_PARSEJSON);
        }
    }

    JSONArray groupsAry = new JSONArray();
    if (groups != null) {
        try {
            groupsAry = (JSONArray) JSONValue.parseWithException(groups); //JSON parse validation
        } catch (Exception ex) {
            ex.printStackTrace();
            status = false;
            addErrMsg(errMsg, ITEM_MEMBER_GROUPS, ErrorCode.ERR_PARSEJSON);
        }
    }

    //Edit members info of the group
    if (status) {
        //Group info
        setModifiedSignature(httpRequest, group);

        //Member(User) info
        List<String> usersList = editUserMembers(repositoryId, usersAry, errMsg, apiType, group);
        group.setUsers(usersList);

        //Member(Group) info
        List<String> groupsList = editGroupMembers(repositoryId, groupsAry, errMsg, apiType, group);
        group.setGroups(groupsList);

        //Update
        if (apiType.equals(API_ADD)) {
            try {
                principalService.updateGroup(repositoryId, group);
            } catch (Exception ex) {
                ex.printStackTrace();
                status = false;
                addErrMsg(errMsg, ITEM_GROUP, ErrorCode.ERR_UPDATEMEMBERS);
            }
        } else if (apiType.equals(API_REMOVE)) {
            try {
                principalService.updateGroup(repositoryId, group);
            } catch (Exception ex) {
                ex.printStackTrace();
                status = false;
                addErrMsg(errMsg, ITEM_GROUP, ErrorCode.ERR_UPDATEMEMBERS);
            }
        }
    }

    result = makeResult(status, result, errMsg);
    return result.toJSONString();
}

From source file:br.com.ulife.googlexmpp.SmackCcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 *
 * @param username GCM_SENDER_ID@gcm.googleapis.com
 * @param password API Key/*  www  .  j a  v a2s . c  om*/
 * @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 jsonObject = (Map) 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);
}

From source file:com.mch.registry.ccs.server.CcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 *
 * @throws XMPPException/*  www  . ja v a 2 s  .  c  om*/
 */
public void connect() 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(mDebuggable);

    // -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> jsonMap = (Map<String, Object>) JSONValue.parseWithException(json);
                handleMessage(jsonMap);
            } 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(mProjectId + "@gcm.googleapis.com", mApiKey);

    logger.log(Level.INFO, "logged in: " + mProjectId);
}

From source file:eu.edisonproject.training.wsd.BabelNet.java

private Map<String, Double> getEdgeIDs(String language, CharSequence id, String relation)
        throws MalformedURLException, IOException, ParseException, Exception {
    //        if (db == null || db.isClosed()) {
    //            loadCache();
    //        }/* ww w. j  a  v a  2  s .  co m*/
    String genreJson = getFromEdgesDB(id);
    if (genreJson == null) {
        URL url = new URL("http://babelnet.io/v2/getEdges?id=" + id + "&key=" + this.key);
        LOGGER.log(Level.FINE, url.toString());
        genreJson = IOUtils.toString(url);
        handleKeyLimitException(genreJson);
        if (genreJson != null) {
            addToEdgesDB(id, genreJson);
        }
        if (genreJson == null) {
            addToEdgesDB(id, "NON-EXISTING");
        }
    }

    Object obj = JSONValue.parseWithException(genreJson);
    JSONArray edgeArray = null;
    if (obj instanceof org.json.simple.JSONObject) {
        JSONObject jsonObj = (JSONObject) obj;
    } else {
        edgeArray = (JSONArray) obj;
    }

    Map<String, Double> map = new HashMap<>();
    for (Object o : edgeArray) {
        JSONObject pointer = (JSONObject) ((JSONObject) o).get("pointer");
        String relationGroup = (String) pointer.get("relationGroup");
        String target = (String) ((JSONObject) o).get("target");
        Double normalizedWeight = (Double) ((JSONObject) o).get("normalizedWeight");
        Double weight = (Double) ((JSONObject) o).get("weight");
        if (relationGroup.equals(relation)) {
            map.put(target, ((normalizedWeight + weight) / 2.0));
        }
    }
    return map;
}

From source file:com.example.CcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 * @throws XMPPException/*  ww  w.  j  a v a 2s. co  m*/
 */
public void connect() 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(mDebuggable);

    // -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(packet -> {
        logger.log(Level.INFO, "Received: " + packet.toXML());
        System.out.print(packet.toXML());
        Message incomingMessage = (Message) packet;
        GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE);
        String json = gcmPacket.getJson();
        System.out.print(json);
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> jsonMap = (Map<String, Object>) JSONValue.parseWithException(json);

            handleMessage(jsonMap);
        } 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((PacketInterceptor) packet -> logger.log(Level.INFO, "Sent: {0}", packet.toXML()), new PacketTypeFilter(Message.class));

    connection.login(mProjectId + "@gcm.googleapis.com", mApiKey);
    logger.log(Level.INFO, "logged in: " + mProjectId);
}