下面列出了org.json.simple.JSONArray#toJSONString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* [CommonUtils.getTimeInstant] -------- When getting a time instant, it is properly obtained when
* passing a valid SQL timestamp without miliseconds.
*/
@Test
public void testGetTimeInstantSQLTimestampWithoutMiliseconds() {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "-------- When getting a time instant, it is properly obtained when passing a valid "
+ "SQL timestamp without miliseconds");
JSONObject metadataJson = new JSONObject();
metadataJson.put("name", "TimeInstant");
metadataJson.put("type", "SQL timestamp");
metadataJson.put("value", "2017-01-01 00:00:01");
JSONArray metadatasJson = new JSONArray();
metadatasJson.add(metadataJson);
String metadatasStr = metadatasJson.toJSONString();
Long timeInstant = CommonUtils.getTimeInstant(metadatasStr);
try {
assertTrue(timeInstant != null);
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]") + "- OK - Time instant obtained for '"
+ metadatasJson.toJSONString() + "' is '" + timeInstant + "'");
} catch (AssertionError e) {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "- FAIL - Time instant obtained is 'null'");
throw e;
} // try catch
}
/**
* [CommonUtils.getTimeInstant] -------- When getting a time instant, it is properly obtained when passing
* a valid ISO 8601 timestamp without miliseconds.
*/
@Test
public void testGetTimeInstantISO8601TimestampWithoutMiliseconds() {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "-------- When getting a time instant, it is properly obtained when passing a valid "
+ "ISO 8601 timestamp without miliseconds");
JSONObject metadataJson = new JSONObject();
metadataJson.put("name", "TimeInstant");
metadataJson.put("type", "SQL timestamp");
metadataJson.put("value", "2017-01-01T00:00:01Z");
JSONArray metadatasJson = new JSONArray();
metadatasJson.add(metadataJson);
String metadatasStr = metadatasJson.toJSONString();
Long timeInstant = CommonUtils.getTimeInstant(metadatasStr);
try {
assertTrue(timeInstant != null);
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]") + "- OK - Time instant obtained for '"
+ metadatasJson.toJSONString() + "' is '" + timeInstant + "'");
} catch (AssertionError e) {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "- FAIL - Time instant obtained is 'null'");
throw e;
} // try catch
}
@Override
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid);
}
if (rateLimiting && i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}
@SuppressWarnings("unchecked")
@GET
public String getAddresses()
{
//CHECK IF WALLET EXISTS
if(!Controller.getInstance().doesWalletExists())
{
throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_WALLET_NO_EXISTS);
}
//GET ACCOUNTS
List<Account> accounts = Controller.getInstance().getAccounts();
//CONVERT TO LIST OF ADDRESSES
JSONArray addresses = new JSONArray();
for(Account account: accounts)
{
addresses.add(account.getAddress());
}
//RETURN
return addresses.toJSONString();
}
public Map<String, UUID> call() throws IOException, ParseException, InterruptedException {
Map<String, UUID> uuidMap = new HashMap<>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid);
}
if (i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}
private String getActiveBannersJSON() {
JSONArray banners = new JSONArray();
String serverId = ServerConfigurationService.getString("serverId", "localhost");
User currentUser = UserDirectoryService.getCurrentUser();
if (currentUser != null && currentUser.getId() != null && !"".equals(currentUser.getId())) {
for (Banner banner : getBanners().getRelevantBanners(serverId, currentUser.getId())) {
try {
JSONObject bannerData = new JSONObject();
bannerData.put("id", banner.getUuid());
bannerData.put("message", banner.getMessage());
bannerData.put("dismissible", banner.isDismissible());
bannerData.put("dismissed", banner.isDismissed());
bannerData.put("type", banner.getType());
banners.add(bannerData);
} catch (Exception e) {
log.warn("Error processing banner: " + banner, e);
}
}
}
return banners.toJSONString();
}
/**
* [CommonUtils.getTimeInstant] -------- When getting a time instant, it is properly obtained when
* passing a valid SQL timestamp with miliseconds.
*/
@Test
public void testGetTimeInstantSQLTimestampWithMiliseconds() {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "-------- When getting a time instant, it is properly obtained when passing a valid "
+ "SQL timestamp with miliseconds");
JSONObject metadataJson = new JSONObject();
metadataJson.put("name", "TimeInstant");
metadataJson.put("type", "SQL timestamp");
metadataJson.put("value", "2017-01-01 00:00:01.123");
JSONArray metadatasJson = new JSONArray();
metadatasJson.add(metadataJson);
String metadatasStr = metadatasJson.toJSONString();
Long timeInstant = CommonUtils.getTimeInstant(metadatasStr);
try {
assertTrue(timeInstant != null);
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "- OK - Time instant obtained for '" + metadatasJson.toJSONString() + "' is '"
+ timeInstant + "'");
} catch (AssertionError e) {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "- FAIL - Time instant obtained is 'null'");
throw e;
} // try catch
}
@SuppressWarnings("unchecked")
@GET
public String getNames()
{
//CHECK IF WALLET EXISTS
if(!Controller.getInstance().doesWalletExists())
{
throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_WALLET_NO_EXISTS);
}
List<Pair<Account, Name>> names = Controller.getInstance().getNames();
JSONArray array = new JSONArray();
for(Pair<Account, Name> name: names)
{
array.add(name.getB().toJson());
}
return array.toJSONString();
}
/**
* [CommonUtils.getTimeInstant] -------- When getting a time instant, it is properly obtained when
* passing a valid ISO 8601 timestamp with microseconds.
*/
@Test
public void testGetTimeInstantISO8601TimestampWithMicroseconds() {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "-------- When getting a time instant, it is properly obtained when passing a valid "
+ "ISO 8601 timestamp with microseconds");
JSONObject metadataJson = new JSONObject();
metadataJson.put("name", "TimeInstant");
metadataJson.put("type", "SQL timestamp");
metadataJson.put("value", "2017-01-01T00:00:01.123456Z");
JSONArray metadatasJson = new JSONArray();
metadatasJson.add(metadataJson);
String metadatasStr = metadatasJson.toJSONString();
Long timeInstant = CommonUtils.getTimeInstant(metadatasStr);
try {
assertTrue(timeInstant != null);
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]") + "- OK - Time instant obtained for '"
+ metadatasJson.toJSONString() + "' is '" + timeInstant + "'");
} catch (AssertionError e) {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "- FAIL - Time instant obtained is 'null'");
throw e;
} // try catch
}
/**
* [CommonUtils.getTimeInstant] -------- When getting a time instant, it is properly obtained when passing
* a valid ISO 8601 timestamp with miliseconds.
*/
@Test
public void testGetTimeInstantISO8601TimestampWithMiliseconds() {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "-------- When getting a time instant, it is properly obtained when passing a valid "
+ "ISO 8601 timestamp with miliseconds");
JSONObject metadataJson = new JSONObject();
metadataJson.put("name", "TimeInstant");
metadataJson.put("type", "SQL timestamp");
metadataJson.put("value", "2017-01-01T00:00:01.123Z");
JSONArray metadatasJson = new JSONArray();
metadatasJson.add(metadataJson);
String metadatasStr = metadatasJson.toJSONString();
Long timeInstant = CommonUtils.getTimeInstant(metadatasStr);
try {
assertTrue(timeInstant != null);
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]") + "- OK - Time instant obtained for '"
+ metadatasJson.toJSONString() + "' is '" + timeInstant + "'");
} catch (AssertionError e) {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "- FAIL - Time instant obtained is 'null'");
throw e;
} // try catch
}
/**
* 递归算法太消耗资源,不过现在暂时没有时间,等下次有时间再用非递归的实现算了,,
*/
@SuppressWarnings("unchecked")
private void initFolder(){
RepUser user=(RepUser) getSession().getAttribute(WebConstant.SessionAttrKey.USER);
if(user==null){
return;
}
//获取所有的专业类别
folders=folderService.findByhql(
"select f from RepFolder f where f.repUser.id=?", 0, user.getId());
//初始化用来构造json数据的list
folderJsonList=new ArrayList<Map<String,Map<String,Object>>>(10);
//List<RepFolder> stack=new ArrayList<RepFolder>();
//通过递归构造jsonArray形式的类别
for (RepFolder f : folders) {
if(f.getFather()==null){
Map<String, Map<String, Object>> map=new HashMap<String, Map<String, Object>>(1);
Map<String, Object> childMap=new HashMap<String, Object>(2);
childMap.put("children", recurseFolder(f));
childMap.put("text", f.getName());
map.put(f.getId().toString(), childMap);
folderJsonList.add(map);
}
}
String folderJsonArray=JSONArray.toJSONString(folderJsonList);
//输出用于构造树状类别列表的json数据
getRequest().setAttribute(WebConstant.RequestAttrKey
.FOLDER_JSON_ARRAY, folderJsonArray);
}
@SuppressWarnings("unchecked")
@GET
@Path("/address/{address}")
public String getBlocks(@PathParam("address") String address)
{
//CHECK IF WALLET EXISTS
if(!Controller.getInstance().doesWalletExists())
{
throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_WALLET_NO_EXISTS);
}
//CHECK ADDRESS
if(!Crypto.getInstance().isValidAddress(address))
{
throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_INVALID_ADDRESS);
}
//CHECK ACCOUNT IN WALLET
Account account = Controller.getInstance().getAccountByAddress(address);
if(account == null)
{
throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_WALLET_ADDRESS_NO_EXISTS);
}
JSONArray array = new JSONArray();
for(Block block: Controller.getInstance().getLastBlocks(account))
{
array.add(block.toJson());
}
return array.toJSONString();
}
@Override
public String toString() {
JSONArray jsonArray = new JSONArray();
jsonArray.add(_weight);
jsonArray.add(_startBin);
jsonArray.add(_endBin);
return jsonArray.toJSONString();
}
@Override
public String getGeoJsonOuputJSON(Date updated) throws Exception {
List<GeoJsonOutputModel> geoJsonOutputModels = new ArrayList<GeoJsonOutputModel>();
List<ClientApp> clientApps = clientAppService.findClientAppByAppType("appType",CodeLookUp.APP_MAP) ;
for(int i=0; i < clientApps.size(); i++){
ClientApp clientApp = clientApps.get(i);
List<TaskQueue> taskQueues = taskQueueService.getTaskQueueByClientAppStatus(clientApp.getClientAppID(), StatusCodeType.TASK_LIFECYCLE_COMPLETED);
geoJsonOutputModels = processTaskQueue(taskQueues, geoJsonOutputModels, updated);
}
JSONArray jsonArray = new JSONArray();
for(GeoJsonOutputModel item : geoJsonOutputModels) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("info", (JSONObject)parser.parse(item.getGeoJsonInfo()));
jsonObject.put("features", (JSONObject)parser.parse(item.getGeoJson()));
jsonArray.add(jsonObject);
}
String returnValue = jsonArray.toJSONString() ;
return returnValue;
}
/**
* [CommonUtils.getTimeInstant] -------- When getting a time instant, it is properly obtained when passing
* a valid ISO 8601 timestamp with offset with miliseconds.
*/
@Test
public void testGetTimeInstantISO8601TimestampWithOffsetWithMiliseconds() {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "-------- When getting a time instant, it is properly obtained when passing a valid "
+ "ISO 8601 timestamp with offset and miliseconds");
String offsets[] = {"+11:00", "+1100", "+11", "-11:00", "-1100", "-11"};
for (String offset : offsets) {
JSONObject metadataJson = new JSONObject();
metadataJson.put("name", "TimeInstant");
metadataJson.put("type", "ISO8601");
metadataJson.put("value", "2017-01-01T00:00:01.123456" + offset);
JSONArray metadatasJson = new JSONArray();
metadatasJson.add(metadataJson);
String metadatasStr = metadatasJson.toJSONString();
Long timeInstant = CommonUtils.getTimeInstant(metadatasStr);
try {
assertTrue(timeInstant != null);
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]") + "- OK - Time instant obtained for '"
+ metadatasJson.toJSONString() + "' is '" + timeInstant + "'");
} catch (AssertionError e) {
System.out.println(getTestTraceHead("[CommonUtils.getTimeInstant]")
+ "- FAIL - Time instant obtained is 'null'");
throw e;
} // try catch
}
}
/**
* [NGSIUtils.getGeometry] -------- When getting a geometry, a CartoDB point is obtained when passing
* an attribute with 'geometry' metadata.
*/
@Test
public void testGetGeometryMetadata() {
System.out.println(getTestTraceHead("[Utils.getLocation]")
+ "-------- When getting a geometry, a CartoDB point is obtained when passing an attribute "
+ "with 'location' metadata");
JSONObject metadataJson = new JSONObject();
metadataJson.put("name", "location");
metadataJson.put("type", "string");
metadataJson.put("value", "WGS84");
JSONArray metadatasJson = new JSONArray();
metadatasJson.add(metadataJson);
String attrMetadataStr = metadatasJson.toJSONString();
String attrValue = "-3.7167, 40.3833";
String attrType = "coordinates"; // irrelevant for this test
boolean swapCoordinates = false; // irrelevant for this test
ImmutablePair<String, Boolean> geometry = NGSIUtils.getGeometry(
attrValue, attrType, attrMetadataStr, swapCoordinates);
try {
assertEquals("ST_SetSRID(ST_MakePoint(-3.7167::double precision , 40.3833::double precision ), 4326)", geometry.getLeft());
System.out.println(getTestTraceHead("[Utils.getLocation]")
+ "- OK - Geometry '" + geometry.getLeft() + "' obtained for an attribute with metadata '"
+ attrMetadataStr + "' and value '" + attrValue + "'");
} catch (AssertionError e) {
System.out.println(getTestTraceHead("[Utils.getLocation]")
+ "- FAIL - Geometry '" + geometry.getLeft() + "' obtained for an attribute with metadata '"
+ attrMetadataStr + "' and value '" + attrValue + "'");
throw e;
} // try catch // try catch
}
@SuppressWarnings("unchecked")
@GET
@Path("/network")
public String getNetworkTransactions()
{
List<Transaction> transactions = Controller.getInstance().getUnconfirmedTransactions();
JSONArray array = new JSONArray();
for(Transaction transaction: transactions)
{
array.add(transaction.toJson());
}
return array.toJSONString();
}
/**
* Removes given usernames that is cached on the API Gateway
*
* @param username_list - The list of usernames to be removed from the gateway cache.
*/
public void invalidateCachedUsernames(String[] username_list) {
JSONArray userArray = new JSONArray();
userArray.addAll(Arrays.asList(username_list));
Object[] objectData = new Object[]{APIConstants.GATEWAY_USERNAME_CACHE_NAME, userArray.toJSONString()};
Event event = new Event(APIConstants.CACHE_INVALIDATION_STREAM_ID, System.currentTimeMillis(),
null, null, objectData);
APIUtil.publishEventToEventHub(null, event);
}
@SuppressWarnings("unchecked")
@GET
@Path("/address/{address}")
public String getNames(@PathParam("address") String address)
{
//CHECK IF WALLET EXISTS
if(!Controller.getInstance().doesWalletExists())
{
throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_WALLET_NO_EXISTS);
}
//CHECK ADDRESS
if(!Crypto.getInstance().isValidAddress(address))
{
throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_INVALID_ADDRESS);
}
//CHECK ACCOUNT IN WALLET
Account account = Controller.getInstance().getAccountByAddress(address);
if(account == null)
{
throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_WALLET_ADDRESS_NO_EXISTS);
}
JSONArray array = new JSONArray();
for(Name name: Controller.getInstance().getNames(account))
{
array.add(name.toJson());
}
return array.toJSONString();
}
public String getJsonString(){
return JSONArray.toJSONString(ops);
}