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:com.ibm.mobilefirst.mobileedge.abstractmodel.GyroscopeData.java

@Override
public JSONObject asJSON() {
    JSONObject json = super.asJSON();

    try {/* w ww.j a  v  a  2 s .c  o m*/
        JSONObject data = new JSONObject();
        data.put("x", x);
        data.put("y", y);
        data.put("z", z);
        json.put("gyroscope", data);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return json;
}

From source file:io.selendroid.server.SelendroidResponse.java

@Override
public String render() {
    JSONObject o = new JSONObject();
    try {// ww  w  .ja v a 2s.  c  om
        if (sessionId != null) {
            o.put("sessionId", sessionId);
        }
        o.put("status", status);
        if (value != null) {
            o.put("value", value);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return o.toString();
}

From source file:io.selendroid.server.SelendroidResponse.java

private JSONObject buildErrorValue(Throwable t) throws JSONException {
    JSONObject errorValue = new JSONObject();
    errorValue.put("class", t.getClass().getCanonicalName());

    // TODO: Form exception in a way that will be unpacked nicely on the local end.
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    t.printStackTrace(printWriter);/*from   w  ww.  j  a v a2s  . c  o m*/
    errorValue.put("message", t.getMessage() + "\n" + stringWriter.toString());

    /*
     * There is no easy way to attach exception 'cause' clauses here.
     * See workaround above which is used instead.
     */
    //      JSONArray stackTrace = new JSONArray();
    //      for (StackTraceElement el : t.getStackTrace()) {
    //          JSONObject frame = new JSONObject();
    //          frame.put("lineNumber", el.getLineNumber());
    //          frame.put("className", el.getClassName());
    //          frame.put("methodName", el.getMethodName());
    //          frame.put("fileName", el.getFileName());
    //          stackTrace.put(frame);
    //      }
    //      errorValue.put("stackTrace", stackTrace);

    return errorValue;
}

From source file:org.searsia.web.SearsiaApplication.java

protected static Response responseError(int status, String error) {
    JSONObject json = new JSONObject();
    json.put("searsia", VERSION);
    json.put("error", error);
    String entity = json.toString();
    return Response.status(status).entity(entity).header("Access-Control-Allow-Origin", "*").build();
}

From source file:com.guillaumesoft.escapehellprison.PurchaseActivity.java

public void requestPurchase(final Product product)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", product.getIdentifier());
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);//  w  w w  . j a  v a2  s . c o  m
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(product.getIdentifier());

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }
    mOuyaFacade.requestPurchase(this, purchasable, new PurchaseListener(product));
}

From source file:org.loklak.api.iot.NetmonPushServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Query post = RemoteAccess.evaluate(request);
    String remoteHash = Integer.toHexString(Math.abs(post.getClientHost().hashCode()));

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;/*  w  w  w  .  j a  v a 2  s .c  om*/
    }

    String url = post.get("url", "");
    if (url == null || url.length() == 0) {
        response.sendError(400, "your request does not contain an url to your data object");
        return;
    }
    String screen_name = post.get("screen_name", "");
    if (screen_name == null || screen_name.length() == 0) {
        response.sendError(400, "your request does not contain required screen_name parameter");
        return;
    }

    JSONArray nodesList = new JSONArray();
    byte[] xmlText;
    try {
        xmlText = ClientConnection.download(url);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(new String(xmlText))));
        NodeList routerList = document.getElementsByTagName("router");
        for (int i = 0; i < routerList.getLength(); i++) {
            JSONObject node = convertDOMNodeToMap(routerList.item(i));
            if (node != null)
                nodesList.put(node);
        }
    } catch (Exception e) {
        Log.getLog().warn(e);
        response.sendError(400, "error reading json file from url");
        return;
    }

    JsonFieldConverter converter = new JsonFieldConverter(
            JsonFieldConverter.JsonConversionSchemaEnum.NETMON_NODE);
    JSONArray nodes = converter.convert(nodesList);

    for (Object node_obj : nodes) {
        JSONObject node = (JSONObject) node_obj;
        if (!node.has("text")) {
            node.put("text", "");
        }
        node.put("source_type", SourceType.NETMON.toString());
        if (!node.has("user")) {
            node.put("user", new JSONObject());
        }

        List<Object> location_point = new ArrayList<>();
        location_point.add(0, Double.parseDouble((String) node.get("latitude")));
        location_point.add(1, Double.parseDouble((String) node.get("longitude")));
        node.put("location_point", location_point);
        node.put("location_mark", location_point);
        node.put("location_source", LocationSource.USER.name());
        try {
            node.put("id_str", PushServletHelper.computeMessageId(node, SourceType.NETMON));
        } catch (Exception e) {
            DAO.log("Problem computing id" + e.getMessage());
            continue;
        }
        try {
            JSONObject user = (JSONObject) node.get("user");
            user.put("screen_name", computeUserId(user.get("update_date"), user.get("id"), SourceType.NETMON));
        } catch (Exception e) {
            DAO.log("Problem computing user id : " + e.getMessage());
        }
    }

    PushReport pushReport = PushServletHelper.saveMessagesAndImportProfile(nodes, Arrays.hashCode(xmlText),
            post, SourceType.NETMON, screen_name);

    String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), pushReport);
    response.getOutputStream().println(res);
    DAO.log(request.getServletPath() + " -> records = " + pushReport.getRecordCount() + ", new = "
            + pushReport.getNewCount() + ", known = " + pushReport.getKnownCount() + ", from host hash "
            + remoteHash);

}

