Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

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

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:io.crate.frameworks.mesos.api.CrateRestResource.java

@Nullable
String mesosMasterAddress() {/*from  w w w .  j  a v a2 s . co  m*/
    try (CuratorFramework cf = zkClient()) {
        cf.start();
        List<String> children = cf.getChildren().forPath("/mesos");
        List<Integer> masterIds = new ArrayList<Integer>();
        if (children.isEmpty()) {
            return null;
        }
        JSONObject cfData = null;

        for (String child : children) {
            if (child.startsWith("json.info")) {
                masterIds.add(Integer.parseInt(child.split("_")[1]));
            }
        }
        Collections.sort(masterIds);
        for (String child : children) {
            if (child.endsWith(String.valueOf(masterIds.get(0)))) {
                cfData = new JSONObject(new String(cf.getData().forPath("/mesos/" + child)));
                break;
            }
        }

        if (cfData != null) {
            JSONObject address = cfData.getJSONObject("address");
            return String.format("%s:%d", address.getString("ip"), address.getInt("port"));
        }
    } catch (Exception e) {
        LOGGER.error("Error while obtaining a mesos address from the curator framework: ", e);
    }
    return null;
}

From source file:io.crate.frameworks.mesos.api.CrateRestResource.java

int numActiveSlaves(@Nonnull String mesosAddr) {
    String url = String.format("http://%s/metrics/snapshot", mesosAddr);
    javax.ws.rs.core.Response response = RS_CLIENT.target(url).request(MediaType.APPLICATION_JSON).get();
    JSONObject clusterState = new JSONObject(response.readEntity(String.class));

    return clusterState.getInt("master/slaves_active");
}

From source file:io.teak.sdk.RemoteConfiguration.java

