Example usage for org.json JSONTokener JSONTokener

List of usage examples for org.json JSONTokener JSONTokener

Introduction

In this page you can find the example usage for org.json JSONTokener JSONTokener.

Prototype

public JSONTokener(String s) 

Source Link

Document

Construct a JSONTokener from a string.

Usage

From source file:com.whizzosoftware.hobson.mqtt.MQTTMessageHandlerTest.java

@Test
public void testRegisterMessage() {
    MockMQTTMessageSink sink = new MockMQTTMessageSink();
    MockMQTTEventDelegate listener = new MockMQTTEventDelegate();
    MQTTMessageHandler handler = new MQTTMessageHandler(PluginContext.createLocal("plugin1"), sink, listener);

    assertEquals(0, sink.getMessageCount());
    assertEquals(0, listener.getEventCount());

    JSONObject json = new JSONObject(new JSONTokener(
            "{\"deviceId\":\"3b2184be-2f2c-11e5-a151-feff819cdc9f\",\"nonce\":\"foo\",\"name\":\"Sensor 1\",\"data\":{\"on\":false}}"));
    handler.onMessage("bootstrap", json);

    assertEquals(1, sink.getMessageCount());
    assertEquals("bootstrap/3b2184be-2f2c-11e5-a151-feff819cdc9f/foo", sink.getMessage(0).topic);
    assertNotNull(sink.getMessage(0).payload);
    assertTrue(sink.getMessage(0).payload.getString("secret") != null);
    assertTrue(sink.getMessage(0).payload.has("topics"));

    String dataTopic = sink.getMessage(0).payload.getJSONObject("topics").getString("data");
    assertTrue(dataTopic.startsWith("device/") && dataTopic.endsWith("/data"));
    String commandTopic = sink.getMessage(0).payload.getJSONObject("topics").getString("command");
    assertTrue(commandTopic.startsWith("device/") && commandTopic.endsWith("/command"));

    assertEquals(1, listener.getEventCount());
    assertEquals("3b2184be-2f2c-11e5-a151-feff819cdc9f", listener.getDeviceRegistrationIds().iterator().next());
    assertEquals("Sensor 1", listener.getDeviceRegistrationName("3b2184be-2f2c-11e5-a151-feff819cdc9f"));
}

From source file:com.whizzosoftware.hobson.mqtt.MQTTMessageHandlerTest.java

@Test
public void testDataMessage() {
    MockMQTTMessageSink sink = new MockMQTTMessageSink();
    MockMQTTEventDelegate listener = new MockMQTTEventDelegate();
    MQTTMessageHandler handler = new MQTTMessageHandler(PluginContext.createLocal("plugin1"), sink, listener);

    assertEquals(0, sink.getMessageCount());
    assertEquals(0, listener.getEventCount());

    // send registration message
    JSONObject json = new JSONObject(
            new JSONTokener("{\"deviceId\":\"sensor1\",\"nonce\":\"foo\",\"data\":{}}"));
    handler.onMessage("bootstrap", json);
    assertEquals(1, listener.getEventCount());

    // get the data topic from the registration response
    json = sink.getMessage(0).payload;/*ww  w  .  j  a va 2  s . co  m*/
    String dataTopic = json.getJSONObject("topics").getString("data");
    int ix = dataTopic.indexOf('/') + 1;
    sink.clear();

    // send data message
    json = new JSONObject(new JSONTokener("{\"inTempF\":72.5,\"inRh\":30.1}"));
    handler.onMessage(dataTopic, json);

    assertEquals(2, listener.getEventCount());

    assertNotNull(listener.getData("sensor1"));
    assertEquals(2, listener.getData("sensor1").size());

    Iterator<VariableUpdate> it = listener.getData("sensor1").iterator();
    VariableUpdate so1 = it.next();
    VariableUpdate so2 = it.next();
    assertTrue(so1.getName().equals("inTempF") || so1.getName().equals("inRh"));
    assertTrue(so2.getName().equals("inTempF") || so2.getName().equals("inRh"));
}

From source file:io.bci.BitcoinSTLGenerator.java

