Example usage for org.json JSONObject put

List of usage examples for org.json JSONObject put

Introduction

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

Prototype

public JSONObject put(String key, Object value) throws JSONException 

Source Link

Document

Put a key/value pair in the JSONObject.

Usage

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  ww .java2s.  c om*/
    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;//from   w ww  .j av a 2s  .c o  m
    }

    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.loklak.api.iot.NetmonPushServlet.java

private static JSONObject convertDOMNodeToMap(Node node) {
    Node directChild = node.getFirstChild();
    if (directChild == null) {
        return null;
    }// www . ja v  a  2 s . c  o  m
    JSONObject result = new JSONObject(true);
    while (directChild != null) {
        if (directChild.getChildNodes().getLength() == 1
                && directChild.getChildNodes().item(0).getNodeType() == Node.TEXT_NODE) {
            result.put(directChild.getNodeName(), directChild.getChildNodes().item(0).getTextContent());
        } else {
            result.put(directChild.getNodeName(), convertDOMNodeToMap(directChild));
        }
        directChild = directChild.getNextSibling();
    }
    return result;
}

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

/**
 * Generates some dummy articles with the specified context.
 * //from   ww w. j  ava  2s  .c o m
 * @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);
    }//from w  w  w  .j a 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  w ww . j  a v  a  2  s .com
    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;/*from  w w  w .  jav a  2 s  .  c  om*/
}

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

private JSONObject getPermID(Storage storage, String name, String queryString, String permbase,
        JSONArray actions)/*from  w w  w .  j a v a  2 s.  co  m*/
        throws JSONException, UIException, ExistException, UnimplementedException, UnderlyingStorageException {

    JSONObject permitem = new JSONObject();
    JSONObject permrestrictions = new JSONObject();
    permrestrictions.put("keywords", name);
    permrestrictions.put("queryTerm", "actGrp");
    permrestrictions.put("queryString", queryString);
    JSONObject data = searcher.getJSON(storage, permrestrictions, "items", permbase);

    String permid = "";
    JSONArray items = data.getJSONArray("items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        String resourcename = item.getString("summary");
        String actionGroup = item.getString("number");
        //need to do a double check as the query is an inexact match
        if (resourcename.equals(name) && actionGroup.equals(queryString)) {
            permid = item.getString("csid");
        }
    }
    if (permid.equals("")) {

        //create the permission
        /**
         * {
        "effect": "PERMIT",
        "resourceName": "testthing2",
                
        "action":[{"name":"CREATE"},{"name":"READ"},{"name":"UPDATE"},{"name":"DELETE"},{"name":"SEARCH"}]
        }
         */

        JSONObject permission_add = new JSONObject();
        permission_add.put("effect", "PERMIT");
        permission_add.put("description", "created because we couldn't find a match");
        permission_add.put("resourceName", name);
        permission_add.put("actionGroup", queryString);
        permission_add.put("action", actions);

        permid = storage.autocreateJSON(spec.getRecordByWebUrl("permission").getID(), permission_add, null);

    }

    if (!permid.equals("")) {
        permitem.put("resourceName", name);
        permitem.put("permissionId", permid);
        permitem.put("actionGroup", queryString);
    }
    return permitem;

}

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

private void assignPermissions(Storage storage, String path, JSONObject data)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject fields = data.optJSONObject("fields");

    JSONArray permdata = new JSONArray();
    JSONObject permcheck = new JSONObject();
    if (fields.has("permissions")) {
        JSONArray permissions = fields.getJSONArray("permissions");
        for (int i = 0; i < permissions.length(); i++) {
            JSONObject perm = permissions.getJSONObject(i);

            Record recordForPermResource = Generic.RecordNameServices(spec, perm.getString("resourceName"));
            if (recordForPermResource != null) {
                if (recordForPermResource.hasSoftDeleteMethod()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            DELETE_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(//from   w  w w.  jav  a  2 s . co m
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/delete permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
                if (recordForPermResource.supportsLocking()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            LOCK_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/lock permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
            }
            JSONObject permitem = getPerm(storage, recordForPermResource, perm.getString("resourceName"),
                    perm.getString("permission"));
            if (permitem.has("permissionId")) {
                if (permcheck.has(permitem.getString("resourceName"))) {
                    //ignore as we have duplicate name - eek
                    log.warn("RecordCreateUpdate.assignPermissions got duplicate permission for: "
                            + permitem.getString("resourceName"));
                } else {
                    permcheck.put(permitem.getString("resourceName"), permitem);
                    permdata.put(permitem);
                }
            }
        }
    }

    //log.info("permdata"+permdata.toString());
    JSONObject roledata = new JSONObject();
    roledata.put("roleName", fields.getString("roleName"));

    String[] ids = path.split("/");
    roledata.put("roleId", ids[ids.length - 1]);

    JSONObject accountrole = new JSONObject();
    JSONObject arfields = new JSONObject();
    arfields.put("role", roledata);
    arfields.put("permission", permdata);
    accountrole.put("fields", arfields);
    //log.info("WAAA"+arfields.toString());
    if (fields != null)
        path = storage.autocreateJSON(spec.getRecordByWebUrl("permrole").getID(), arfields, null);
}

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

private boolean setPayloadField(String fieldName, JSONObject payloadOut, JSONObject fieldsSrc,
        JSONObject dataSrc, String defaultValue) throws JSONException {
    boolean result = true;

    if (fieldsSrc != null && fieldsSrc.has(fieldName)) {
        payloadOut.put(fieldName, fieldsSrc.getString(fieldName));
    } else if (dataSrc != null && dataSrc.has(fieldName)) {
        payloadOut.put(fieldName, dataSrc.getString(fieldName));
    } else if (defaultValue != null) {
        payloadOut.put(fieldName, defaultValue);
    } else {/*from   ww  w  . j  av a2 s.com*/
        result = false;
    }

    return result;
}