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:compare.handler.get.MetadataHandler.java

/**
 * Handle a request to get some metadata for a document
 * @param request the http request//from www . ja  v  a  2s.co m
 * @param response the response
 * @param urn the current urn (ignored)
 * @throws CompareException if the resource could not be found
 */
public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws CompareException {
    try {
        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) {
                jObj1 = (JSONObject) JSONValue.parse(res);
                if (jObj1.containsKey(metadataKey)) {
                    metadataValue = (String) jObj1.get(metadataKey);
                    saved = true;
                }
            }
            if (metadataValue == null)
                getMetadataFromCortex(conn);
            saveToMetadata(jObj1, conn);
        } else
            metadataValue = "";
        response.setContentType("text/plain");
        response.getWriter().write(metadataValue);
    } catch (Exception e) {
        throw new CompareException(e);
    }
}

From source file:com.baystep.jukeberry.JsonConfiguration.java

public void load(String fileName) {
    BerryLogger.LOG.info("Loading configuration file...");

    File configFile = new File(fileName);
    if (configFile.exists()) {
        JSONParser jparser = new JSONParser();
        try {//from   ww  w . j a  va 2  s  .  c  om
            Object obj = jparser.parse(new FileReader(configFile));
            jsonConfig = (JSONObject) obj;

            if (jsonConfig.containsKey("disable")) {
                String dOpt = (String) jsonConfig.get("disable");
                setDisableOption(dOpt);
            }

            if (jsonConfig.containsKey("http server")) {
                JSONObject httpObj = (JSONObject) jsonConfig.get("http server");
                if (httpObj.containsKey("port"))
                    httpPort = getInt(httpObj, "port");
            }

            if (jsonConfig.containsKey("websocket server")) {
                JSONObject wsObj = (JSONObject) jsonConfig.get("websocket server");
                if (wsObj.containsKey("port"))
                    websocketPort = getInt(wsObj, "port");
            }

            if (jsonConfig.containsKey("music player")) {
                JSONObject mpObj = (JSONObject) jsonConfig.get("music player");

                if (mpObj.containsKey("start service")) {
                    mpStartService = (String) mpObj.get("start service");
                }

                if (mpObj.containsKey("local directories")) {
                    mpDirectories = getStringArray(mpObj, "local directories");
                }

                if (mpObj.containsKey("sources")) {
                    mpSources = getSourceDescriptionArray(mpObj, "sources");
                }
            }

        } catch (IOException | org.json.simple.parser.ParseException ex) {
            BerryLogger.LOG.log(Level.WARNING, "Failed to parse configuration file: {0}", ex.getMessage());
        }
    } else {
        BerryLogger.LOG.warning("Failed to load the configuration file!");
    }
}

From source file:controllers.LoginController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   ww  w.jav a  2s. co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //User user = (User) request.getAttribute("user");
    //if (user != null) {
    // User has been already registered
    //response.sendRedirect(request.getContextPath() + "/home");
    //} else {
    // Login in user
    String email = request.getParameter("email"), password = request.getParameter("pass");

    JSONObject object = null;
    object = (JSONObject) ISConnector.validateLogin(email, password);
    if (object.containsKey("token")) {
        Cookie cookie = new Cookie("token", (String) object.get("token"));
        cookie.setPath("/");
        long expiredDate = -1;
        if (object.containsKey("expiry_date")) {
            expiredDate = (long) object.get("expiry_date") - new Timestamp(new Date().getTime()).getTime();
            expiredDate /= 1000;
            cookie.setMaxAge((int) expiredDate);
        }
        response.addCookie(cookie);
        response.sendRedirect(request.getContextPath() + "/home");
    } else if (object.containsKey("error")) {
        request.setAttribute("error", (String) object.get("error"));
        String error = (String) object.get("error");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet coba2</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(error);
            out.println("</body>");
            out.println("</html>");

        }
        //doGet(request, response);
    } else {
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet coba2</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(object);
            out.println("</body>");
            out.println("</html>");

        }
    }
    //}
}

From source file:com.turt2live.uuid.turt2live.v1.ApiV1Service.java