private static void parseJsonFile() {
    try {//from   w  w  w  .j  a  va  2 s .  c om
        String jsonFile = new Scanner(new File(getKeyFileName())).useDelimiter("\\Z").next();

        System.out.println(jsonFile);

        JSONTokener tokener = new JSONTokener(jsonFile);
        JSONArray keyArray = new JSONArray(tokener);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.wo2b.sdk.common.util.http.JsonHttpResponseHandler.java

/**
 * Returns Object of type {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long,
 * Double or {@link JSONObject#NULL}, see {@link org.json.JSONTokener#nextValue()}
 *
 * @param responseBody response bytes to be assembled in String and parsed as JSON
 * @return Object parsedResponse//from  www  .  j  av  a 2 s. c  om
 * @throws org.json.JSONException exception if thrown while parsing JSON
 */
protected Object parseResponse(byte[] responseBody) throws JSONException {
    if (null == responseBody)
        return null;
    Object result = null;
    //trim the string to prevent start with blank, and test if the string is valid JSON, because the parser don't do this :(. If JSON is not valid this will return null
    String jsonString = getResponseString(responseBody, getCharset());
    if (jsonString != null) {
        jsonString = jsonString.trim();
        if (jsonString.startsWith("{") || jsonString.startsWith("[")) {
            result = new JSONTokener(jsonString).nextValue();
        }
    }
    if (result == null) {
        result = jsonString;
    }
    return result;
}

From source file:controlador.Peticiones.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*ww  w .j a v a  2  s  .c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //response.setContentType("text/html;charset=UTF-8");
    String target, op, action, view;

    target = request.getParameter("target");
    op = request.getParameter("op");

    if (target.equals("login")) {

        bd = new ControlDB();
        bd.cargarDriver();
        bd.conectar();
        String login = request.getParameter("login");
        String pass = request.getParameter("password");
        ResultSet r = bd.ejecutarSelect("SELECT * FROM roles WHERE nombreRol='" + login + "' AND passRol='"
                + Auxiliar.encriptarPass(pass) + "'");
        JSONObject objetoJSON = new JSONObject();
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            if (r != null && r.next()) {
                objetoJSON.put("r", "1");
                out.print(objetoJSON);
            } else {
                objetoJSON.put("r", "0");
                out.print(objetoJSON);
            }
        } catch (SQLException ex) {

        } catch (JSONException ex) {

        }
    } else {
        if (target.equals("pedido")) {
            bd = new ControlDB();
            bd.cargarDriver();
            bd.conectar();
            String s = request.getParameter("datos");
            JSONTokener token = new JSONTokener(s);
            JSONArray ar = null;
            ArrayList<Producto> productos = new ArrayList();
            try {
                ar = new JSONArray(token);
                for (int i = 0; i < ar.length(); i++) {
                    agregarProducto(ar.getJSONObject(i).getInt("idMesa"),
                            ar.getJSONObject(i).getInt("idProducto"));
                    ResultSet rs = bd.ejecutarSelect("SELECT nombreProducto from productos where idProducto = "
                            + ar.getJSONObject(i).getInt("idProducto"));
                    rs.next();
                    String nombre = rs.getString("nombreProducto");
                    Producto pr = new Producto(nombre);
                    if (productos.contains(pr)) {
                        int pos = productos.indexOf(pr);
                        productos.get(pos).sumaCantidad();
                    } else {
                        productos.add(new Producto(nombre));
                    }
                }
                ResultSet nombreMesa = bd.ejecutarSelect(
                        "SELECT nombreMesa, nombreZona from mesas inner join zona on idZona=Zona_Idzona where idmesa="
                                + ar.getJSONObject(0).getInt("idMesa"));
                nombreMesa.next();
                String nombre = nombreMesa.getString("nombreMesa") + " " + nombreMesa.getString("nombreZona");
                Comanda comanda = new Comanda(productos, nombre);
                System.out.println("Ticket: \n" + comanda.contenidoComanda);
                Auxiliar.imprimir(comanda.contenidoComanda);
            } catch (JSONException ex) {
                System.out.println("Error JSON " + ex.toString());
            } catch (SQLException ex) {
                System.out.println("Error SQL " + ex.toString());
            }

            // Crear un el objeto para enviar a comanda para imprimir, implementar

            response.setHeader("Content-Type", "application/json");
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            JSONObject obj = new JSONObject();
            try {
                obj.put("r", "recibido");
            } catch (JSONException ex) {

            }
            out.print(obj);
            out.flush();
        } else {
            if (target.equals("mesas")) {
                bd = new ControlDB();
                bd.cargarDriver();
                bd.conectar();

                ResultSet r = bd.ejecutarSelect(
                        "SELECT mesas.idMesa, nombreMesa, nombreZona FROM mesas inner join zona on idzona = Zona_idZona");

                JSONArray array = new JSONArray();
                ResultSetMetaData rsMetaData = null;
                int columns = 0;
                try {
                    rsMetaData = r.getMetaData();
                    columns = rsMetaData.getColumnCount();
                } catch (SQLException ex) {

                }

                try {
                    while (r.next()) {
                        JSONObject objetoJSON = new JSONObject();
                        for (int i = 1; i <= columns; i++) {
                            objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i));
                        }
                        System.out.println(objetoJSON + "\n");
                        array.put(objetoJSON);
                    }
                } catch (SQLException ex) {

                } catch (JSONException ex) {

                }
                response.setHeader("Content-Type", "application/json");
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                PrintWriter out = response.getWriter();
                out.print(array);
                out.flush();
            } else {
                if (target.equals("familias")) {
                    bd = new ControlDB();
                    bd.cargarDriver();
                    bd.conectar();

                    ResultSet r = bd.ejecutarSelect(
                            "SELECT idFamilia, nombreFamilia FROM `familias` order by idFamilia");

                    JSONArray array = new JSONArray();
                    ResultSetMetaData rsMetaData = null;
                    int columns = 0;
                    try {
                        rsMetaData = r.getMetaData();
                        columns = rsMetaData.getColumnCount();
                    } catch (SQLException ex) {

                    }

                    try {
                        while (r.next()) {
                            JSONObject objetoJSON = new JSONObject();
                            for (int i = 1; i <= columns; i++) {
                                objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i));
                            }
                            array.put(objetoJSON);
                        }
                    } catch (SQLException ex) {

                    } catch (JSONException ex) {
                        ;
                    }
                    response.setHeader("Content-Type", "application/json");
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    PrintWriter out = response.getWriter();
                    out.print(array);
                    out.flush();
                } else {
                    if (target.equals("productos")) {
                        bd = new ControlDB();
                        bd.cargarDriver();
                        bd.conectar();

                        ResultSet r = bd.ejecutarSelect(
                                "SELECT idProducto, nombreProducto,fotoProducto , precioProducto, Familias_idFamilias FROM productos order by idProducto");

                        JSONArray array = new JSONArray();
                        ResultSetMetaData rsMetaData = null;
                        int columns = 0;
                        try {
                            rsMetaData = r.getMetaData();
                            columns = rsMetaData.getColumnCount();
                        } catch (SQLException ex) {

                        }

                        try {
                            while (r.next()) {
                                JSONObject objetoJSON = new JSONObject();
                                for (int i = 1; i <= columns; i++) {
                                    objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i));
                                }
                                array.put(objetoJSON);
                            }
                        } catch (SQLException ex) {

                        } catch (JSONException ex) {

                        }
                        response.setHeader("Content-Type", "application/json");
                        response.setContentType("application/json");
                        response.setCharacterEncoding("UTF-8");
                        PrintWriter out = response.getWriter();
                        out.print(array);
                        out.flush();
                    }
                }
            }
        }
    }

}

