Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:cgeo.geocaching.connector.gc.GCParser.java

public static boolean uploadPersonalNote(Geocache cache) {
    final String userToken = getUserToken(cache);
    if (StringUtils.isEmpty(userToken)) {
        return false;
    }/*from w  ww .  ja v a  2  s . c  om*/

    try {
        final JSONObject jo = new JSONObject().put("dto",
                (new JSONObject().put("et", cache.getPersonalNote()).put("ut", userToken)));

        final String uriSuffix = "SetUserCacheNote";

        final String uriPrefix = "http://www.geocaching.com/seek/cache_details.aspx/";
        final HttpResponse response = Network.postJsonRequest(uriPrefix + uriSuffix, jo);
        Log.i("Sending to " + uriPrefix + uriSuffix + " :" + jo.toString());

        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            Log.i("GCParser.uploadPersonalNote - uploaded to GC.com");
            return true;
        }

    } catch (final JSONException e) {
        Log.e("Unknown exception with json wrap code", e);
    }
    Log.e("GCParser.uploadPersonalNote - cannot upload personal note");
    return false;
}

From source file:pt.webdetails.cfr.CfrContentGenerator.java

@Exposed(accessLevel = AccessLevel.PUBLIC, outputType = MimeType.JSON)
public void store(OutputStream out) throws IOException, InvalidOperationException, Exception {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List /* FileItem */ items = upload.parseRequest(getRequest());

    String fileName = null, savePath = null;
    byte[] contents = null;
    for (int i = 0; i < items.size(); i++) {
        FileItem fi = (FileItem) items.get(i);

        if ("path".equals(fi.getFieldName())) {
            savePath = fi.getString();//from   w w  w.  ja v a  2 s.  com
        }
        if ("file".equals(fi.getFieldName())) {
            contents = fi.get();
            fileName = fi.getName();
        }
    }

    if (fileName == null) {
        logger.error("parameter fileName must not be null");
        throw new Exception("paramete fileName must not be null");
    }
    if (savePath == null) {
        logger.error("parameter path must not be null");
        throw new Exception("parameter path must not be null");
    }
    if (contents == null) {
        logger.error("File content must not be null");
        throw new Exception("File content must not be null");
    }

    FileStorer fileStorer = new FileStorer(service.getRepository());

    boolean stored = fileStorer.storeFile(checkRelativePathSanity(fileName), checkRelativePathSanity(savePath),
            contents, userSession.getName());

    JSONObject result = new JSONObject().put("result", stored);
    writeOut(out, result.toString());
}

From source file:com.github.cambierr.lorawanpacket.semtech.PushData.java

@Override
public void toRaw(ByteBuffer _bb) throws MalformedPacketException {
    super.toRaw(_bb);
    _bb.put(gatewayEui);//from  w ww.  j  a  va2  s .  c  o  m

    JSONObject json = new JSONObject();
    if (!stats.isEmpty()) {
        JSONArray stat = new JSONArray();
        for (Stat s : stats) {
            stat.put(s.toJson());
        }
        json.put("stat", stats);
    }
    if (!rxpks.isEmpty()) {
        JSONArray rxpk = new JSONArray();
        for (Rxpk s : rxpks) {
            rxpk.put(s.toJson());
        }
        json.put("rxpk", rxpks);
    }

    _bb.put(json.toString().getBytes());
}

From source file:org.openhab.io.myopenhab.internal.MyOpenHABClient.java

private void handleRequestEvent(JSONObject data) {
    try {/*from  w  ww  .  j  a v a2  s. co m*/
        // Get myOH unique request Id
        int requestId = data.getInt("id");
        logger.debug("Got request {}", requestId);
        // Get request path
        String requestPath = data.getString("path");
        // Get request method
        String requestMethod = data.getString("method");
        // Get request body
        String requestBody = data.getString("body");
        // Get JSONObject for request headers
        JSONObject requestHeadersJson = data.getJSONObject("headers");
        logger.debug(requestHeadersJson.toString());
        // Get JSONObject for request query parameters
        JSONObject requestQueryJson = data.getJSONObject("query");
        // Create URI builder with base request URI of openHAB and path from request
        String newPath = URIUtil.addPaths(localBaseUrl, requestPath);
        @SuppressWarnings("unchecked")
        Iterator<String> queryIterator = requestQueryJson.keys();
        // Add query parameters to URI builder, if any
        newPath += "?";
        while (queryIterator.hasNext()) {
            String queryName = queryIterator.next();
            newPath += queryName;
            newPath += "=";
            newPath += URLEncoder.encode(requestQueryJson.getString(queryName), "UTF-8");
            if (queryIterator.hasNext())
                newPath += "&";
        }
        // Finally get the future request URI
        URI requestUri = new URI(newPath);
        // All preparations which are common for different methods are done
        // Now perform the request to openHAB
        // If method is GET
        logger.debug("Request method is " + requestMethod);
        Request request = jettyClient.newRequest(requestUri);
        setRequestHeaders(request, requestHeadersJson);
        request.header("X-Forwarded-Proto", "https");
        if (requestMethod.equals("GET")) {
            request.method(HttpMethod.GET);
        } else if (requestMethod.equals("POST")) {
            request.method(HttpMethod.POST);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else if (requestMethod.equals("PUT")) {
            request.method(HttpMethod.PUT);
            request.content(new BytesContentProvider(requestBody.getBytes()));
        } else {
            // TODO: Reject unsupported methods
            logger.error("Unsupported request method " + requestMethod);
            return;
        }
        ResponseListener listener = new ResponseListener(requestId);
        request.onResponseHeaders(listener).onResponseContent(listener).onRequestFailure(listener)
                .send(listener);
        // If successfully submitted request to http client, add it to the list of currently
        // running requests to be able to cancel it if needed
        runningRequests.put(requestId, request);
    } catch (JSONException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
    }
}

From source file:com.shampan.services.PhotoService.java

public static String getCategories() {
    JSONObject categories = new JSONObject();
    categories.put("categoryList", photoObject.getCategories());
    return categories.toString();
}

From source file:com.shampan.services.PhotoService.java

public static String getCategoriesAndAlbums(String userId) {
    JSONObject list = new JSONObject();
    list.put("categoryList", photoObject.getCategories());
    list.put("albumList", photoObject.getAlbumList(userId));
    return list.toString();
}

From source file:com.shampan.services.PhotoService.java

public static String getAlbums(String userId) {
    JSONObject albums = new JSONObject();
    albums.put("albumList", photoObject.getAlbums(userId));
    return albums.toString();
}

From source file:com.shampan.services.PhotoService.java

public static String getUserPhotos(String userId, int offset, int limit) {
    JSONObject photos = new JSONObject();
    //        photos.put("photoList", photoObject.getUserPhotos(userId, offset, limit));
    return photos.toString();
}

From source file:com.shampan.services.PhotoService.java

public static String getPhotos(String userId, String albumId) {
    JSONObject photos = new JSONObject();
    photos.put("albumInfo", photoObject.getAlbum(userId, albumId));
    photos.put("photoList", photoObject.getPhotos(userId, albumId));
    return photos.toString();
}

From source file:com.shampan.services.PhotoService.java

public static String getPhotoListByCategory(String albumId, String categoryId, int limit, int offset) {
    JSONObject photos = new JSONObject();
    photos.put("photoList", photoObject.getPhotoListByCategory(albumId, categoryId, limit, offset));
    return photos.toString();
}