Java Code Examples for org.json.simple.JSONObject#toJSONString()

The following examples show how to use org.json.simple.JSONObject#toJSONString() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@EntityCustomAction(action = "remove", viewKey = EntityView.VIEW_NEW)
public String remove(EntityView view, Map<String, Object> params) {

    JSONObject result = new JSONObject();

    result.put("status", "ERROR");

    if (!checkCSRFToken(params)) {
        return result.toJSONString();
    }

    User currentUser = UserDirectoryService.getCurrentUser();
    String currentUserId = currentUser.getId();

    if (currentUserId == null) {
        log.warn("Access denied");
        return result.toJSONString();
    }

    if (imageLogic.resetProfileImage(currentUserId)) {
        profileImageService.resetCachedProfileImageId(currentUserId);
        result.put("status", "SUCCESS");
    }

    return result.toJSONString();
}
 
Example 2
Source Project: protect   File: PartialHandler.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static String computeEncryptedPartials(final ApvssShareholder shareholder, final String secretName,
		final Integer requesterId) throws NotFoundException {

	// This server
	final int serverIndex = shareholder.getIndex();

	// Epoch information
	final long epoch = shareholder.getEpoch();

	// Return encrypted partials
	final SimpleEntry<BigInteger, BigInteger> encryptedPartials = shareholder.computeEncryptedPartial(requesterId);
	final BigInteger encryptedShare1Part = encryptedPartials.getKey();
	final BigInteger encryptedShare2Part = encryptedPartials.getValue();

	// Return the result in json
	final JSONObject obj = new JSONObject();
	obj.put("responder", new Integer(serverIndex));
	obj.put("requester", new Integer(requesterId));
	obj.put("epoch", new Long(epoch));
	obj.put("share1_part", encryptedShare1Part.toString());
	obj.put("share2_part", encryptedShare2Part.toString());
	return obj.toJSONString() + "\n";

}
 
Example 3
@SuppressWarnings("rawtypes")
private void createHar(String pt, String rt) {
    Har<String, Log> har = new Har<>();
    Page p = new Page(pt, har.pages());
    har.addPage(p);
    for (Object res : (JSONArray) JSONValue.parse(rt)) {
        JSONObject jse = (JSONObject) res;
        if (jse.size() > 14) {
            Entry e = new Entry(jse.toJSONString(), p);
            har.addEntry(e);
        }
    }
    har.addRaw(pt, rt);
    Control.ReportManager.addHar(har, (TestCaseReport) Report,
            escapeName(Data));
}
 
Example 4
Source Project: io   File: AbstractCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Box作成.
 * @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;
}
 
Example 5
Source Project: sepia-assist-server   File: Number.java    License: MIT License 6 votes vote down vote up
@Override
public String build(String input) {
	//extracted any number?
	if (!NluTools.stringContains(input, ".*\\d.*")){
		return "";
	}
	
	//expects a number including type as string
	String type = getTypeClass(input, language).replaceAll("^<|>$", "").trim();
	String value = input.replaceFirst(".*?(" + PLAIN_NBR_REGEXP + ").*", "$1").trim();
	
	//build default result
	JSONObject itemResultJSON = new JSONObject();
		JSON.add(itemResultJSON, InterviewData.INPUT, input);
		JSON.add(itemResultJSON, InterviewData.VALUE, value.replaceAll(",", "."));	//default decimal format is "1.00"
		JSON.add(itemResultJSON, InterviewData.NUMBER_TYPE, type);
	
	buildSuccess = true;
	return itemResultJSON.toJSONString();
}
 
Example 6
Source Project: SB_Elsinore_Server   File: UrlEndpoints.java    License: MIT License 6 votes vote down vote up
@UrlEndpoint(url = "/toggleaux", help = "Toggle the aux pin for a PID",
parameters = {@Parameter(name = "toggle", value = "The name of the PID to toggle the pin for")})
public Response toggleAux() {
    JSONObject usage = new JSONObject();
    if (parameters.containsKey("toggle")) {
        String pidname = parameters.get("toggle");
        PID tempPID = LaunchControl.findPID(pidname);
        if (tempPID != null) {
            tempPID.toggleAux();
            return new NanoHTTPD.Response(Status.OK, MIME_HTML,
                    "Updated Aux for " + pidname);
        } else {
            BrewServer.LOG.warning("Invalid PID: " + pidname + " provided.");
            usage.put("Error", "Invalid name supplied: " + pidname);
        }
    }

    usage.put("toggle",
            "The name of the PID to toggle the aux output for");
    return new Response(usage.toJSONString());
}
 