@Override
protected PlayerRecord parsePlayerRecord(String json) {
    if (json == null)
        return null;

    JSONObject jsonValue = (JSONObject) JSONValue.parse(json);
    if (jsonValue.containsKey("uuid") && jsonValue.containsKey("name")) {
        String uuidStr = (String) jsonValue.get("uuid");
        String name = (String) jsonValue.get("name");

        if (name.equals("unknown") || uuidStr.equals("unknown"))
            return null;

        UUID uuid = convertUuid(uuidStr);

        return new Turt2LivePlayerRecord(uuid, name);
    }//from   w  w w.  jav  a2  s  .  c  o  m

    return null;
}

From source file:com.turt2live.uuid.turt2live.v1.ApiV1Service.java

@Override
public String[] getNameHistory(UUID uuid) {
    String response = doUrlRequest(getConnectionUrl() + "/history/" + convertUuid(uuid));
    if (response != null) {
        JSONObject json = (JSONObject) JSONValue.parse(response);

        if (json.containsKey("names")) {
            JSONArray array = (JSONArray) json.get("names");
            String[] names = new String[array.size()];

            int i = 0;
            for (Object o : array) {
                names[i] = o.toString();
                i++;/*w  w w. ja  v a  2  s  . c o  m*/
            }

            return names;
        }
    }

    return null;
}

From source file:lockers.Usuarios.java

private void getUserData(String userId) {
    JSONObject obj = Utils.getJSONObjectFromURL("http://127.0.0.1:8000/Users/" + userId + "/?format=json");

    System.out.println(obj.size());
    if (obj.containsKey("Error")) {
        boolNewUser = true;//w  w  w  .  j a v a2  s . c om
        return;
    }

    this.txtName.setText(obj.get("user_name").toString());
    this.txtFLN.setText(obj.get("user_ap").toString());
    this.txtMLN.setText(obj.get("user_am").toString());
}

From source file:com.precioustech.fxtrading.oanda.restapi.streaming.marketdata.OandaMarketDataStreamingService.java

@Override
public void startMarketDataStreaming() {
    stopMarketDataStreaming();/*ww w.  ja v a  2  s.  c o m*/
    this.streamThread = new Thread(new Runnable() {

        @Override
        public void run() {
            CloseableHttpClient httpClient = getHttpClient();
            try {
                BufferedReader br = setUpStreamIfPossible(httpClient);
                if (br != null) {
                    String line;
                    while ((line = br.readLine()) != null && serviceUp) {
                        Object obj = JSONValue.parse(line);
                        JSONObject instrumentTick = (JSONObject) obj;
                        // unwrap if necessary
                        if (instrumentTick.containsKey(tick)) {
                            instrumentTick = (JSONObject) instrumentTick.get(tick);
                        }

                        if (instrumentTick.containsKey(OandaJsonKeys.instrument)) {
                            final String instrument = instrumentTick.get(OandaJsonKeys.instrument).toString();
                            final String timeAsString = instrumentTick.get(time).toString();
                            final long eventTime = Long.parseLong(timeAsString);
                            final double bidPrice = ((Number) instrumentTick.get(bid)).doubleValue();
                            final double askPrice = ((Number) instrumentTick.get(ask)).doubleValue();
                            marketEventCallback.onMarketEvent(new TradeableInstrument<String>(instrument),
                                    bidPrice, askPrice,
                                    new DateTime(TradingUtils.toMillisFromNanos(eventTime)));
                        } else if (instrumentTick.containsKey(heartbeat)) {
                            handleHeartBeat(instrumentTick);
                        } else if (instrumentTick.containsKey(disconnect)) {
                            handleDisconnect(line);
                        }
                    }
                    br.close();
                    // stream.close();
                }
            } catch (Exception e) {
                LOG.error("error encountered inside market data streaming thread", e);
            } finally {
                serviceUp = false;
                TradingUtils.closeSilently(httpClient);
            }

        }
    }, "OandMarketDataStreamingThread");
    this.streamThread.start();

}

