Example usage for org.json.simple JSONValue parse

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

Introduction

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

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:com.punyal.blackhole.core.net.lwm2m.LWM2Msniffer.java

private void checkConnectedMulles(String response) {
    JSONArray jsonArray = (JSONArray) JSONValue.parse(response);
    Iterator i = jsonArray.iterator();
    LWM2Mdevice device;/*from ww  w . j a  va  2s .c  om*/
    while (i.hasNext()) {
        JSONObject json = (JSONObject) i.next();
        String name = json.get("endPoint").toString();
        String id = json.get("registrationId").toString();
        String host = json.get("address").toString().substring(1);
        int port = Integer.parseInt(json.get("port").toString());
        //System.out.println(name+" ("+id+") "+host+":"+port);

        device = devicesList.getDeviceByName(name);

        if (device == null) // Add new device
            devicesList.addDevice(name, id, host, port);
        else {
            if (!device.getId().equals(id)) {
                //System.out.println(name+" new id:"+id+ " old id:"+device.getId());
                //System.out.println("Last update:"+ device.getLastUpdate());
                device.updateID(id);
                //System.out.println("Current time:"+ device.getLastUpdate());
            }
        }
    }
}

From source file:com.rylinaux.plugman.util.BukGetUtil.java

/**
 * Get the slug of the plugin.//  w  w  w .j  a  v  a 2 s . c  o  m
 *
 * @param name the name of the plugin.
 * @return the slug of the plugin.
 */
public static String getPluginSlug(String name) {

    HttpClient client = HttpClients.createMinimal();
    HttpGet get = new HttpGet(API_BASE_URL + "search/slug/like/" + name + "?fields=plugin_name,slug");

    try {

        HttpResponse response = client.execute(get);
        String body = IOUtils.toString(response.getEntity().getContent());

        JSONArray array = (JSONArray) JSONValue.parse(body);

        for (int i = 0; i < array.size(); i++) {
            JSONObject json = (JSONObject) array.get(i);
            String pluginName = (String) json.get("plugin_name");
            if (name.equalsIgnoreCase(pluginName))
                return (String) json.get("slug");
        }

    } catch (IOException e) {

    }

    return null;

}