From source file:com.jskaleel.xml.JSONObject.java

/**
 * Construct a JSONObject from a source JSON text string. This is the most
 * commonly used JSONObject constructor.
 *
 * @param source//from   w  w w. j av a2 s  . com
 *            A string beginning with <code>{</code>&nbsp;<small>(left
 *            brace)</small> and ending with <code>}</code>
 *            &nbsp;<small>(right brace)</small>.
 * @exception JSONException
 *                If there is a syntax error in the source string or a
 *                duplicated key.
 * @throws org.json.JSONException 
 */
public JSONObject(String source) throws JSONException, org.json.JSONException {
    this(new JSONTokener(source));
}

From source file:com.github.gorbin.asne.googleplus.GooglePlusSocialNetwork.java

/**
 * Request {@link com.github.gorbin.asne.core.AccessToken} of Google plus social network that you can get from onRequestAccessTokenCompleteListener
 * @param onRequestAccessTokenCompleteListener listener for {@link com.github.gorbin.asne.core.AccessToken} request
 *///from   ww w . ja v  a  2  s .co m
@Override
public void requestAccessToken(OnRequestAccessTokenCompleteListener onRequestAccessTokenCompleteListener) {
    super.requestAccessToken(onRequestAccessTokenCompleteListener);

    AsyncTask<Activity, Void, String> task = new AsyncTask<Activity, Void, String>() {
        @Override
        protected String doInBackground(Activity... params) {
            String scope = "oauth2:" + Scopes.PLUS_LOGIN;
            String token;
            String error = null;
            try {
                token = GoogleAuthUtil.getToken(params[0], Plus.AccountApi.getAccountName(googleApiClient),
                        scope);

                try {
                    HttpParams httpParameters = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(httpParameters, 20000);
                    HttpConnectionParams.setSoTimeout(httpParameters, 20000);
                    HttpClient client = new DefaultHttpClient(httpParameters);
                    String url = "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + token;

                    HttpGet httpGet = new HttpGet(url);

                    HttpResponse response = client.execute(httpGet);
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                    StringBuilder builder = new StringBuilder();
                    for (String line = null; (line = reader.readLine()) != null;) {
                        builder.append(line).append("\n");
                    }

                    JSONTokener tokener = new JSONTokener(builder.toString());
                    JSONObject finalResult = new JSONObject(tokener);
                    error = finalResult.getString("error");
                } catch (Exception e) {
                    //Probably shouldn't use Exception E here but there are quite a few
                    //http/io/json exceptions that could occur
                }

                if (error != null && error.equals("invalid_token")) {
                    GoogleAuthUtil.clearToken(params[0], token);
                    token = GoogleAuthUtil.getToken(params[0], Plus.AccountApi.getAccountName(googleApiClient),
                            scope);
                }

            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
            return token;
        }

        @Override
        protected void onPostExecute(String token) {
            if (token != null) {
                ((OnRequestAccessTokenCompleteListener) mLocalListeners.get(REQUEST_ACCESS_TOKEN))
                        .onRequestAccessTokenComplete(getID(), new AccessToken(token, null));
            } else {
                mLocalListeners.get(REQUEST_ACCESS_TOKEN).onError(getID(), REQUEST_ACCESS_TOKEN, token, null);
            }
        }
    };
    task.execute(mActivity);
}

From source file:com.example.trafficvolation_android.VolationWebView.java

private void handleJson() {
    String json = "{\"code\":\"0\", \"message\":\"?\", \"result\":[{\"url\":\"http://www.shjtaq.com/zwfg/dzjc_new.asp\"}]}";

    try {/*  w w  w  .j  ava2 s . c  o  m*/
        JSONTokener jsonParser = new JSONTokener(json);

        JSONObject jsonObject = (JSONObject) jsonParser.nextValue();

        JSONArray result = jsonObject.getJSONArray("result");
        JSONObject url = result.getJSONObject(0);
        String resultUrl = url.getString("url");

        Log.d("1", resultUrl + " json");

    } catch (JSONException ex) {
        Log.d("1", "handle json failed");
    }

}

From source file:com.tassadar.multirommgr.installfragment.UbuntuManifest.java

public boolean downloadAndParse(Device dev) {
    ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
    try {/* w  w  w . j  ava 2  s . c  o m*/
        final String url = dev.getUbuntuBaseUrl() + CHANNELS_PATH;
        if (!Utils.downloadFile(url, out, null, true) || out.size() == 0)
            return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        Object rawObject = new JSONTokener(out.toString()).nextValue();
        if (!(rawObject instanceof JSONObject)) {
            Log.e(TAG, "Malformed manifest format!");
            return false;
        }

        JSONObject o = (JSONObject) rawObject;
        SharedPreferences pref = MgrApp.getPreferences();

        Iterator itr = o.keys();
        while (itr.hasNext()) {
            String name = (String) itr.next();
            JSONObject c = o.getJSONObject(name);

            // Skip hidden channels
            if (c.optBoolean("hidden", false) && !pref.getBoolean(SettingsFragment.UTOUCH_SHOW_HIDDEN, false)) {
                continue;
            }

            addChannel(name, c);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }

    // Remove channels without the device we're currently running on and load images
    Iterator<Map.Entry<String, TreeMap<String, UbuntuChannel>>> f_itr = m_flavours.entrySet().iterator();
    while (f_itr.hasNext()) {
        Map<String, UbuntuChannel> channelMap = f_itr.next().getValue();
        Iterator<Map.Entry<String, UbuntuChannel>> c_itr = channelMap.entrySet().iterator();
        while (c_itr.hasNext()) {
            UbuntuChannel c = c_itr.next().getValue();

            // Devices like deb or tilapia won't be in
            // Ubuntu Touch manifests, yet the versions
            // for flo/grouper work fine - select those.
            String dev_name = dev.getName();
            if (!c.hasDevice(dev_name)) {
                dev_name = dev.getBaseVariantName();

                if (!c.hasDevice(dev_name)) {
                    c_itr.remove();
                    continue;
                }
            }

            try {
                if (!c.loadDeviceImages(dev_name, dev))
                    return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            // Remove channels with no images for our device
            if (!c.hasImages()) {
                c_itr.remove();
                continue;
            }

            Log.d(TAG, "Got channel: " + c.getDisplayName());
        }

        if (channelMap.isEmpty())
            f_itr.remove();
    }
    return true;
}

From source file:com.novemser.voicetest.utils.JsonParser.java

public static ArrayList<NewsResult> parseNewsInfo(String json) {
    ArrayList<NewsResult> results = new ArrayList<>();
    try {/*from   w  w w .  ja v a  2s . c  o m*/
        JSONTokener tokener = new JSONTokener(json);
        JSONArray array = (JSONArray) tokener.nextValue();
        int len = array.length();
        for (int i = 0; i < len; i++) {
            JSONObject object = array.getJSONObject(i);

            results.add(new NewsResult(object.getString("url"), object.getString("title"),
                    object.getString("time")));
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return results;
}