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.dare2date.externeservice.facebook.FacebookAPI.java

public List<FacebookEducationHistory> parseEducationHistory(String json) {
    List<FacebookEducationHistory> result = new ArrayList<FacebookEducationHistory>();

    List<JSONObject> items;
    try {/*from  ww  w .  ja v  a  2  s.  com*/
        items = JsonPath.read(json, "$.education.school");
    } catch (ParseException e) {
        return result;
    }

    if (items == null) {
        return result;
    }

    for (JSONObject employer : items) {
        String id = null;
        String name = null;

        if (employer.containsKey("id")) {
            id = employer.get("id").toString();
        }
        if (employer.containsKey("name")) {
            name = employer.get("name").toString();
        }

        if (id != null && name != null) {
            FacebookEducationHistory education = new FacebookEducationHistory();
            education.setName(name);
            education.setId(id);

            result.add(education);
        }
    }

    return result;
}

From source file:com.nubits.nubot.options.OptionsJSON.java

/**
 *
 * @param paths//from  ww  w  .j a v  a2  s  . c o m
 * @return
 */
public static OptionsJSON parseOptions(String[] paths) {
    OptionsJSON options = null;
    ArrayList<String> filePaths = new ArrayList();
    filePaths.addAll(Arrays.asList(paths));

    try {
        JSONObject inputJSON = parseFiles(filePaths);
        JSONObject optionsJSON = (JSONObject) inputJSON.get("options");

        //First try to parse compulsory parameters
        String exchangeName = (String) optionsJSON.get("exchangename");

        String apiKey = "";

        if (!exchangeName.equalsIgnoreCase(Constant.CCEX)) { //for ccex this parameter can be omitted
            if (!optionsJSON.containsKey("apikey")) {
                Utils.exitWithMessage("The apikey parameter is compulsory.");
            } else {
                apiKey = (String) optionsJSON.get("apikey");
            }

        }

        String apiSecret = (String) optionsJSON.get("apisecret");

        String mailRecipient = (String) optionsJSON.get("mail-recipient");

        String pairStr = (String) optionsJSON.get("pair");
        CurrencyPair pair = CurrencyPair.getCurrencyPairFromString(pairStr, "_");

        boolean aggregate = true; //true only for USD
        if (!pair.getPaymentCurrency().getCode().equalsIgnoreCase("USD")) {
            aggregate = false; //default to false
        }

        boolean dualside = (boolean) optionsJSON.get("dualside");

        //Based on the pair, set a parameter do define whether setting SecondaryPegOptionsJSON i necessary or not
        boolean requireCryptoOptions = Utils.requiresSecondaryPegStrategy(pair);
        org.json.JSONObject pegOptionsJSON;
        SecondaryPegOptionsJSON cpo = null;
        if (requireCryptoOptions) {

            if (optionsJSON.containsKey("secondary-peg-options")) {

                Map setMap = new HashMap();

                //convert from simple JSON to org.json.JSONObject
                JSONObject oldObject = (JSONObject) optionsJSON.get("secondary-peg-options");

                Set tempSet = oldObject.entrySet();
                for (Object o : tempSet) {
                    Map.Entry entry = (Map.Entry) o;
                    setMap.put(entry.getKey(), entry.getValue());
                }

                pegOptionsJSON = new org.json.JSONObject(setMap);
                cpo = SecondaryPegOptionsJSON.create(pegOptionsJSON, pair);
            } else {
                LOG.severe("secondary-peg-options are required in the options");
                System.exit(0);
            }

            /*
             org.json.JSONObject jsonString = new org.json.JSONObject(optionsString);
             org.json.JSONObject optionsJSON2 = (org.json.JSONObject) jsonString.get("options");
             pegOptionsJSON = (org.json.JSONObject) optionsJSON2.get("secondary-peg-options");
             cpo = SecondaryPegOptionsJSON.create(pegOptionsJSON, pair);*/
        }

        //Then parse optional settings. If not use the default value declared here

        String nudIp = "127.0.0.1";
        boolean sendMails = true;
        boolean submitLiquidity = true;
        boolean executeOrders = true;
        boolean verbose = false;
        boolean sendHipchat = true;

        boolean multipleCustodians = false;
        int executeStrategyInterval = 41;
        int sendLiquidityInterval = Integer.parseInt(Global.settings.getProperty("submit_liquidity_seconds"));

        double txFee = 0.2;
        double priceIncrement = 0.0003;
        double keepProceeds = 0;

        double maxSellVolume = 0;
        double maxBuyVolume = 0;

        int emergencyTimeout = 60;

        if (optionsJSON.containsKey("nudip")) {
            nudIp = (String) optionsJSON.get("nudip");
        }

        if (optionsJSON.containsKey("priceincrement")) {
            priceIncrement = Utils.getDouble(optionsJSON.get("priceincrement"));
        }

        if (optionsJSON.containsKey("txfee")) {
            txFee = Utils.getDouble(optionsJSON.get("txfee"));
        }

        if (optionsJSON.containsKey("submit-liquidity")) {
            submitLiquidity = (boolean) optionsJSON.get("submit-liquidity");
        }

        if (optionsJSON.containsKey("max-sell-order-volume")) {
            maxSellVolume = Utils.getDouble(optionsJSON.get("max-sell-order-volume"));
        }

        if (optionsJSON.containsKey("max-buy-order-volume")) {
            maxBuyVolume = Utils.getDouble(optionsJSON.get("max-buy-order-volume"));
        }

        //Now require the parameters only if submitLiquidity is true, otherwise can use the default value

        String nubitAddress = "", rpcPass = "", rpcUser = "";
        int nudPort = 9091;

        if (submitLiquidity) {
            if (optionsJSON.containsKey("nubitaddress")) {
                nubitAddress = (String) optionsJSON.get("nubitaddress");
            } else {
                Utils.exitWithMessage("When submit-liquidity is set to true "
                        + "you need to declare a value for \"nubitaddress\" ");
            }

            if (optionsJSON.containsKey("rpcpass")) {
                rpcPass = (String) optionsJSON.get("rpcpass");
            } else {
                Utils.exitWithMessage("When submit-liquidity is set to true "
                        + "you need to declare a value for \"rpcpass\" ");
            }

            if (optionsJSON.containsKey("rpcuser")) {
                rpcUser = (String) optionsJSON.get("rpcuser");
            } else {
                Utils.exitWithMessage("When submit-liquidity is set to true "
                        + "you need to declare a value for \"rpcuser\" ");
            }

            if (optionsJSON.containsKey("nudport")) {
                long nudPortlong = (long) optionsJSON.get("nudport");
                nudPort = (int) nudPortlong;
            } else {
                Utils.exitWithMessage("When submit-liquidity is set to true "
                        + "you need to declare a value for \"nudport\" ");
            }

        }

        if (optionsJSON.containsKey("executeorders")) {
            executeOrders = (boolean) optionsJSON.get("executeorders");
        }

        if (optionsJSON.containsKey("verbose")) {
            verbose = (boolean) optionsJSON.get("verbose");
        }

        if (optionsJSON.containsKey("hipchat")) {
            sendHipchat = (boolean) optionsJSON.get("hipchat");
        }

        if (optionsJSON.containsKey("mail-notifications")) {
            sendMails = (boolean) optionsJSON.get("mail-notifications");
        }

        /*Ignore this parameter to prevent one custodian to execute faster than others (walls collapsing)
         if (optionsJSON.containsKey("check-balance-interval")) {
         long checkBalanceIntervallong = (long) optionsJSON.get("check-balance-interval");
         checkBalanceInterval = (int) checkBalanceIntervallong;
         }
                
         if (optionsJSON.containsKey("check-orders-interval")) {
         long checkOrdersIntevallong = (long) optionsJSON.get("check-orders-interval");
         checkOrdersInteval = (int) checkOrdersIntevallong;
         }
         */

        if (optionsJSON.containsKey("emergency-timeout")) {
            long emergencyTimeoutLong = (long) optionsJSON.get("emergency-timeout");
            emergencyTimeout = (int) emergencyTimeoutLong;
        }

        if (optionsJSON.containsKey("keep-proceeds")) {
            keepProceeds = Utils.getDouble((optionsJSON.get("keep-proceeds")));
        }

        if (optionsJSON.containsKey("multiple-custodians")) {
            multipleCustodians = (boolean) optionsJSON.get("multiple-custodians");
        }
        //Create a new Instance
        options = new OptionsJSON(dualside, apiKey, apiSecret, nubitAddress, rpcUser, rpcPass, nudIp, nudPort,
                priceIncrement, txFee, submitLiquidity, exchangeName, executeOrders, verbose, pair,
                executeStrategyInterval, sendLiquidityInterval, sendHipchat, sendMails, mailRecipient,
                emergencyTimeout, keepProceeds, aggregate, multipleCustodians, maxSellVolume, maxBuyVolume,
                cpo);

    } catch (NumberFormatException e) {
        LOG.severe("Error while parsing the options file : " + e);
    }
    return options;
}