public static void requestConfigurationForApp(final Session session) {
    HashMap<String, Object> payload = new HashMap<>();
    payload.put("id", session.appConfiguration.appId);

    new Thread(new Request("gocarrot.com", "/games/" + session.appConfiguration.appId + "/settings.json",
            payload, session) {/*from w w w .j av  a 2 s.co m*/
        @Override
        protected void done(int responseCode, String responseBody) {
            try {
                JSONObject response = new JSONObject(responseBody);

                RemoteConfiguration configuration = new RemoteConfiguration(session.appConfiguration,
                        response.isNull("auth") ? "gocarrot.com" : response.getString("auth"),
                        nullInsteadOfEmpty(response.isNull("sdk_sentry_dsn") ? null
                                : response.getString("sdk_sentry_dsn")),
                        nullInsteadOfEmpty(response.isNull("app_sentry_dsn") ? null
                                : response.getString("app_sentry_dsn")));

                synchronized (eventListenersMutex) {
                    for (EventListener e : RemoteConfiguration.eventListeners) {
                        e.onConfigurationReady(configuration);
                    }
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error processing settings.json " + Log.getStackTraceString(e));
            }
        }
    }).start();
}

From source file:io.teak.sdk.RemoteConfiguration.java

@Override
public String toString() {
    try {/* www .jav a 2s  .co  m*/
        return String.format(Locale.US, "%s: %s", super.toString(), new JSONObject(this.to_h()).toString(2));
    } catch (Exception ignored) {
        return super.toString();
    }
}

From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java

/**
 * Basing on passed JSON in String format, creates object of CdmiObjecStatus.
 * (Translates JSON in String format into CdmiObjectStatus)
 *//*  www  .  j a  v  a  2s.c  o  m*/
@Override
public CdmiObjectStatus getCdmiObjectStatus(String gatewayResponse) {

    //log.debug("Translate {} to CdmiObjectStatus", gatewayResponse);

    Map<String, Object> monitoredAttributes = new HashMap<>();

    JSONObject profile = new JSONObject(gatewayResponse);
    //log.debug("profile: {}", profile);

    JSONObject metadataProvided = profile.getJSONObject("metadata_provided");
    //log.debug("metadata_provided: {}", metadataProvided);

    Iterator<?> keys = metadataProvided.keys();
    while (keys.hasNext()) {

        /*
         * get key name for current item in metadata array
         */
        String key = (String) keys.next();
        //log.debug("key: {}", key);

        Object metadataProvidedAsObj = metadataProvided.get(key);
        //String metadataProvidedAsString = metadataProvidedAsObj.toString();

        //monitoredAttributes.put(key, metadataProvidedAsString);
        monitoredAttributes.put(key, metadataProvidedAsObj);

    }

    String profileName = profile.getString("name");
    String type = profile.getString("type");

    String currentCapabilitiesUri = "/cdmi_capabilities/" + type + "/" + profileName;

    return new CdmiObjectStatus(monitoredAttributes, currentCapabilitiesUri, null);

}

From source file:org.cfr.restlet.ext.shindig.resource.RpcResourceTest.java

@Test
public void testDoGetNormal() throws Exception {

    Request request = createGetRequest("{\"gadgets\":[]}",
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._");
    ;// w w w. ja va 2  s.  c om
    Response response = createResponse(request, MediaType.APPLICATION_JSON,
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._({\"GADGETS\":[]})", Status.SUCCESS_OK);

    Form params = new Form();
    params.add(Disposition.NAME_FILENAME, "rpc.txt");
    Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT, params);
    response.getEntity().setDisposition(disposition);
    resource.init(Context.getCurrent(), request, response);

    JSONObject handlerResponse = new JSONObject("{\"GADGETS\":[]}");
    expect(handler.process(isA(JSONObject.class))).andReturn(handlerResponse);
    replay(handler);
    resource.doGet();
    //        verify(response);
}

From source file:org.akop.ararat.io.WSJFormatter.java

@Override
public void read(Crossword.Builder builder, InputStream inputStream) throws IOException {
    InputStreamReader reader = new InputStreamReader(inputStream, mEncoding);

    StringBuilder sb = new StringBuilder();
    int nread;// w  w w  .j ava 2  s  . c o m
    char[] buffer = new char[4000];
    while ((nread = reader.read(buffer, 0, buffer.length)) > -1) {
        sb.append(buffer, 0, nread);
    }

    JSONObject obj;
    try {
        obj = new JSONObject(sb.toString());
    } catch (JSONException e) {
        throw new FormatException("Error parsing JSON object", e);
    }

    JSONObject dataObj = obj.optJSONObject("data");
    if (dataObj == null) {
        throw new FormatException("Missing 'data'");
    }

    JSONObject copyObj = dataObj.optJSONObject("copy");
    if (copyObj == null) {
        throw new FormatException("Missing 'data.copy'");
    }

    JSONObject gridObj = copyObj.optJSONObject("gridsize");
    if (gridObj == null) {
        throw new FormatException("Missing 'data.copy.gridsize'");
    }

    builder.setTitle(copyObj.optString("title"));
    builder.setDescription(copyObj.optString("description"));
    builder.setCopyright(copyObj.optString("publisher"));
    builder.setAuthor(copyObj.optString("byline"));

    String pubString = copyObj.optString("date-publish");
    try {
        builder.setDate(PUBLISH_DATE_FORMAT.parse(pubString).getTime());
    } catch (ParseException e) {
        throw new FormatException("Can't parse '" + pubString + "' as publish date");
    }

    int width = gridObj.optInt("cols");
    int height = gridObj.optInt("rows");

    builder.setWidth(width);
    builder.setHeight(height);

    readClues(builder, copyObj, Grid.parseJSON(dataObj.optJSONArray("grid"), width, height));
}

From source file:com.github.hobbe.android.openkarotz.util.AssetUtils.java

/**
 * Load a JSON resource from the asset filename.
 * @param context the context/*from   www  . j a v  a  2s  .co m*/
 * @param filename the name of the JSON object
 * @return the JSON object
 */
public static JSONObject loadJsonFromAsset(Context context, String filename) {
    JSONObject json = null;
    InputStream is = null;

    try {
        is = context.getAssets().open(filename);

        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);

        String content = new String(buffer, "UTF-8");
        json = new JSONObject(content);

    } catch (IOException e) {
        Log.e(LOG_TAG, "Could not load JSON asset " + filename, e);
        return null;
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Could not parse JSON from asset " + filename, e);
        return null;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // Ignored
            }
        }
    }

    return json;
}