Example 7
Source Project: sepia-assist-server   File: Color.java    License: MIT License 6 votes vote down vote up
@Override
public String build(String input) {
	//is accepted result?
	String inputLocal = getLocal(input, language);
	if (inputLocal.isEmpty()){
		return "";
	}
	
	//build default result
	JSONObject itemResultJSON = new JSONObject();
		JSON.add(itemResultJSON, InterviewData.VALUE, input);
		//TODO: should use GENERALIZED
		JSON.add(itemResultJSON, InterviewData.VALUE_LOCAL, inputLocal);
		//TODO: add ACCOUNT here?
	
	buildSuccess = true;
	return itemResultJSON.toJSONString();
}
 
Example 8
Source Project: sepia-assist-server   File: TravelRequestInfo.java    License: MIT License 5 votes vote down vote up
@Override
public String build(String input) {
	//expects a color tag!
	String commonValue = input.replaceAll("^<|>$", "").trim();
	
	//build default result
	JSONObject itemResultJSON = new JSONObject();
		JSON.add(itemResultJSON, InterviewData.VALUE, commonValue);
	
	buildSuccess = true;
	return itemResultJSON.toJSONString();
}
 
Example 9
Source Project: io   File: EventResourceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * リクエストボディのlevelがない場合に場合にエラーとなること.
 */
@Test(expected = DcCoreException.class)
public void リクエストボディのlevelがない場合にエラーとなること() {
    TestEventResource resource = new TestEventResource();
    JSONObject body = createEventBody();
    body.remove("level");
    StringReader reader = new StringReader(body.toJSONString());
    JSONEvent event = resource.getRequestBody(reader);
    resource.validateEventProperties(event);
}
 
Example 10
@Test
public void testSingleDirection() {
  // Create testing connector
  List<MConnector> connectors = new LinkedList<MConnector>();
  connectors.add(BeanTestUtil.getConnector(1L, "jdbc", true, false));
  connectors.add(BeanTestUtil.getConnector(2L, "mysql", false, true));

  // Create testing bundles
  Map<Long, ResourceBundle> bundles = new HashMap<Long, ResourceBundle>();
  bundles.put(1L, ConfigTestUtil.getResourceBundle());
  bundles.put(2L, ConfigTestUtil.getResourceBundle());

  // Serialize it to JSON object
  ConnectorsBean bean = new ConnectorsBean(connectors, bundles);
  JSONObject json = bean.extract(false);

  // "Move" it across network in text form
  String string = json.toJSONString();

  // Retrieved transferred object
  JSONObject retrievedJson = JSONUtils.parse(string);
  ConnectorsBean retrievedBean = new ConnectorsBean();
  retrievedBean.restore(retrievedJson);

  assertEquals(connectors.size(), retrievedBean.getConnectors().size());
  assertEquals(connectors.get(0), retrievedBean.getConnectors().get(0));
  assertEquals(connectors.get(1), retrievedBean.getConnectors().get(1));
}
 
Example 11
Source Project: sepia-assist-server   File: FashionBrand.java    License: MIT License 5 votes vote down vote up
@Override
public String build(String input) {
	//build default result
	JSONObject itemResultJSON = new JSONObject();
		JSON.add(itemResultJSON, InterviewData.VALUE, input);
	
	buildSuccess = true;
	return itemResultJSON.toJSONString();
}
 