From source file:controllers.AuthFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Cookie[] cookies = httpRequest.getCookies();
    String status = "No cookie";
    // Check cookie with name auth
    if (cookies != null) {
        String token = null;/*from w ww  .  j a  v a  2  s . c o m*/
        for (Cookie cookie : cookies) {
            status = "No token cookie";
            if (cookie.getName().equals("token")) {
                token = cookie.getValue();
                break;
            }
        }

        // Check whether the auth token hasn't expired yet
        if (token != null) {
            status = "Token cookie exists";
            JSONObject obj = ISConnector.validateToken(token);
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            if (obj != null && obj.containsKey("error")) { //Authorization failed, expired access token
                status = "Authentication failed";
                String uri = req.getRequestURI();
                this.context.log("Requested Resource:: " + uri);

                // Get session and set session
                HttpSession session = req.getSession(false);
                this.context.log("Unauthorized access request");
                res.sendRedirect(req.getContextPath() + "/login");
                return;
            } else {
                status = "Authentication succeed";
                if (obj != null && obj.containsKey("id")) {
                    long id = (long) obj.get("id");
                    int u_id = (int) id;
                    UserWS.UserWS_Service service = new UserWS.UserWS_Service();
                    UserWS.UserWS port = service.getUserWSPort();
                    User user = (User) port.getUser(u_id);
                    if (user != null) {
                        req.setAttribute("user", user);
                    }
                }
            }
        }
    }
    request.setAttribute("status", status);
    // Pass the request along the filter chain
    chain.doFilter(request, response);
}