From source file:com.turt2live.uuid.turt2live.v1.ApiV1Service.java

@Override
public List<PlayerRecord> doBulkLookup(UUID... uuids) {
    String list = combine(uuids);
    String response = doUrlRequest(getConnectionUrl() + "/name/list/" + list);

    if (response != null) {
        JSONObject json = (JSONObject) JSONValue.parse(response);

        if (json.containsKey("results")) {
            JSONObject object = (JSONObject) json.get("results");
            List<PlayerRecord> records = new ArrayList<>();

            for (Object key : object.keySet()) {
                UUID uuid = convertUuid(key.toString());
                String name = (String) ((JSONObject) object.get(key)).get("name");

                if (uuid == null || name.equals("unknown"))
                    continue;

                PlayerRecord record = new Turt2LivePlayerRecord(uuid, name);
                records.add(record);/*from  ww  w. j  av  a2 s .  c om*/
            }

            return records;
        }
    }

    return null;
}

From source file:com.turt2live.uuid.turt2live.v1.ApiV1Service.java

@Override
public List<PlayerRecord> doBulkLookup(String... playerNames) {
    String list = combine(playerNames);
    String response = doUrlRequest(getConnectionUrl() + "/uuid/list/" + list);

    if (response != null) {
        JSONObject json = (JSONObject) JSONValue.parse(response);

        if (json.containsKey("results")) {
            JSONObject object = (JSONObject) json.get("results");
            List<PlayerRecord> records = new ArrayList<>();

            for (Object key : object.keySet()) {
                String name = key.toString();
                UUID uuid = convertUuid((String) object.get(key));

                if (uuid == null || name.equals("unknown"))
                    continue;

                PlayerRecord record = new Turt2LivePlayerRecord(uuid, name);
                records.add(record);//from w w w  .jav  a  2s. co m
            }

            return records;
        }
    }

    return null;
}

From source file:com.mapr.xml2json.MySaxParser.java

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    super.endElement(uri, localName, qName);

    String cleanQName = cleanQName(qName);

    if (stk.empty() == true) {
        //System.out.println("Stack empty");
        stk.push(val);
    }//from   w w  w. j  av  a 2s  . c  o  m
    newVal = (JSONObject) stk.pop();
    if (content != null) {

        newVal.put("value", content);
        content = null;
    }

    if (stk.empty() == false) {
        JSONObject parent = (JSONObject) stk.pop();

        if (parent.containsKey(cleanQName) == true) {
            if (parent.get(cleanQName) instanceof JSONObject) {
                JSONObject old_val = (JSONObject) parent.get(cleanQName);
                if (newVal.size() > 0) {
                    JSONArray new_array = new JSONArray();

                    if (old_val.size() == 1 && old_val.containsKey("value") && newVal.size() == 1
                            && newVal.containsKey("value")) {
                        new_array.add(old_val.get("value"));
                        new_array.add(newVal.get("value"));
                    } else {
                        new_array.add(old_val);
                        new_array.add(newVal);
                    }
                    parent.put(cleanQName, new_array);
                }

                stk.push(parent);
            } else if (parent.get(cleanQName) instanceof JSONValue) {
                JSONValue old_val = (JSONValue) parent.get(cleanQName);
                JSONArray new_array = new JSONArray();
                new_array.add(old_val);
                new_array.add(newVal);

                parent.put(cleanQName, new_array);
                stk.push(parent);

            } else if (parent.get(cleanQName) instanceof JSONArray) {
                JSONArray old_val = (JSONArray) parent.get(cleanQName);
                if (newVal.size() == 1 && newVal.containsKey("value")) {
                    old_val.add(newVal.get("value"));
                } else {
                    old_val.add(newVal);
                }
                stk.push(parent);
            } else {
                String old_val = (String) parent.get(cleanQName);
                JSONArray new_array = new JSONArray();
                new_array.add(old_val);
                new_array.add(newVal);

                parent.put(cleanQName, new_array);
                stk.push(parent);
            }
        } else {
            parent.put(cleanQName, newVal);
            stk.push(parent);
        }
    }

}