From source file:org.obiba.magma.Coordinate.java

public static Coordinate getCoordinateFrom(String string) {
    // GeoJSON coordinate
    if (string.trim().startsWith("[")) {
        JSONArray array = null;/*from  w w  w .  ja v  a2s . co m*/
        try {
            array = new JSONArray(string);
            return getCoordinateFrom(array);
        } catch (JSONException e) {
            throw new MagmaRuntimeException("Not a valid GeoJSON coordinate", e);
        }
    }
    // JSON coordinate
    if (string.trim().startsWith("{")) {
        JSONObject object = null;
        try {
            object = new JSONObject(string);
            return getCoordinateFrom(object);
        } catch (JSONException e) {
            throw new MagmaRuntimeException("Not a valid JSON coordinate", e);
        }
    }
    // Google coordinate  lat,long
    else {
        String stringToParse = "[" + string.trim() + "]";
        JSONArray array = null;
        try {
            array = new JSONArray(stringToParse);
            return new Coordinate(array.getDouble(1), array.getDouble(0));
        } catch (JSONException e) {
            throw new MagmaRuntimeException("Not a valid coordinate", e);
        }
    }
}

From source file:com.mobile.system.db.abatis.AbatisService.java

/**
 * //from   w ww.j av a 2s . c o  m
 * @param jsonStr
 *            JSON String
 * @param beanClass
 *            Bean class
 * @param basePackage
 *            Base package name which includes all Bean classes
 * @return Object Bean
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception {
    Object obj = null;
    JSONObject jsonObj = new JSONObject(jsonStr);
    // Check bean object
    if (beanClass == null) {
        Log.d(TAG, "Bean class is null");
        return null;
    }
    // Read Class member fields
    Field[] props = beanClass.getDeclaredFields();
    if (props == null || props.length == 0) {
        Log.d(TAG, "Class" + beanClass.getName() + " has no fields");
        return null;
    }
    // Create instance of this Bean class
    obj = beanClass.newInstance();
    // Set value of each member variable of this object
    for (int i = 0; i < props.length; i++) {
        String fieldName = props[i].getName();
        // Skip public and static fields
        if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) {
            continue;
        }
        // Date Type of Field
        Class type = props[i].getType();
        String typeName = type.getName();
        // Check for Custom type
        if (typeName.equals("int")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getInt(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("long")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getLong(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.lang.String")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getString(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("double")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getDouble(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.util.Date")) { // modify

            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);

            String dateString = jsonObj.getString(fieldName);
            dateString = dateString.replace(" KST", "");
            SimpleDateFormat genderFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.KOREA);
            // Set value
            try {
                Date afterDate = genderFormat.parse(dateString);
                m.invoke(obj, afterDate);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        } else if (type.getName().equals(List.class.getName())
                || type.getName().equals(ArrayList.class.getName())) {
            // Find out the Generic
            String generic = props[i].getGenericType().toString();
            if (generic.indexOf("<") != -1) {
                String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">"));
                if (genericType != null) {
                    JSONArray array = null;
                    try {
                        array = jsonObj.getJSONArray(fieldName);
                    } catch (Exception ex) {
                        Log.d(TAG, ex.getMessage());
                        array = null;
                    }
                    if (array == null) {
                        continue;
                    }
                    ArrayList arrayList = new ArrayList();
                    for (int j = 0; j < array.length(); j++) {
                        arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType),
                                basePackage));
                    }
                    // Set value
                    Class[] parms = { type };
                    Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                    m.setAccessible(true);
                    m.invoke(obj, arrayList);
                }
            } else {
                // No generic defined
                generic = null;
            }
        } else if (typeName.startsWith(basePackage)) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                JSONObject customObj = jsonObj.getJSONObject(fieldName);
                if (customObj != null) {
                    m.invoke(obj, parse(customObj.toString(), type, basePackage));
                }
            } catch (JSONException ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else {
            // Skip
            Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip");
        }
    }
    return obj;
}