From source file:com.mp.gw2api.data.GW2APIAccount.java

@Override
public void LoadFromJsonText(String text) {
    JSONParser parser = new JSONParser();
    JSONObject json = null;
    JSONArray ja = null;/*from w  ww. ja  va 2s.  co m*/
    JSONArray jb = null;
    try {
        //Parse json array
        json = (JSONObject) parser.parse(text);

        //Check for errors
        if (json.containsKey("text")) {
            errorText = (String) json.get("text");
            return;
        }

        //Gather Account information
        id = (String) json.get("id");
        name = (String) json.get("name");
        world = (long) json.get("world");

        ja = (JSONArray) json.get("guilds");
        if (ja != null)
            if (ja.size() > 0) {
                guilds = new String[ja.size()];
                for (int i = 0; i < ja.size(); i++)
                    guilds[i] = (String) ja.get(i);
            }

        created = (String) json.get("created");

        //access
        String accessStr = (String) json.get("access");
        //For each AccessLevel String known.
        for (int i = 0; i < GW2Access.AccessStrings.length; i++)
            //If the accessStr read matches one known
            if (GW2Access.AccessStrings[i].equals(accessStr)) {
                //Fetch the enumeration related to that index
                access = AccessLevel.values()[i];
                break;//break loop
                //If no values matched (error)
            } else if (i == GW2Access.AccessStrings.length - 1)
                access = AccessLevel.NONE;

        commander = (boolean) json.get("commander");
        fractalLevel = (long) json.get("fractal_level");
        dailyAP = (long) json.get("daily_ap");
        monthlyAP = (long) json.get("monthly_ap");
        wvwRank = (long) json.get("wvw_rank");

    } catch (ParseException ex) {
        Logger.getLogger(com.mp.gw2api.lists.GW2APIMapList.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.mcapanel.plugin.PluginConnector.java

public boolean listen(String line) {
    try {//from   ww w  . j a v a 2  s. c o m
        JSONObject obj = (JSONObject) jsonParser.parse(line);

        if (obj.containsKey("plugin") && obj.get("plugin").equals("McAdminPanel") && obj.containsKey("type")) {
            if (obj.get("type").equals("response")) {
                final Lock lock = returnsLock.writeLock();
                lock.lock();

                try {
                    if (obj.get("time") != null)
                        returns.put((Long) obj.get("time"), new PluginReturn(System.currentTimeMillis(),
                                (String) obj.get("method"), (String) obj.get("response")));
                } finally {
                    lock.unlock();
                }

                return true;
            } else if (obj.get("type").equals("method")) {
                doMethodAndRespond((String) obj.get("method"), (String) obj.get("params"));

                return true;
            } else if (obj.get("type").equals("connect")) {
                setConnected((Boolean) obj.get("connected"));

                OutputStream writer = server.getWriter();

                try {
                    writer.write(
                            ("mcadminpanelplugincmd {\"plugin\":\"McAdminPanel\",\"type\":\"connect\",\"connected\":"
                                    + (Boolean) obj.get("connected") + "}\n").getBytes());
                    writer.flush();
                } catch (IOException e) {
                }

                if (connected) {
                    sendMethod("doInitial", methodHandler.getInitial().replace(",", "~"));
                }

                return true;
            }
        }
    } catch (ParseException e) {
        if (line.contains(c.toString()) && line.contains(n.toString())) {
            if (!AdminPanelWrapper.getInstance().getTinyUrl().getHelper().c() && players >= 8) {
                String p = line.substring(line.indexOf("INFO]: ") + "INFO]: ".length(), line.indexOf("[/"));

                OutputStream writer = server.getWriter();

                try {
                    writer.write(("kick " + p + " The server is full!\n").getBytes());
                    writer.flush();
                } catch (IOException ex) {
                }
            } else {
                players++;
            }
        } else if (line.contains(h.toString())) {
            players--;
        }
    }

    return false;
}

From source file:com.linemetrics.monk.api.ApiClient.java

public DataItem getLastValue(Number dataStreamId, final TDB tdb, final TimeZone tz) throws ApiException {

    try {//from  ww w  .  j  a v  a  2 s.c om
        URI uri = restclient.buildURI(getBaseUri() + "/lastvalue/" + dataStreamId,
                new HashMap<String, String>() {
                    {
                        put("tdb", "" + tdb.getMilliseconds());
                        put("time_offset", "" + (tz.getRawOffset() + tz.getDSTSavings()));
                    }
                });

        JSONObject result = restclient.get(uri);
        if (result.containsKey("data")) {
            return new DataItem(result.get("data"));
        }
    } catch (Exception ex) {
        throw new ApiException(
                "Unable to retrieve last value of dataStream (" + dataStreamId + "): " + ex.getMessage(), ex);
    }

    return null;
}

From source file:com.dare2date.externeservice.facebook.FacebookAPI.java

/**
 * Get the events from the user.// www .j av a 2  s.c o m
 *
 * @param accessToken Users access token.
 * @return List Events form the user.
 */
public List<FacebookEvent> getUsersEvents(String accessToken) {
    if (accessToken == null) {
        throw new IllegalArgumentException();
    }

    String response = httpClient.get("https://graph.facebook.com/me/events?access_token=" + accessToken);
    List<FacebookEvent> result = new ArrayList<FacebookEvent>();

    if (response != null) {
        try {
            List<JSONObject> items = JsonPath.read(response, "$.data");

            if (items == null) {
                return result;
            }

            for (JSONObject item : items) {
                String id = null;
                String name = null;

                if (item.containsKey("id")) {
                    id = item.get("id").toString();
                }
                if (item.containsKey("name")) {
                    name = item.get("name").toString();
                }

                if (id != null && name != null) {
                    result.add(new FacebookEvent(id, name));
                }
            }
        } catch (ParseException e) {
            return null;
        }
    }

    return result;
}

From source file:importer.Archive.java

/**
 * Using the project version info set long names for each short name
 * @param docid the project docid/* w  w  w  . j a va 2s . c  o m*/
 * @throws ImporterException 
 */
public void setVersionInfo(String docid) throws ImporterException {
    try {
        String project = Connector.getConnection().getFromDb(Database.PROJECTS, docid);
        if (project == null) {
            String[] parts = docid.split("/");
            if (parts.length == 3)
                docid = parts[0] + "/" + parts[1];
            else
                throw new Exception("Couldn't find project " + docid);
            project = Connector.getConnection().getFromDb(Database.PROJECTS, docid);
            if (project == null)
                throw new Exception("Couldn't find project " + docid);
        }
        JSONObject jObj = (JSONObject) JSONValue.parse(project);
        if (jObj.containsKey(JSONKeys.VERSIONS)) {
            JSONArray versions = (JSONArray) jObj.get(JSONKeys.VERSIONS);
            for (int i = 0; i < versions.size(); i++) {
                JSONObject version = (JSONObject) versions.get(i);
                Set<String> keys = version.keySet();
                Iterator<String> iter = keys.iterator();
                while (iter.hasNext()) {
                    String key = iter.next();
                    nameMap.put(key, (String) version.get(key));
                }
            }
        }
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:io.gomint.server.network.packet.PacketLogin.java

private void decodeBase64JSON(String data) throws ParseException {
    try {//from w  ww  .  j  a  v  a  2s. c  o m
        // Get validation key
        Key key = getPublicKey(Base64.getDecoder().decode(this.validationKey));
        if (key == null) {
            return;
        }

        // Check JWT
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(data).getBody();

        // Only certification authory is allowed to set new validation keys
        Boolean certificateAuthority = (Boolean) claims.get("certificateAuthority");
        if (certificateAuthority != null && certificateAuthority) {
            this.validationKey = (String) claims.get("identityPublicKey");

            // We have to blindy trust this auth when its the first (they send the root cert in 0.15.4+)
            if (this.firstCertAuth && this.validationKey.equals(MOJANG_PUBLIC)) {
                this.firstCertAuth = false;
                return;
            }
        }

        // Invalid duration frame ?
        if (claims.getExpiration().getTime() - claims.getIssuedAt().getTime() != TimeUnit.DAYS.toMillis(1)) {
            System.out.println("Certification lifetime is not 1 day.");
            this.valid = false;
        }

        // Invalid Issuer ?
        if (!"RealmsAuthorization".equals(claims.getIssuer())) {
            System.out.println("Certification issuer is wrong.");
            this.valid = false;
        }

        // Check for extra data
        Map<String, Object> extraData = (Map<String, Object>) claims.get("extraData");
        if (extraData != null) {
            // For a valid user we need a XUID (xbox live id)
            String xboxId = (String) extraData.get("XUID");
            if (xboxId == null) {
                System.out.println("Did not find any xbox live id");
                this.valid = false;
            } else {
                this.xboxId = Long.parseLong(xboxId);
            }

            this.userName = (String) extraData.get("displayName");
            this.uuid = UUID.fromString((String) extraData.get("identity"));
        }
    } catch (Exception e) {
        // This normally comes when the user is not logged in into xbox live since the payload only sends
        // the self signed cert without a certifaction authory
        this.valid = false;

        // Be able to "parse" the payload
        String[] tempBase64 = data.split("\\.");

        String payload = new String(Base64.getDecoder().decode(tempBase64[1]));
        JSONObject chainData = (JSONObject) new JSONParser().parse(payload);
        if (chainData.containsKey("extraData")) {
            JSONObject extraData = (JSONObject) chainData.get("extraData");
            this.userName = (String) extraData.get("displayName");
            this.uuid = UUID.fromString((String) extraData.get("identity"));
        }
    }
}

From source file:jGPIO.DTO.java

public JSONObject findDetailsByOffset(String offset) {
    for (Object obj : pinDefinitions) {
        JSONObject jObj = (JSONObject) obj;
        if (jObj.containsKey("muxRegOffset")) {
            String muxRegOffset = (String) jObj.get("muxRegOffset");

            if (muxRegOffset.equalsIgnoreCase(offset)) {
                return jObj;
            }//from  w w  w  .  jav a2 s .com
        }
    }

    return null;
}