Example 12
@Test
public void testNoDirection() {
  // Create testing connector
  List<MConnector> connectors = new LinkedList<MConnector>();
  connectors.add(BeanTestUtil.getConnector(1L, "jdbc", false, false));
  connectors.add(BeanTestUtil.getConnector(2L, "mysql", false, false));

  // Create testing bundles
  Map<Long, ResourceBundle> bundles = new HashMap<Long, ResourceBundle>();
  bundles.put(1L, ConfigTestUtil.getResourceBundle());
  bundles.put(2L, ConfigTestUtil.getResourceBundle());

  // Serialize it to JSON object
  ConnectorsBean bean = new ConnectorsBean(connectors, bundles);
  JSONObject json = bean.extract(false);

  // "Move" it across network in text form
  String string = json.toJSONString();

  // Retrieved transferred object
  JSONObject retrievedJson = JSONUtils.parse(string);
  ConnectorsBean retrievedBean = new ConnectorsBean();
  retrievedBean.restore(retrievedJson);

  assertEquals(connectors.size(), retrievedBean.getConnectors().size());
  assertEquals(connectors.get(0), retrievedBean.getConnectors().get(0));
  assertEquals(connectors.get(1), retrievedBean.getConnectors().get(1));
}
 
Example 13
@EntityCustomAction(action = "createTagCollection", viewKey = EntityView.VIEW_NEW)
public String createTagCollection(EntityView view, Map<String, Object> params) {
    try {
        assertSession(params);

        WrappedParams wp = new WrappedParams(params);


        //Mandatory fields
        String tagCollectionId = UUID.randomUUID().toString();
        String  name = wp.getString("name");

        //Optional fields (default values)
        String description = null;
        String externalsourcename = null;
        String externalsourcedescription = null;

        Boolean externalupdate = Boolean.TRUE;
        Boolean externalcreation = Boolean.TRUE;
        Long lastsynchronizationdate = 0L;
        Long lastupdatedateinexternalsystem = 0L;


        if (wp.containsKey("description")){
            description = wp.getString("description");
        }
        if (wp.containsKey("externalsourcename")){
            externalsourcename = wp.getString("externalsourcename");
        }
        if (wp.containsKey("externalsourcedescription")){
            externalsourcedescription = wp.getString("externalsourcedescription");
        }
        if (wp.containsKey("externalcreation")){
            externalcreation = wp.getBoolean("externalcreation");
        }
        if (wp.containsKey("externalupdate")){
            externalupdate = wp.getBoolean("externalupdate");
        }
        if (wp.containsKey("lastsynchronizationdate")){
            lastsynchronizationdate = wp.getEpochMS("lastsynchronizationdate");
        }
        if (wp.containsKey("lastupdatedateinexternalsystem")) {
            lastupdatedateinexternalsystem = wp.getEpochMS("lastupdatedateinexternalsystem");
        }



        TagCollection tagCollection = new TagCollection(tagCollectionId,
                name,
                description,
                null,
                0L,
                externalsourcename,
                externalsourcedescription,
                null,
                0L,
                externalupdate,
                externalcreation,
                lastsynchronizationdate,
                lastupdatedateinexternalsystem);


        Errors errors = tagCollection.validate();

        if (errors.hasErrors()) {
            return respondWithError(errors);
        }

        String uuid = tagService().getTagCollections().createTagCollection(tagCollection);

        JSONObject result = new JSONObject();
        result.put("status", "OK");
        result.put("tagcollectionid", uuid);
        return result.toJSONString();
    } catch (Exception e) {
        return respondWithError(e);
    }
}
 
Example 14
@EntityCustomAction(action = "updateTagCollection", viewKey = EntityView.VIEW_EDIT)
public String updateTagCollection(EntityView view, Map<String, Object> params) {
    try {
        assertSession(params);

        WrappedParams wp = new WrappedParams(params);

        String tagcollectionid= wp.getString("tagcollectionid");

        TagCollection tagCollection = tagService().getTagCollections().getForId(tagcollectionid).get();

        //We don't need to change the creation date or user

        if (wp.containsKey("name")){
            tagCollection.setName(wp.getString("name"));
        }
        if (wp.containsKey("description")){
        tagCollection.setDescription(wp.getString("description"));
        }
        if (wp.containsKey("externalsourcename")){
            tagCollection.setExternalSourceName(wp.getString("externalsourcename"));
        }
        if (wp.containsKey("externalsourcedescription")){
            tagCollection.setExternalSourceDescription(wp.getString("externalsourcedescription"));
        }
        if (wp.containsKey("externalupdate")){
            tagCollection.setExternalUpdate(wp.getBoolean("externalupdate"));
        }
        if (wp.containsKey("externalcreation")){
            tagCollection.setExternalCreation(wp.getBoolean("externalcreation"));
        }
        if (wp.containsKey("lastsynchronizationdate")){
            tagCollection.setLastSynchronizationDate(wp.getEpochMS("lastsynchronizationdate"));
        }
        if (wp.containsKey("lastupdatedateinexternalsystem")) {
            tagCollection.setLastUpdateDateInExternalSystem(wp.getEpochMS("lastupdatedateinexternalsystem"));
        }
        Errors errors = tagCollection.validate();

        if (errors.hasErrors()) {
            return respondWithError(errors);
        }

        tagService().getTagCollections().updateTagCollection(tagCollection);

        JSONObject result = new JSONObject();
        result.put("status", "OK");
        result.put("tagcollectionid", tagcollectionid);
        return result.toJSONString();
    } catch (Exception e) {
        return respondWithError(e);
    }
}
 