From source file:org.b3log.solo.dev.ArticleGenerator.java

/**
 * Generates some dummy articles with the specified context.
 * /* ww  w . j a  va  2  s. c om*/
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @throws IOException io exception 
 */
@RequestProcessing(value = "/dev/articles/gen/*", method = HTTPRequestMethod.GET)
public void genArticles(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException {
    if (RuntimeMode.DEVELOPMENT != Latkes.getRuntimeMode()) {
        LOGGER.log(Level.WARNING,
                "Article generation just for development mode, " + "current runtime mode is [{0}]",
                Latkes.getRuntimeMode());
        response.sendRedirect("/");

        return;
    }

    Stopwatchs.start("Gen Articles");

    final String requestURI = request.getRequestURI();
    final int num = Integer
            .valueOf(requestURI.substring((Latkes.getContextPath() + "/dev/articles/gen/").length()));

    try {
        final ArticleMgmtService articleMgmtService = ArticleMgmtService.getInstance();
        final UserQueryService userQueryService = UserQueryService.getInstance();
        final JSONObject admin = userQueryService.getAdmin();
        final String authorEmail = admin.optString(User.USER_EMAIL);

        for (int i = 0; i < num; i++) {
            final JSONObject article = new JSONObject();

            // XXX: http://en.wikipedia.org/wiki/Markov_chain
            article.put(Article.ARTICLE_TITLE, "article title" + i);
            article.put(Article.ARTICLE_ABSTRACT, "article" + i + " abstract");
            article.put(Article.ARTICLE_TAGS_REF, "tag1,tag2");
            article.put(Article.ARTICLE_AUTHOR_EMAIL, authorEmail);
            article.put(Article.ARTICLE_COMMENT_COUNT, 0);
            article.put(Article.ARTICLE_VIEW_COUNT, 0);
            article.put(Article.ARTICLE_CONTENT, "article content");
            article.put(Article.ARTICLE_PERMALINK, "article" + i + " permalink");
            article.put(Article.ARTICLE_HAD_BEEN_PUBLISHED, true);
            article.put(Article.ARTICLE_IS_PUBLISHED, true);
            article.put(Article.ARTICLE_PUT_TOP, false);
            article.put(Article.ARTICLE_CREATE_DATE, new Date());
            article.put(Article.ARTICLE_UPDATE_DATE, new Date());
            article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random());
            article.put(Article.ARTICLE_COMMENTABLE, true);
            article.put(Article.ARTICLE_VIEW_PWD, "");
            article.put(Article.ARTICLE_SIGN_ID, "1");

            articleMgmtService.addArticle(new JSONObject().put(Article.ARTICLE, article));
        }

    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }

    Stopwatchs.end();

    response.sendRedirect("/");
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private void deleteAllRelations(Storage storage, String csid)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException {
    JSONObject r = new JSONObject();
    r.put("src", base + "/" + csid);
    // XXX needs pagination support CSPACE-1819
    JSONObject data = storage.getPathsJSON("relations/main", r);
    String[] paths = (String[]) data.get("listItems");
    for (String relation : paths) {
        storage.deleteJSON("relations/main/" + relation);
    }//  w w  w.ja v  a  2 s.c  o m
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private void setRelations(Storage storage, String csid, JSONArray relations)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException {
    deleteAllRelations(storage, csid);//from  www  .  java  2 s .  c om
    for (int i = 0; i < relations.length(); i++) {
        // Extract data from miniobject
        JSONObject in = relations.getJSONObject(i);
        String dst_type = spec.getRecordByWebUrl(in.getString("recordtype")).getID();
        String dst_id = in.getString("csid");
        String type = in.getString("relationshiptype");
        // Create relation
        JSONObject r = new JSONObject();
        r.put("src", base + "/" + csid);
        r.put("dst", dst_type + "/" + dst_id);
        r.put("type", type);
        storage.autocreateJSON("relations/main", r, null);
    }
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private JSONObject permJSON(String permValue) throws JSONException {
    JSONObject perm = new JSONObject();
    perm.put("name", permValue);
    return perm;//w ww .  j  a  v  a 2s  .c  o  m
}