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.precioustech.fxtrading.oanda.restapi.events.OrderFilledEventHandlerTest.java

@Test
public void generatePayLoad() {
    OrderFilledEventHandler eventHandler = new OrderFilledEventHandler(null);
    JSONObject jsonPayLoad = mock(JSONObject.class);
    EventPayLoad<JSONObject> payLoad = new OrderEventPayLoad(OrderEvents.ORDER_FILLED, jsonPayLoad);
    when(jsonPayLoad.containsKey(OandaJsonKeys.instrument)).thenReturn(true);
    when(jsonPayLoad.get(OandaJsonKeys.instrument)).thenReturn("GBP_CHF");
    when(jsonPayLoad.get(OandaJsonKeys.type)).thenReturn(OrderEvents.ORDER_FILLED);
    when(jsonPayLoad.get(OandaJsonKeys.accountId)).thenReturn(OandaTestConstants.accountId);
    when(jsonPayLoad.containsKey(OandaJsonKeys.accountBalance)).thenReturn(true);
    when(jsonPayLoad.get(OandaJsonKeys.accountBalance)).thenReturn(178.95);
    when(jsonPayLoad.get(OandaJsonKeys.id)).thenReturn(1002L);
    EmailPayLoad emailPayLoad = eventHandler.generate(payLoad);
    assertEquals("Order event ORDER_FILLED for GBP_CHF", emailPayLoad.getSubject());
    assertEquals(/*from w  ww.ja  v  a  2s  .  co  m*/
            "Order event ORDER_FILLED received on account 123456. Order id=1002. Account balance after the event=178.95",
            emailPayLoad.getBody());
}

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

@Override
public void startEventsStreaming() {
    stopEventsStreaming();/*from  w  ww.  j a  v  a2  s .c  o m*/
    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 jsonPayLoad = (JSONObject) obj;
                        if (jsonPayLoad.containsKey(heartbeat)) {
                            handleHeartBeat(jsonPayLoad);
                        } else if (jsonPayLoad.containsKey(transaction)) {
                            JSONObject transactionObject = (JSONObject) jsonPayLoad.get(transaction);
                            String transactionType = transactionObject.get(type).toString();
                            /*convert here so that event bus can post to an appropriate handler, 
                             * event though this does not belong here*/
                            EventPayLoad<JSONObject> payLoad = OandaUtils.toOandaEventPayLoad(transactionType,
                                    transactionObject);
                            if (payLoad != null) {
                                eventCallback.onEvent(payLoad);
                            }
                        } else if (jsonPayLoad.containsKey(OandaJsonKeys.disconnect)) {
                            handleDisconnect(line);
                        }
                    }
                    br.close();
                }

            } catch (Exception e) {
                LOG.error("error encountered inside event streaming thread", e);
            } finally {
                serviceUp = false;
                TradingUtils.closeSilently(httpClient);
            }

        }
    }, "OandEventStreamingThread");
    streamThread.start();
}

From source file:com.bowprog.sql.constructeur.Table.java

public String createCol(JSONObject tableColonne) {
    String strQuery = "`id` INT NOT NULL AUTO_INCREMENT";
    Collection<String> str = tableColonne.keySet();
    for (String colName : str) {
        strQuery += ",`" + colName + "` ";
        JSONObject colonne = (JSONObject) tableColonne.get(colName);
        String type = (String) colonne.get("type");
        strQuery += type;/* w w  w.  java  2  s . c om*/
        if (colonne.containsKey("size")) {
            Long size = (Long) colonne.get("size");
            strQuery += "(" + size + ")";
        }
        if (colonne.containsKey("fk_table")) {

            String tableFK = (String) colonne.get("fk_table");

            //fkSQL.add(" ALTER TABLE " + tableName + " ADD CONSTRAINT fk_" + tableFK + " FOREIGN KEY(" + colName + ") REFERENCES " + tableFK + "(id)");
        }
    }
    strQuery += ",PRIMARY KEY (id)";
    return strQuery;
}