Example 15
private void updateJSONToCustomer(Connection conn , int cid , JSONObject json ){    
  
  if ( !SQLTest.hasJSON  || SQLHelper.isDerbyConn(conn))
    return;

  String jsonString = null ;
  try{
    
    if ( json != null ) {
      jsonString = json.toJSONString();
    }
           
 Log.getLogWriter().info("updating trade.customers with NETWORTH_JSON:" +  jsonString + " where CID:" + cid );
 
 String stmt = "update trade.customers set networth_json = ? where cid = " + cid;
 
 PreparedStatement ps = conn.prepareStatement(stmt);
 
 ps.setObject(1, jsonString);
 ps.execute();
 
  }catch (SQLException se ){      
    throw new TestException ( "Adding " + jsonString + " to trade.customers" + "Exception: "  + TestHelper.getStackTrace(se));
  }
  
}
 
Example 16
protected int insertToTable(PreparedStatement stmt, int oid, int cid, int sid, int qty,
     String status, Timestamp time, BigDecimal bid, int tid, boolean isPut) throws SQLException {
       
   
   String database = SQLHelper.isDerbyConn(stmt.getConnection())?"Derby - " :"gemfirexd - " +  " ";
   
   
   JSONObject json = new JSONObject();
   String  jsonLog ="";
   if (!SQLHelper.isDerbyConn(stmt.getConnection())) { 
      json = getJSONObject(oid,cid,sid,qty,status,time,bid,tid);
      jsonLog = ",JSON_DETAILS: " +json.toJSONString();
   }
   
   Log.getLogWriter().info( database + (isPut ? "putting" : "inserting" ) + " into trade.buyorders with OID:" + oid +
       ",CID:"+ cid + ",SID:" + sid + ",QTY:" + qty + ",STATUS:" + status +
       ",TIME:"+ time + ",BID:" + bid + ",TID:" + tid + jsonLog);
   
   stmt.setInt(1, oid);
   stmt.setInt(2, cid);
   stmt.setInt(3, sid);
   stmt.setInt(4, qty);
   stmt.setBigDecimal(5, bid);
   stmt.setTimestamp(6, time);
   stmt.setString(7, status);       
   stmt.setInt(8, tid);
   if (!SQLHelper.isDerbyConn(stmt.getConnection())) { 
   Clob jsonClob = stmt.getConnection().createClob();
   jsonClob.setString(1, json.toJSONString());
   stmt.setClob(9, jsonClob);
   }
   
   int rowCount = stmt.executeUpdate();

   Log.getLogWriter().info( database + (isPut ? "put " : "inserted " ) + rowCount + " rows in trade.buyorders with OID:" + oid +
       ",CID:"+ cid + ",SID:" + sid + ",QTY:" + qty + ",STATUS:" + status +
       ",TIME:"+ time + ",BID:" + bid + ",TID:" + tid + jsonLog);
   
   if (SQLTest.hasJSON &&  !SQLHelper.isDerbyConn(stmt.getConnection()) && !SQLTest.hasTx && !setCriticalHeap)  insertUpdateCustomerJson(stmt.getConnection(), cid, json);
   
   SQLWarning warning = stmt.getWarnings(); //test to see there is a warning
   if (warning != null) {
     SQLHelper.printSQLWarning(warning);
   } 

   if ( database.contains("gemfirexd") && isPut) {
     if (! SQLTest.ticket49794fixed) {
       insertToBuyordersFulldataset(stmt.getConnection() , oid, cid, sid, qty, bid, time, status, tid);
       }      
     Log.getLogWriter().info( database +  (isPut ? "putting" : "inserting" ) + " into trade.buyorders with OID:" + oid +
         ",CID:"+ cid + ",SID:" + sid + ",QTY:" + qty + ",STATUS:" + status +
         ",TIME:"+ time + ",BID:" + bid + ",TID:" + tid + jsonLog);    
     
    rowCount = stmt.executeUpdate();
    
    Log.getLogWriter().info( database + (isPut ? "put" : "inserted" ) + rowCount + " rows in trade.buyorders with OID:" + oid +
        ",CID:"+ cid + ",SID:" + sid + ",QTY:" + qty + ",STATUS:" + status +
        ",TIME:"+ time + ",BID:" + bid + ",TID:" + tid + jsonLog);   
    warning = stmt.getWarnings(); //test to see there is a warning   
    if (warning != null) {
      SQLHelper.printSQLWarning(warning);
    } 
}    
   return rowCount;
 }
 
