Example usage for org.json.simple JSONObject toJSONString

List of usage examples for org.json.simple JSONObject toJSONString

Introduction

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

Prototype

public String toJSONString() 

Source Link

Usage

From source file:com.aerothai.database.dept.DeptService.java

/**
* Method to check whether uname and pwd combination are correct
* 
* @param uname//from   w w  w .  j a  va 2s.c  o m
* @param pwd
* @return
* @throws Exception
*/
public String updateDept(String query) throws Exception {

    Connection dbConn = null;
    JSONObject obj = new JSONObject();

    try {
        dbConn = DBConnection.createConnection();

        Statement stmt = dbConn.createStatement();
        System.out.println(query);
        stmt.executeUpdate(query);

        obj.put("tag", "update");
        obj.put("msg", "done");
        obj.put("status", true);

    } catch (SQLException sqle) {
        throw sqle;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        if (dbConn != null) {
            dbConn.close();
        }
        throw e;
    } finally {
        if (dbConn != null) {
            dbConn.close();
        }
    }
    return obj.toJSONString();
}

From source file:com.aerothai.database.dept.DeptService.java

/**
 * Method to check whether uname and pwd combination are correct
 * //from w  ww .j av a 2 s  .co m
 * @param uname
 * @param pwd
 * @return
 * @throws Exception
 */
public String deleteDept(String query) throws Exception {

    Connection dbConn = null;
    JSONObject obj = new JSONObject();

    try {
        dbConn = DBConnection.createConnection();

        Statement stmt = dbConn.createStatement();
        System.out.println(query);
        stmt.executeUpdate(query);

        obj.put("tag", "delete");
        obj.put("msg", "done");
        obj.put("status", true);

    } catch (SQLException sqle) {
        throw sqle;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        if (dbConn != null) {
            dbConn.close();
        }
        throw e;
    } finally {
        if (dbConn != null) {
            dbConn.close();
        }
    }
    return obj.toJSONString();
}

From source file:io.personium.test.jersey.box.odatacol.AbstractUserDataTest.java

/**
 * ?.//  w  w w .  j  a va 2s. c  om
 * @param cell ??
 * @param box ??
 * @param col ??
 * @param entityType ??
 * @param userDataId ID
 * @param body 
 * @return ?
 */
protected TResponse updateUserData(String cell, String box, String col, String entityType, String userDataId,
        JSONObject body) {
    return Http.request("box/odatacol/update.txt").with("cell", cell).with("box", box).with("collection", col)
            .with("entityType", entityType).with("id", userDataId).with("accept", MediaType.APPLICATION_JSON)
            .with("contentType", MediaType.APPLICATION_JSON).with("ifMatch", "*")
            .with("token", PersoniumUnitConfig.getMasterToken()).with("body", body.toJSONString()).returns()
            .statusCode(HttpStatus.SC_NO_CONTENT).debug();

}

From source file:io.personium.test.jersey.box.odatacol.AbstractUserDataTest.java

/**
 * ??./*from  w w  w.  j  a  v a 2s.  co  m*/
 * @param body 
 * @param sc ?
 * @return ?
 */
protected TResponse createUserData(JSONObject body, int sc) {
    TResponse response = Http.request("box/odatacol/create.txt").with("cell", cellName).with("box", boxName)
            .with("collection", colName).with("entityType", entityTypeName)
            .with("accept", MediaType.APPLICATION_JSON).with("contentType", MediaType.APPLICATION_JSON)
            .with("token", "Bearer " + PersoniumUnitConfig.getMasterToken()).with("body", body.toJSONString())
            .returns().statusCode(sc).debug();

    return response;
}

From source file:hoot.services.controllers.ogr.TranslatorResource.java