From source file:com.nubits.nubot.pricefeeds.OpenexchangeratesPriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {
    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = getUrl(pair);
        String htmlString;/*from   w w w  .j  a  v a2 s. co  m*/
        try {
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.severe(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        boolean found = false;
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));

            String lookingfor = pair.getOrderCurrency().getCode().toUpperCase();
            JSONObject rates = (JSONObject) httpAnswerJson.get("rates");
            lastRequest = System.currentTimeMillis();
            if (rates.containsKey(lookingfor)) {
                double last = (Double) rates.get(lookingfor);
                last = Utils.round(1 / last, 8);
                lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                        new Amount(last, pair.getPaymentCurrency()));
                return lastPrice;
            } else {
                LOG.warning("Cannot find currency :" + lookingfor + " on feed :" + name);
                return new LastPrice(true, name, pair.getOrderCurrency(), null);
            }

        } catch (ParseException ex) {
            LOG.severe(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.fine("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms "
                + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }
}

From source file:copter.GpsdConnector.java

public String doAction(JSONObject jsonParam, WebSocket conn) {
    this.conn = conn;
    if (!jsonParam.containsKey("action")) {
        return "Missing 'action' param!";
    }//from  w  w w.j  av a  2s . c  o m
    String action = (String) jsonParam.get("action");
    switch (action) {
    case Constants.START_STREAM_GPS_DATA:
        streamGpsData = true;
        return "Gps data streaming started...";
    case Constants.STOP_STREAM_GPS_DATA:
        streamGpsData = false;
        return "Gps data streaming stoped";
    }
    return "Unknown 'action' param: " + action;
}

From source file:de.Keyle.MyPet.util.Updater.java

protected Optional<Update> check() {
    try {//from   w w w.  j  a  v a2 s  .  c om
        String parameter = "";
        parameter += "&package=" + MyPetApi.getCompatUtil().getInternalVersion();
        parameter += "&build=" + MyPetVersion.getBuild();
        parameter += "&dev=" + MyPetVersion.isDevBuild();

        String url = "http://update.mypet-plugin.de/" + plugin + "?" + parameter;

        // no data will be saved on the server
        String content = Util.readUrlContent(url);
        JSONParser parser = new JSONParser();
        JSONObject result = (JSONObject) parser.parse(content);

        if (result.containsKey("latest")) {
            String version = result.get("latest").toString();
            int build = ((Long) result.get("build")).intValue();
            return Optional.of(new Update(version, build));
        }
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
    return Optional.empty();
}

From source file:com.nubits.nubot.pricefeeds.feedservices.OpenexchangeratesPriceFeed.java

@Override
public LastPrice getLastPrice(CurrencyPair pair) {

    long now = System.currentTimeMillis();
    long diff = now - lastRequest;
    if (diff >= refreshMinTime) {
        String url = getUrl(pair);
        String htmlString;/*  www  . j a  v a2  s . c o  m*/
        try {
            LOG.trace("feed fetching from URL: " + url);
            htmlString = Utils.getHTML(url, true);
        } catch (IOException ex) {
            LOG.error(ex.toString());
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
        JSONParser parser = new JSONParser();
        boolean found = false;
        try {
            JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));

            String lookingfor = pair.getOrderCurrency().getCode().toUpperCase();
            JSONObject rates = (JSONObject) httpAnswerJson.get("rates");
            lastRequest = System.currentTimeMillis();
            if (rates.containsKey(lookingfor)) {
                double last = (Double) rates.get(lookingfor);
                LOG.trace("last " + last);
                last = Utils.round(1 / last, 8);
                lastPrice = new LastPrice(false, name, pair.getOrderCurrency(),
                        new Amount(last, pair.getPaymentCurrency()));
                return lastPrice;
            } else {
                LOG.warn("Cannot find currency :" + lookingfor + " on feed :" + name);
                return new LastPrice(true, name, pair.getOrderCurrency(), null);
            }

        } catch (ParseException ex) {
            LOG.error(ex.toString());
            lastRequest = System.currentTimeMillis();
            return new LastPrice(true, name, pair.getOrderCurrency(), null);
        }
    } else {
        LOG.warn("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms "
                + "before making a new request. Now returning the last saved price\n\n");
        return lastPrice;
    }
}

From source file:com.conwet.silbops.msg.UnsubscribeMsg.java

public UnsubscribeMsg(JSONObject payload) {

    this(Subscription.fromJSON((JSONObject) payload.get("subscription")));

    if (payload.containsKey("uncovered")) {

        for (Object fil : (JSONArray) payload.get("uncovered")) {

            uncovered.add(Subscription.fromJSON((JSONObject) fil));
        }//  www .j av a 2s . c  o m
    }
}

From source file:copter.MPU9150.java

public String doAction(JSONObject jsonParam, WebSocket conn) {
    this.conn = conn;
    if (!jsonParam.containsKey("action")) {
        return "Missing 'action' param!";
    }//from  w  w w  .  ja  va 2  s  .  c om
    String action = (String) jsonParam.get("action");
    switch (action) {
    case Constants.SET_ACCELEROMETER_ON_ACTION:
        sendAccelData = true;
        return "Accelerometer data sending on";
    case Constants.SET_ACCELEROMETER_OFF_ACTION:
        sendAccelData = false;
        return "Accelerometer data sending off";
    case Constants.SET_GYO_ON_ACTION:
        sendGyroData = true;
        return "Gyroscope data sending on";
    case Constants.SET_GYO_OFF_ACTION:
        sendGyroData = false;
        return "Gyroscope data sending off";
    }
    return "Unknown 'action' param: " + action;
}

From source file:com.conwet.xjsp.features.DefaultXJSPHandler.java

private ErrorMessage toErrorMessage(Object payload) throws IllegalArgumentException {
    try {/*from w  w w .j  av a  2s  .co  m*/
        JSONObject object = (JSONObject) payload;
        long code = (Long) object.get("code");
        String message = (String) object.get("message");
        String id = null;
        if (object.containsKey("id")) {
            id = (String) object.get("id");
        }
        return new ImmutableErrorMessage(code, message, id);
    } catch (ClassCastException ex) {
        throw new IllegalArgumentException("Malformed error message");
    }
}