Example 17
@SuppressWarnings("unchecked")
private String toJSON() {
    JSONObject json = new JSONObject();
    EncodingUtils.putJSON(json, JSON_MIME_TYPE, mMimeType);
    return json.toJSONString();
}
 
Example 18
@Override
public String assembleTPybossaJson(ClientApp clientApp, String key, String value) throws Exception{

    String getInfo = this.getAppInfo(clientApp);
    JSONParser parser = new JSONParser();

    JSONObject data = (JSONObject) parser.parse(getInfo);


    String created = (String)data.get("created");

    JSONObject info  = (JSONObject)data.get("info");
    String long_description = (String)data.get("long_description");
    String tutorial = (String)info.get("tutorial");
    String task_presenter = (String)info.get("task_presenter");

    if(key.equalsIgnoreCase(CodeLookUp.WELCOMPAGE_UPDATE)){
        long_description = value;
    }

    if(key.equalsIgnoreCase(CodeLookUp.TUTORIAL)){
        tutorial = value;
    }

    if(key.equalsIgnoreCase(CodeLookUp.TASK_PRESENTER)){
        task_presenter = value;
    }

    JSONObject app = new JSONObject();

    app.put("task_presenter", task_presenter);

    app.put("tutorial", tutorial);
    app.put("thumbnail", "http://i.imgur.com/lgZAWIc.png");

    JSONObject app2 = new JSONObject();
    app2.put("info", app );

    app2.put("long_description", long_description);
    app2.put("name", clientApp.getName());
    app2.put("short_name", clientApp.getShortName());
    app2.put("description", clientApp.getShortName());
    app2.put("id", clientApp.getPlatformAppID());
    app2.put("time_limit", 0);
    app2.put("long_tasks", 0);
    app2.put("created", created);
    app2.put("calibration_frac", 0);
    app2.put("bolt_course_id", 0);
    app2.put("link", "<link rel='self' title='app' href='http://localhost:5000/api/app/2'/>");
    app2.put("allow_anonymous_contributors", true);
    app2.put("time_estimate", 0);
    app2.put("hidden", 0);
    if(data.get("category_id")!=null){
        long category_id = (Long)data.get("category_id");
        app2.put("category_id", category_id);
    }
    //app2.put("owner_id", 1);

    return  app2.toJSONString();
}
 
Example 19
/**
 * Transforms the given {@link ScriptableObject} into a JSON string.
 * 
 * @param object
 *            the object to serialize
 * @return JSON formatted string
 * @since 0.7.5
 */
public static String toJSON(final Scriptable object) {
    final JSONObject json = toJSONObject(object);
    if (json == null) {
        return null;
    }
    return json.toJSONString();
}
 
Example 20
Source Project: io   File: JsonUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * This method converts the Map values to string form.
 * @param jsonMap Target Map
 * @return JSON string
 */
public static String toJsonString(final Map<String, Object> jsonMap) {
    return JSONObject.toJSONString(jsonMap);
}