From source file:mml.handler.get.MMLGetDialectHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {//w w  w . j  a v  a 2s . c o m
        docid = request.getParameter(Params.DOCID);
        version1 = request.getParameter(Params.VERSION1);
        if (version1 != null && version1.length() > 0 && !docid.endsWith(version1))
            docid += version1;
        // look for a dialect file with the full path then
        // if not found progressively pop off segments from the end
        String res = null;
        Connection conn = Connector.getConnection();
        while (res == null && docid.length() > 0) {
            res = conn.getFromDb(Database.DIALECTS, docid);
            if (res == null)
                docid = Utils.chomp(docid);
        }
        if (res == null)
            res = DEFAULT_DIALECT;
        JSONObject jObj = (JSONObject) JSONValue.parse(res);
        String dialect = (String) jObj.get(JSONKeys.BODY);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(dialect);
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:formatter.handler.get.Version1Handler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws FormatterException {
    try {//from w  ww  .  j  ava  2s . c o  m
        Connection conn = Connector.getConnection();
        docid = request.getParameter(Params.DOCID);
        if (docid != null && docid.length() > 0) {
            String res = conn.getFromDb(Database.METADATA, docid);
            JSONObject jObj1 = null;
            if (res != null) {
                System.out.println("found metadata for " + docid);
                jObj1 = (JSONObject) JSONValue.parse(res);
                if (jObj1.containsKey(JSONKeys.VERSION1)) {
                    System.out.println("found version1 in metadata");
                    metadataValue = (String) jObj1.get(JSONKeys.VERSION1);
                }
            }
            if (metadataValue == null) {
                System.out.println("Getting version1 from cortex");
                getMetadataFromCortex(conn);
            }
        } else {
            metadataValue = "";
            System.out.println("version1 not found for " + docid + "; setting to empty string");
        }
        System.out.println("version1=" + metadataValue);
        response.setContentType("text/plain");
        response.getWriter().write(metadataValue);
    } catch (Exception e) {
        throw new FormatterException(e);
    }
}

From source file:eu.anynet.java.util.HttpClient.java

/**
 * Request to JSONObject (max 2048 KB)//w  w  w  .j  a v  a  2s . c o  m
 * @param request The request object
 * @return The JSON Object
 * @throws IOException
 */
public static JSONObject toJsonObject(Request request) throws IOException {
    String text = toString(request, DEFAULT_MAXDOWNLOADINKBYTE * 1024);
    JSONObject json = (JSONObject) JSONValue.parse(text);
    return json;
}

From source file:config.PGConfig.java

private void readAllConfig() {
    String confPath = System.getProperty("confpath");
    if (PGHelper.isNullOrEmpty(confPath)) {
        confPath = PGHelper.valid(System.getProperty("apppath"), ".") + "/config/";
    }// w w w .  j av  a  2  s  .  c  om

    for (String config : CONFIGS) {
        try {
            String configFile = confPath + config + ".xfj";
            FileReader configReader = new FileReader(new File(configFile));
            Map<String, Object> configData = (Map<String, Object>) JSONValue.parse(configReader);

            allConfigs.put(config, configData.get(config));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PGConfig.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java

@Override
public void run() {

    Connection connection = null;
    Channel channel = null;// w  w w. j a v  a 2 s  .c  o  m
    try {
        ConnectionFactory factory = new ConnectionFactory();
        logger.info("Starting RabbitMQDaemon, MQ IP = " + hostname);
        factory.setHost(hostname);

        connection = factory.newConnection();
        channel = connection.createChannel();

        channel.queueDeclare(rpcQueueName, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(rpcQueueName, false, consumer);

        while (true) {
            String response = null;

            // Block and fetch next msg from queue
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                String message = new String(delivery.getBody(), "UTF-8");
                logger.trace("Received msg: " + message);

                // Convert the message to a JSON request object
                JSONObject request = (JSONObject) JSONValue.parse(message);

                // Delegate to the server request handler for handling the
                // request and computing an answer
                JSONObject reply = serverRequestHandler.handleRequest(request);

                // Convert the answer back into a string for replying to
                // client
                response = reply.toJSONString();
            } catch (Exception e) {
                logger.error(" Exception in MQDAemon run()/while true] " + e.toString());
                response = "wrong";
            } finally {
                logger.trace("Returning answer: " + response);
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                logger.trace("Answer acknowledged.");
            }
        }
    } catch (Exception e) {
        logger.error("Exception in daemon's outer loop: nested exception" + e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:mml.handler.get.MMLGetImgHandler.java

/**
 * Create the list of images/*from  ww w .j a  va 2  s  .c o  m*/
 * @param req the http request
 * @param map the page reference to dimensions map
 * @return the images as a sequence of IMGs inside divs
 */
String createImgs(HttpServletRequest req, HashMap<String, String> map) {
    Element images = new Element("div");
    images.addAttribute("id", "images");
    Set<String> keys = map.keySet();
    String[] names = new String[keys.size()];
    keys.toArray(names);
    if (pageRefs == null) {
        ImageComparator comp = new ImageComparator();
        Arrays.sort(names, comp);
    } else {
        names = sortByPageRefs(names);
    }
    for (String name : names) {
        String jDoc = map.get(name);
        JSONObject info = (JSONObject) JSONValue.parse(jDoc);
        Element wrap = new Element("div");
        wrap.addAttribute("class", "image");
        Element img = new Element("img");
        String jDocId = (String) info.get(JSONKeys.DOCID);
        String src = "/" + jDocId;
        img.addAttribute("src", src);
        img.addAttribute("id", "image_" + name);
        //String mimetype = (String)info.get("mimetype");
        int width = ((Number) info.get("width")).intValue();
        int height = ((Number) info.get("height")).intValue();
        img.addAttribute("style", "width: 100%; max-width: " + width + "px");
        img.addAttribute("data-width", Integer.toString(width));
        img.addAttribute("data-height", Integer.toString(height));
        img.addAttribute("data-ref", name);
        wrap.addChild(img);
        images.addChild(wrap);
    }
    return images.toString();
}

From source file:com.jgoetsch.eventtrader.test.ProfidingMsgParserTest.java

@SuppressWarnings("rawtypes")
public void testExit() throws Exception {
    msgParser.parseData("alert", (Map) JSONValue.parse(
            "{\"entry\":{\"exitPrice\":3.2,\"dateAdded\":1344346779000,\"newsletterIds\":[3,26,2,24],\"type\":\"Short Stock\",\"dateClosed\":1344347916726,\"amount\":null,\"username\":\"timothysykes\",\"compareDate\":1344347916726,\"ticker\":\"CRMB\",\"action\":\"Covered\",\"entryPrice\":3.1,\"shortSell\":true,\"shortUrl\":\"1Mn25g\",\"optionType\":\"CALL\",\"callOption\":true,\"entryComments\":\"Spiked waaaay too much on low volume so I shorted some, shares available at IB and SureTrader\",\"percentage\":null,\"optionExpiration\":null,\"entryDate\":1344346779000,\"futuresMonth\":0,\"futuresYear\":0,\"shares\":300,\"entryType\":\"STOCK\",\"exitDate\":1344347916726,\"optionStrike\":null,\"comments\":\"Superman now spiking it due to its low float, took a small loss on the remainder of my short, overall small profit, definite potential reshort on any more big spike\",\"openTrade\":false},\"msgId\":28001,\"image\":\"http://a1.twimg.com/profile_images/1166026278/TimCover1_normal.jpg\"}"),
            new MsgHandler() {
                public boolean newMsg(Msg msg) {
                    Assert.assertEquals(TradeSignal.class, msg.getClass());
                    TradeSignal trade = (TradeSignal) msg;
                    Assert.assertEquals("timothysykes", trade.getSourceName());
                    Assert.assertEquals("http://a1.twimg.com/profile_images/1166026278/TimCover1_normal.jpg",
                            trade.getImageUrl());
                    Assert.assertEquals(1344347916726L, trade.getDate().toDate().getTime());
                    Assert.assertEquals(TradeSignal.TYPE_COVER, trade.getType());
                    Assert.assertEquals(Contract.stock("CRMB"), trade.getContract());
                    Assert.assertEquals(300, trade.getNumShares());
                    Assert.assertEquals(3.2, trade.getPrice());
                    return false;
                }// www .  j av  a 2 s.  c o  m
            });
}

From source file:compare.handler.CompareHandler.java

/**
 * Get the document body of the given urn or null
 * @param db the database where it is/*ww  w. j a v  a2 s  .c om*/
 * @param docID the docID of the resource
 * @return the document body or null if not present
 */
private static String getDocumentBody(String db, String docID) throws CompareException {
    try {
        String jStr = Connector.getConnection().getFromDb(db, docID);
        if (jStr != null) {
            JSONObject jDoc = (JSONObject) JSONValue.parse(jStr);
            if (jDoc != null) {
                String body = (String) jDoc.get(JSONKeys.BODY);
                if (body != null)
                    return body;
            }
        }
        throw new CompareException("document " + db + "/" + docID + " not found");
    } catch (Exception e) {
        throw new CompareException(e);
    }
}