/**
 * <NAME>OGR-LTDS Translation Service Translate TDS to OSM</NAME>
 * <DESCRIPTION>/*from  w ww.  j  a  v  a  2s .  c o m*/
 * WARNING: THIS END POINT WILL BE DEPRECATED SOON
 * Translate TDS to OSM
 *  http://localhost:8080/hoot-services/ogr/ltds/translate/tds/{OSM element id}?translation={translation script}
 * </DESCRIPTION>
 * <PARAMETERS>
 * <translation>
 *    relative path of translation script
 * </translation>
 * </PARAMETERS>
 * <OUTPUT>
 *    TDS output
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/ogr/ltds/translate/-1669795?translation=MGCP.js</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 * {"attrs":{"FCODE":"AP030","HCT":"0","UID":"d9c4b1df-066c-4ece-a583-76fec0056b58"},"tableName":"LAP030"}
 *   </INPUT>
 * <OUTPUT>OSM XML output</OUTPUT>
 * </EXAMPLE>
* @param id
* @param translation
* @param osmXml
* @return
*/
@POST
@Path("/ltds/translate/tds/{id}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response translateTdsToOsm(@PathParam("id") String id,
        @QueryParam("translation") final String translation, String osmXml) {
    String outStr = "unknown";
    PostMethod mpost = new PostMethod("http://localhost:" + currentPort + "/tdstoosm");
    try {

        try {

            String ogrxml = osmXml.replace('"', '\'');

            JSONObject requestParams = new JSONObject();
            requestParams.put("command", "translate");
            requestParams.put("uid", id);
            requestParams.put("input", ogrxml);
            requestParams.put("script", homeFolder + "/translations" + translation);
            requestParams.put("direction", "toogr");
            String postData = requestParams.toJSONString();
            StringEntity se = new StringEntity(requestParams.toJSONString());
            StringRequestEntity requestEntity = new StringRequestEntity(requestParams.toJSONString(),
                    "text/plain", "UTF-8");
            mpost.setRequestEntity(requestEntity);

            mclient.executeMethod(mpost);
            String response = mpost.getResponseBodyAsString();

            JSONParser par = new JSONParser();
            JSONObject transRes = (JSONObject) par.parse(response);
            String tdsOSM = transRes.get("output").toString();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader strReader = new StringReader(tdsOSM);
            InputSource is = new InputSource(strReader);

            Document document = builder.parse(is);
            strReader.close();

            JSONObject attrib = new JSONObject();
            NodeList nodeList = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node instanceof Element) {
                    NodeList childNodes = node.getChildNodes();
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node cNode = childNodes.item(j);
                        if (cNode instanceof Element) {
                            String k = ((Element) cNode).getAttribute("k");
                            String v = ((Element) cNode).getAttribute("v");
                            attrib.put(k, v);

                        }
                    }
                }
            }

            JSONObject ret = new JSONObject();
            ret.put("tablenName", "");
            ret.put("attrs", attrib);
            outStr = ret.toJSONString();

        } catch (Exception ee) {
            ResourceErrorHandler.handleError("Failed upload: " + ee.toString(), Status.INTERNAL_SERVER_ERROR,
                    log);
        } finally {
            log.debug("postJobRequest Closing");
            mpost.releaseConnection();
        }

    } catch (Exception e) {
        ResourceErrorHandler.handleError("Translation error: " + e.toString(), Status.INTERNAL_SERVER_ERROR,
                log);
    }

    return Response.ok(outStr, MediaType.APPLICATION_JSON).build();
}

From source file:com.piusvelte.hydra.AuthServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ServletContext servletContext = getServletContext();
    ConnectionManager connMgr = ConnectionManager.getInstance(servletContext);
    JSONObject j = new JSONObject();
    String token = request.getParameter("token");
    if ((token != null) && (token.length() > 0)) {
        try {//from w  w  w.j av a2  s  . c o m
            connMgr.authorizeToken(token);
        } catch (Exception e) {
            servletContext.log(e.getMessage());
            JSONArray errors = new JSONArray();
            errors.add(e.getMessage());
            j.put("errors", errors);
            response.setStatus(403);
        }
    } else {
        try {
            j.put("result", connMgr.createToken());
        } catch (Exception e) {
            servletContext.log(e.getMessage());
            JSONArray errors = new JSONArray();
            errors.add(e.getMessage());
            j.put("errors", errors);
            response.setStatus(403);
        }
    }
    response.getWriter().write(j.toJSONString());
}

