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() 

Source Link

Document

Construct an empty JSONObject.

Usage

From source file:org.dasein.cloud.tier3.APIHandler.java

public @Nonnull APIResponse post(@Nonnull String resource, @Nonnull String json)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + APIHandler.class.getName() + ".post(" + resource + "," + json + ")");
    }/*from   w  w w.  j  a v a2  s.c o m*/
    try {
        String target = getEndpoint(resource, null);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [POST (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new ConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }

                HttpPost post = new HttpPost(target);

                post.addHeader("Accept", "application/json");
                post.addHeader("Content-type", "application/json");

                if (!resource.contains("Auth/Logon/")) {
                    post.addHeader("Cookie", provider.logon());
                }

                try {
                    post.setEntity(new StringEntity(json, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    logger.error("Unsupported encoding UTF-8: " + e.getMessage());
                    throw new InternalException(e);
                }

                if (wire.isDebugEnabled()) {
                    wire.debug(post.getRequestLine().toString());
                    for (Header header : post.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                    wire.debug(json);
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    APITrace.trace(provider, "POST " + resource);
                    response = client.execute(post);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND) {
                    throw new CloudException("No such endpoint: " + target);
                }
                if (resource.contains("/Logon/") && status.getStatusCode() == OK) {
                    APIResponse r = new APIResponse();

                    try {
                        JSONObject jsonCookie = new JSONObject();

                        // handle logon response specially
                        Header[] cookieHdrs = response.getHeaders("Set-Cookie");
                        for (int c = 0; c < cookieHdrs.length; c++) {
                            Header cookieHdr = cookieHdrs[c];
                            if (cookieHdr.getValue().startsWith("Tier3.API.Cookie")) {
                                jsonCookie.put("Session", cookieHdr.getValue());
                                break;
                            }
                        }

                        r.receive(status.getStatusCode(), jsonCookie, true);
                    } catch (JSONException e) {
                        throw new CloudException(e);
                    }
                    return r;

                } else if (status.getStatusCode() != ACCEPTED && status.getStatusCode() != CREATED
                        && status.getStatusCode() != OK) {
                    logger.error(
                            "Expected OK, ACCEPTED or CREATED for POST request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    try {
                        json = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new Tier3Exception(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                    }
                    wire.debug("");
                    throw new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), json);
                } else {
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new CloudException("No response to the POST");
                    }
                    try {
                        json = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new Tier3Exception(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                    }
                    wire.debug("");
                    APIResponse r = new APIResponse();

                    try {
                        r.receive(status.getStatusCode(), new JSONObject(json), true);
                    } catch (JSONException e) {
                        throw new CloudException(e);
                    }
                    return r;
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [POST (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + APIHandler.class.getName() + ".post()");
        }
    }
}

From source file:game.objects.Board.java

public JSONArray getBoardJSON() throws JSONException {
    JSONArray arr = new JSONArray();
    for (String key : countries.keySet()) {
        JSONObject json = new JSONObject();
        json.put("CountryID", key);
        json.put("CountryName", countries.get(key).getName());
        json.put("Owner", countries.get(key).getOwner());
        json.put("Troops", countries.get(key).getTroops());
        arr.put(json);/*  w  w  w.j  a  v a  2 s. co  m*/
    }
    return arr;
}

From source file:com.atinternet.tracker.NuggAdsTest.java

@Test
public void addTest() {
    NuggAd nuggAd = nuggAds.add(new JSONObject());
    assertEquals(1, tracker.getBusinessObjects().size());
    assertEquals("{}", ((NuggAd) tracker.getBusinessObjects().get(nuggAd.getId())).getNuggAdData().toString());
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitCherryPickTest.java

private static WebRequest getPostGitCherryPickRequest(String location, String toCherryPick)
        throws JSONException, UnsupportedEncodingException {
    String requestURI = toAbsoluteURI(location);
    JSONObject body = new JSONObject();
    body.put(GitConstants.KEY_CHERRY_PICK, toCherryPick);
    WebRequest request = new PostMethodWebRequest(requestURI, IOUtilities.toInputStream(body.toString()),
            "UTF-8");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request);//w w  w.j  ava  2s. c  o m
    return request;
}

From source file:com.ecml.MidiOptions.java

/** Convert this MidiOptions object into a JSON string. */
public String toJson() {
    try {// w  ww  .  java2 s.c o  m
        JSONObject json = new JSONObject();
        JSONArray jsonTracks = new JSONArray();
        for (boolean value : tracks) {
            jsonTracks.put(value);
        }
        JSONArray jsonMute = new JSONArray();
        for (boolean value : mute) {
            jsonMute.put(value);
        }
        JSONArray jsonInstruments = new JSONArray();
        for (int value : instruments) {
            jsonInstruments.put(value);
        }
        if (time != null) {
            JSONObject jsonTime = new JSONObject();
            jsonTime.put("numerator", time.getNumerator());
            jsonTime.put("denominator", time.getDenominator());
            jsonTime.put("quarter", time.getQuarter());
            jsonTime.put("tempo", time.getTempo());
            json.put("time", jsonTime);
        }

        json.put("versionCode", 7);
        json.put("tracks", jsonTracks);
        json.put("mute", jsonMute);
        json.put("instruments", jsonInstruments);
        json.put("useDefaultInstruments", useDefaultInstruments);
        json.put("scrollVert", scrollVert);
        json.put("showPiano", showPiano);
        json.put("showNoteColors", showNoteColors);
        json.put("showLyrics", showLyrics);
        json.put("delay", delay);
        json.put("twoStaffs", twoStaffs);
        json.put("showNoteLetters", showNoteLetters);
        json.put("transpose", transpose);
        json.put("key", key);
        json.put("combineInterval", combineInterval);
        json.put("shade1Color", shade1Color);
        json.put("shade2Color", shade2Color);
        json.put("showMeasures", showMeasures);
        json.put("playMeasuresInLoop", playMeasuresInLoop);
        json.put("playMeasuresInLoopStart", playMeasuresInLoopStart);
        json.put("playMeasuresInLoopEnd", playMeasuresInLoopEnd);

        return json.toString();
    } catch (JSONException e) {
        return null;
    } catch (NullPointerException e) {
        return null;
    }
}

From source file:blink.Message.java

/**
 * a Message object that represents a message to be sent
 * @param timestamp when a message was created
 * @param text the actual content of the message
 * @param userId the id number for the user sending the message
 *//* w w w .  j  a  va 2s . c  om*/
public Message(long timestamp, String text, int userId) {
    this.timestamp = timestamp;
    this.text = text;
    this.userId = userId;
    this.type = "message";
    JSONObject json = new JSONObject();
    try {
        json.put("timestamp", timestamp);
        json.put("content", text);
        json.put("type", "message");
    } catch (JSONException ex) {
        Logger.getLogger(Message.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.json = json.toString();
}

From source file:com.andybotting.tramhunter.objects.FavouriteList.java

/**
 * Convert an old favourites string to the new JSON format
 * @param favouriteString/*  w  w  w  . j  a v  a 2  s. c  o  m*/
 * @return JSONArray
 */
private String convertOldFavourites(String favouriteString) {

    try {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        int tramTrackerId;

        StringTokenizer tokenizer = new StringTokenizer(favouriteString, ",");
        while (tokenizer.hasMoreTokens()) {
            tramTrackerId = Integer.parseInt(tokenizer.nextToken());
            jsonObject = new JSONObject();
            jsonObject.put("stop", tramTrackerId);
            jsonArray.put(jsonObject);
        }
        return jsonArray.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}

From source file:com.cmgapps.android.util.CMGAppRater.java

private static String ratePreferenceToString(SharedPreferences pref) {
    JSONObject thiz = new JSONObject();
    try {/*w w  w.  j av  a2 s  .com*/
        thiz.put(DECLINED_RATE, pref.getBoolean(DECLINED_RATE, false));
        thiz.put(APP_RATED, pref.getBoolean(APP_RATED, false));
        thiz.put(TRACKING_VERSION, pref.getInt(TRACKING_VERSION, -1));
        thiz.put(FIRST_USE,
                SimpleDateFormat.getDateTimeInstance().format(new Date(pref.getLong(FIRST_USE, 0L))));
        thiz.put(USE_COUNT, pref.getInt(USE_COUNT, 0));
        thiz.put(REMIND_LATER_DATE,
                SimpleDateFormat.getDateTimeInstance().format(new Date(pref.getLong(REMIND_LATER_DATE, 0L))));
    } catch (JSONException exc) {
        LOGE(TAG, "Error creating JSON Object", exc);
    }

    return thiz.toString();
}

From source file:de.kp.ames.web.function.transform.cache.XslCacheManager.java

/**
 * This method retrieves the actually uploaded transformators 
 * that are currently not registered in the OASIS ebXML RegRep
 * //w  w  w . j av  a2 s.c  o m
 * @return
 * @throws Exception
 */
public JSONArray getJEntries() throws Exception {

    JSONArray jEntries = new JSONArray();

    List<CacheEntry> transformators = cache.getAll();
    for (int ix = 0; ix < transformators.size(); ix++) {

        XslTransformator transformator = (XslTransformator) transformators.get(ix);
        String key = transformator.getKey();

        JSONObject jTransformator = new JSONObject();

        jTransformator.put(JsonConstants.J_KEY, key);
        jTransformator.put(JsonConstants.J_NAME, transformator.getName());

        jTransformator.put(JsonConstants.J_DESC, "No description available.");
        jTransformator.put(JsonConstants.J_MIME, transformator.getMimetype());

        jEntries.put(jEntries.length(), jTransformator);

    }

    return jEntries;

}

From source file:CNCEntities.ResponseRequestCheckCount.java

@Override
public JSONObject getJsonEntity() {
    JSONObject jo = new JSONObject();
    try {// w w w  .j  a  v a2  s  .  c o m
        jo.put("code", code);
        jo.put("msg", msg);
        jo.put("listprovider", listprovider);
    } catch (JSONException ex) {
        Logger.getLogger(ResponseRequestCheckCount.class.getName()).log(Level.SEVERE, null, ex);
    }
    return jo;
}