Example usage for org.json.simple JSONObject containsKey

List of usage examples for org.json.simple JSONObject containsKey

Introduction

In this page you can find the example usage for org.json.simple JSONObject containsKey.

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:com.au.splashinc.JControl.Load.JsonLoaderHelper.java

private void populateMaps() {
    Set keys = jo.keySet();/*ww w.j  av  a 2s  .c  o m*/
    //Collection co = jo.values();
    Object[] objKey = keys.toArray();
    for (Object key : objKey) {
        System.out.println("Key: " + key.toString());
        JSONObject value = (JSONObject) jo.get(key);
        if (value.containsKey(ControllerAction.SIMPLE_BUTTON.toString())) {
            int button = (int) value.get(ControllerAction.SIMPLE_BUTTON.toString());
            AButtonDownUpExecute down = new SimpleKeyPress(button);
            keyDownMap.put(key.toString(), down);
            AButtonDownUpExecute up = new SimpleKeyRelease(button);
            keyUpMap.put(key.toString(), up);
        } else if (value.containsKey(ControllerAction.SIMPLE_MOUSE.toString())) {
            Object obj = value.get(ControllerAction.SIMPLE_MOUSE.toString());
            try {
                int mouse = Integer.parseInt(obj.toString());
                if (mouse != 224) {
                    AButtonDownUpExecute down = new SimpleMousePress(mouse);
                    mouseButtonDownMap.put(key.toString(), down);
                    AButtonDownUpExecute up = new SimpleMouseRelease(mouse);
                    mouseButtonUpMap.put(key.toString(), up);
                }
            } catch (NumberFormatException ex) {
                String mouse = obj.toString();
                String moveDirection = "";
                switch (mouse) {
                case "LeftRight":
                    moveDirection = "x";
                    break;
                case "UpDown":
                    moveDirection = "y";
                    break;
                default:
                    moveDirection = "unknown";
                    break;
                }
                if (moveDirection.equals("unknown")) {
                } else {
                    AMouseMoveExecute mme = new SimpleMouseMove(moveDirection);
                    mouseMoveMap.put(key.toString(), mme);
                }
            }
        }
    }
    System.out.println("Hello World");
}

From source file:hudson.plugins.memegen.MemegeneratorResponseException.java

protected JSONObject parseResponse(HttpURLConnection conn)
        throws ParseException, IOException, MemegeneratorResponseException, MemegeneratorJSONException {

    Reader rd = new InputStreamReader(conn.getInputStream());
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(rd);

    JSONObject jsonObject = (JSONObject) obj;
    if (!jsonObject.containsKey("success")) {
        throw new MemegeneratorJSONException(jsonObject, "success");
    }/*w  w  w.j a v a 2 s  . c o m*/
    if (!jsonObject.get("success").equals(true)) {
        throw new MemegeneratorResponseException(jsonObject);
    }

    if (!jsonObject.containsKey("result")) {
        throw new MemegeneratorJSONException(jsonObject, "result");
    }

    return jsonObject;
}

From source file:net.jakobnielsen.imagga.color.convert.ColorsConverter.java

@Override
public List<ColorResult> convert(String jsonString) {
    if (jsonString == null) {
        throw new ConverterException("The given JSON string is null");
    }/*from   www  . j av  a  2  s . c  om*/

    JSONObject json = (JSONObject) JSONValue.parse(jsonString);

    if (!json.containsKey(COLORS)) {
        throw new ConverterException(COLORS + " key missing from json : " + jsonString);
    }

    JSONArray jsonArray = (JSONArray) json.get(COLORS);
    List<ColorResult> colorResults = new ArrayList<ColorResult>();

    for (Object co : jsonArray) {

        JSONObject colorResultJSON = (JSONObject) co;
        String url = getString("url", colorResultJSON);
        JSONObject infoJSON = (JSONObject) colorResultJSON.get("info");
        List<ExtendedColor> imageColors = new ArrayList<ExtendedColor>();
        List<ExtendedColor> foregroundColors = new ArrayList<ExtendedColor>();
        List<ExtendedColor> backgroundColors = new ArrayList<ExtendedColor>();
        Double objectPercentage = null;
        Long colorVariance = null;

        addColors("image_colors", infoJSON, imageColors);
        addColors("foreground_colors", infoJSON, foregroundColors);
        addColors("background_colors", infoJSON, backgroundColors);

        if (infoJSON.containsKey(OBJECT_PERCENTAGE)) {
            objectPercentage = getDouble(OBJECT_PERCENTAGE, infoJSON);
        }

        if (infoJSON.containsKey("color_variance")) {
            colorVariance = getLong("color_variance", infoJSON);
        }

        colorResults.add(new ColorResult(url,
                new Info(imageColors, foregroundColors, backgroundColors, objectPercentage, colorVariance)));
    }

    return colorResults;
}

From source file:librarysystem.JSONHandlerElsiever.java