From source file:de.dailab.plistacontest.client.ClientAndContestHandler0MQ.java

/**
 * Method to handle incoming messages from the server.
 * /*from ww w. jav  a  2s  .  c  o  m*/
 * @param messageType
 *                the messageType of the incoming contest server message.
 * @param properties
 *                
 * @param entities
 * @return the response to the contest server
 */
private String handleIdomaarMessage(final String messageType, final String properties, final String entities) {
    // write all data from the server to a file
    logger.info(messageType + "\t" + properties + "\t" + entities);

    // create an jSON object from the String
    final JSONObject jOP = (JSONObject) JSONValue.parse(properties);
    final JSONObject jOE = (JSONObject) JSONValue.parse(entities);

    // merge the different jsonObjects and correct missing itemIDs
    jOP.putAll(jOE);
    Object itemID = jOP.get("itemID");
    if (itemID == null) {
        jOP.put("itemID", 0);
    }

    // define a response object
    String response = null;

    if ("impression".equalsIgnoreCase(messageType)) {

        // parse the type of the event
        final RecommenderItem item = RecommenderItem.parseEventNotification(jOP.toJSONString());
        final String eventNotificationType = item.getNotificationType();

        // new items shall be added to the list of items
        if (item.getItemID() != null) {
            recommenderItemTable.handleItemUpdate(item);
        }
        response = "handle impression eventNotification successful";

        // impression refers to articles read by the user
        if ("recommendation_request".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {

                item.setNumberOfRequestedResults(6);
                //List<Long> suggestedItemIDs = item.getListOfDisplayedRecs();
                List<Long> suggestedItemIDs = recommenderItemTable.getLastItems(item);
                response = "{" + "\"recs\": {" + "\"ints\": {" + "\"3\": " + suggestedItemIDs + "}" + "}}";

            } else {
                System.err.println("invalid itemID - requests are only valid for 'normal' articles");
            }
            // click refers to recommendations clicked by the user
        } else if ("click".equalsIgnoreCase(eventNotificationType)) {

            // we mark this information in the article table
            if (item.getItemID() != null) {
                // new items shall be added to the list of items
                recommenderItemTable.handleItemUpdate(item);

                response = "handle impression eventNotification successful";
            }
            response = "handle click eventNotification successful";

        } else {
            System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)");
        }

    } else if ("error_notification".equalsIgnoreCase(messageType)) {

        System.out.println("error-notification: " + jOP.toString() + jOE.toJSONString());

    } else {
        System.out.println("unknown MessageType: " + messageType);
        // Error handling
        logger.info(jOP.toString() + jOE.toJSONString());
        // this.contestRecommender.error(jObj.toString());
    }
    return response;
}

From source file:com.fujitsu.dc.test.jersey.AbstractCase.java

/**
 * Box?.//www . j  a  v  a  2 s .  c  o m
 * @param cellName cell??
 * @param boxName Box??
 * @return Box???
 */
@SuppressWarnings("unchecked")
public final DcResponse createBox(final String cellName, final String boxName) {
    DcRestAdapter rest = new DcRestAdapter();
    DcResponse res = null;

    // 
    HashMap<String, String> requestheaders = new HashMap<String, String>();
    requestheaders.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);

    // ?
    JSONObject requestBody = new JSONObject();
    requestBody.put("Name", boxName);
    String data = requestBody.toJSONString();

    // 
    try {
        res = rest.post(UrlUtils.cellCtl(cellName, Box.EDM_TYPE_NAME), data, requestheaders);
    } catch (Exception e) {
        fail(e.getMessage());
    }
    return res;
}