public List<Journal> parseJson() {
    //  String elsevier = "http://api.elsevier.com/content/search/scidir?apiKey=" + KEY + "&query=ttl(neural)";
    try {//from   ww  w.  ja  va 2s .  c om
        //URL uri = new URL(elsevier);

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(readUrl(url));
        JSONObject jsonObject = (JSONObject) obj;
        JSONObject searchObj = (JSONObject) jsonObject.get("search-results");

        if (searchObj.containsKey("entry")) {
            JSONArray entryarray = (JSONArray) searchObj.get("entry");
            Journal j = null;// new Journal();
            blist = new ArrayList<Journal>();
            //JSONArray autharray = null;

            for (int i = 0; i < entryarray.size(); i++) {
                j = new Journal();
                JSONObject jnext = (JSONObject) entryarray.get(i);

                j.setID(0);
                j.setAbstract(jnext.get("prism:teaser").toString());
                j.setPublication(jnext.get("prism:publicationName").toString());
                j.settitle(jnext.get("dc:title").toString());
                j.setisbn(jnext.get("prism:issn").toString());
                j.setYear(jnext.get("prism:coverDisplayDate").toString());
                String auths = "";

                if (jnext.containsKey("authors")) {
                    JSONObject jauthors = (JSONObject) jnext.get("authors");
                    JSONArray autharray = (JSONArray) jauthors.get("author");

                    for (int x = 0; x < autharray.size(); x++) {
                        JSONObject anext = (JSONObject) autharray.get(x);
                        auths = auths + " " + anext.get("given-name") + " " + anext.get("surname");
                    }
                    j.setauthors(auths);
                } else
                    j.setauthors("");

                blist.add(j);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return blist;
}

From source file:mml.handler.post.MMLPostAnnotationsHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {//from  w ww  . j  a  v  a2  s  . com
        if (ServletFileUpload.isMultipartContent(request)) {
            parseImportParams(request);
            if (docid != null && version1 != null && annotations != null) {
                Connection conn = Connector.getConnection();
                String[] docids = conn.listDocuments(Database.SCRATCH, docid + ".*", JSONKeys.DOCID);
                if (docids != null && docids.length > 0) {
                    HashMap<Integer, JSONObject> map = new HashMap<Integer, JSONObject>();
                    for (int i = 0; i < docids.length; i++) {
                        JSONObject jObj = fetchAnnotation(conn, Database.SCRATCH, docids[i]);
                        if (jObj != null && jObj.containsKey(JSONKeys.ID)) {
                            int key = ((Number) jObj.get(JSONKeys.ID)).intValue();
                            map.put(key, jObj);
                        }
                    }
                    // existing annotations are int eh map
                    // overwrite them with the new ones
                    // and add any new ones
                    // any annotations in SCRATCH have been put there 
                    // by this method
                    for (int i = 0; i < annotations.size(); i++) {
                        JSONObject ann = (JSONObject) annotations.get(i);
                        int key = ((Number) ann.get(JSONKeys.ID)).intValue();
                        if (map.containsKey(key)) {
                            JSONObject old = (JSONObject) map.get(key);
                            conn.removeFromDb(Database.SCRATCH, (String) old.get(JSONKeys.DOCID));
                            conn.putToDb(Database.SCRATCH,
                                    docid + "/" + version1 + "/" + UUID.randomUUID().toString(),
                                    ann.toJSONString());
                        }
                    }
                }
            }
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write("<p>OK</p>");
        }
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:copter.HCSR04.java

public String doAction(JSONObject jsonParam, WebSocket conn) {
    this.conn = conn;
    if (!jsonParam.containsKey("action")) {
        return "Missing 'action' param!";
    }//from  ww w. j  a  v  a2s  .  co  m
    String action = (String) jsonParam.get("action");
    switch (action) {
    case Constants.START_STREAM_DISTANCE_DATA:
        streamData = true;
        init();
        return "Distance data streaming started...";
    case Constants.STOP_STREAM_DISTANCE_DATA:
        streamData = false;
        if (thread != null) {
            thread.interrupt();
        }
        return "Distance data streaming stoped";
    }
    return "Unknown 'action' param: " + action;
}

From source file:com.precioustech.fxtrading.oanda.restapi.events.OrderFilledEventHandler.java

@Override
public EmailPayLoad generate(EventPayLoad<JSONObject> payLoad) {
    JSONObject jsonPayLoad = payLoad.getPayLoad();
    TradeableInstrument<String> instrument = new TradeableInstrument<String>(
            jsonPayLoad.containsKey(OandaJsonKeys.instrument)
                    ? jsonPayLoad.get(OandaJsonKeys.instrument).toString()
                    : "N/A");
    final String type = jsonPayLoad.get(OandaJsonKeys.type).toString();
    final long accountId = (Long) jsonPayLoad.get(OandaJsonKeys.accountId);
    final double accountBalance = jsonPayLoad.containsKey(OandaJsonKeys.accountBalance)
            ? ((Number) jsonPayLoad.get(OandaJsonKeys.accountBalance)).doubleValue()
            : 0.0;/*from w w  w  .  j av  a 2  s  .c  om*/
    final long orderId = (Long) jsonPayLoad.get(OandaJsonKeys.id);
    final String emailMsg = String.format(
            "Order event %s received on account %d. Order id=%d. Account balance after the event=%5.2f", type,
            accountId, orderId, accountBalance);
    final String subject = String.format("Order event %s for %s", type, instrument.getInstrument());
    return new EmailPayLoad(subject, emailMsg);
}

From source file:copter.CameraControl.java

public String doAction(JSONObject jsonParam) {
    if (!jsonParam.containsKey("action")) {
        return "Missing 'action' param!";
    }/*from  www .  java2 s  .c  o m*/
    String action = (String) jsonParam.get("action");
    switch (action) {
    case Constants.CAMERA_START_HTTP_STREMING_ACTION:
        int width = (int) (long) jsonParam.get("width");
        int height = (int) (long) jsonParam.get("height");
        int fps = (int) (long) jsonParam.get("fps");
        return this.startHttpStreaming(width, height, fps);
    case Constants.CAMERA_START_RTMP_STREAMING_ACTION:
        int w = (int) (long) jsonParam.get("width");
        int h = (int) (long) jsonParam.get("height");
        int _fps = (int) (long) jsonParam.get("fps");
        return this.startStreamingRtmp(w, h, _fps);
    case Constants.CAMERA_STOP_STREAMING_COMMAND:
        return this.stopStreaming();
    }
    return "Unknown 'action' param: " + action;
}

From source file:net.amigocraft.mpt.command.AddRepositoryCommand.java

@Override
public void handle() {
    if (!checkPerms())
        return;/*  w w w  . ja va 2s  .c om*/
    if (args.length == 2) {
        final String path = args[1];
        // get the main array from the JSON object
        JSONObject repos = (JSONObject) Main.repoStore.get("repositories");
        // verify the repo hasn't already been added
        Set<Map.Entry> entries = repos.entrySet();
        for (Map.Entry e : entries) { // iterate repos in local store
            JSONObject o = (JSONObject) e.getValue();
            // check URL
            if (o.containsKey("url") && o.get("url").toString().equalsIgnoreCase(path)) {
                sender.sendMessage(ERROR_COLOR + "[MPT] The repository at that URL has already been added!");
                return;
            }
        }
        // no way we're making the main thread wait for us to open and read the stream
        Bukkit.getScheduler().runTaskAsynchronously(Main.plugin, new Runnable() {
            public void run() {
                try {
                    threadSafeSendMessage(sender, INFO_COLOR + "[MPT] Attempting connection to repository...");
                    String id = addRepository(path);
                    threadSafeSendMessage(sender,
                            INFO_COLOR + "[MPT] Successfully added " + "repository under ID " + ID_COLOR + id
                                    + INFO_COLOR + " to local store! You may now use " + COMMAND_COLOR
                                    + "/mpt update" + INFO_COLOR + " to fetch available packages.");
                } catch (MPTException ex) {
                    threadSafeSendMessage(sender, ERROR_COLOR + "[MPT] " + ex.getMessage());
                }
            }

        });
    } else if (args.length < 2)
        sender.sendMessage(ERROR_COLOR + "[MPT] Too few arguments! Type " + COMMAND_COLOR + "/mpt help "
                + ERROR_COLOR + "for help");
    else
        sender.sendMessage(ERROR_COLOR + "[MPT] Too many arguments! Type " + COMMAND_COLOR + "/mpt help "
                + ERROR_COLOR + "for help");
}

From source file:functions.TestWriteOptions.java

/**
 * create a class and then write it to file
 *///from  ww w. ja  v a 2 s .  c  om
@Test
public void testCreateObject() {
    NuBotOptions opt = new NuBotOptions();
    opt.apiKey = "test";
    opt.setExchangeName("testexchange");
    Currency c = Currency.createCurrency("NBT");
    Currency usd = Currency.createCurrency("USD");
    opt.setPair(new CurrencyPair(c, usd));
    String testout = Settings.TESTS_CONFIG_PATH + "/" + "test_out.json";
    SaveOptions.saveOptionsPretty(opt, testout);
    File newout = new File(testout);
    assertTrue(newout.exists());

    try {
        JSONObject inputJSON = ParseOptions.parseSingleJsonFile(testout);
        assertTrue(inputJSON.containsKey(ParseOptions.exchangename));
    } catch (Exception e) {
        assertTrue(false);
    }

    //assertTrue(inputJSON.containsKey("options"));
    //JSONObject optionsJSON = ParseOptions.getOptionsKey(inputJSON);

}