Java Code Examples for org.json.JSONArray#toString()

The following examples show how to use org.json.JSONArray#toString() . 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
Source File: RESTLikeQueryService.java    From epcis with Apache License 2.0 7 votes vote down vote up
/**
 * Returns a list of all query names available for use with the subscribe
 * and poll methods. This includes all pre-defined queries provided by the
 * implementation, including those specified in Section 8.2.7.
 * 
 * No Dependency with Backend
 * 
 * @return JSONArray of query names ( String )
 */
@RequestMapping(value = "/GetQueryNames", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> getQueryNamesREST()
		throws SecurityException, ValidationException, ImplementationException {
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.add("Content-Type", "application/json; charset=utf-8");

	JSONArray jsonArray = new JSONArray();
	List<String> queryNames = getQueryNames();
	for (int i = 0; i < queryNames.size(); i++) {
		jsonArray.put(queryNames.get(i));
	}

	return new ResponseEntity<>(jsonArray.toString(1), responseHeaders, HttpStatus.OK);
}
 
Example 2
Source File: TraceabilityQueryService.java    From epcis with Apache License 2.0 6 votes vote down vote up
public String getRelationship(ChronoGraph g, String epc) {
	try {
		Set<String> edgeLabelSet = new HashSet<String>();
		JSONArray labelArr = new JSONArray();
		// Vertex should be unique
		ChronoVertex v = g.getChronoVertices("vlabel", epc).iterator().next();
		Iterator<ChronoEdge> edgeIter = v.getChronoEdges(Direction.BOTH, null).iterator();
		while (edgeIter.hasNext()) {
			ChronoEdge edge = edgeIter.next();
			edgeLabelSet.add(edge.getLabel());
		}
		Iterator<String> edgeLabelIter = edgeLabelSet.iterator();
		while (edgeLabelIter.hasNext()) {
			labelArr.put(edgeLabelIter.next().toString());
		}
		return labelArr.toString(2);
	} catch (NoSuchElementException e) {
		return "No such vertex labelled with {epc} : " + e;
	}
}
 
Example 3
Source File: L.java    From Aria with Apache License 2.0 6 votes vote down vote up
/**
 * 打印JSON
 */
public static void j(String jsonStr) {
  if (isDebug) {
    String message;
    try {
      if (jsonStr.startsWith("{")) {
        JSONObject jsonObject = new JSONObject(jsonStr);
        message = jsonObject.toString(JSON_INDENT); //这个是核心方法
      } else if (jsonStr.startsWith("[")) {
        JSONArray jsonArray = new JSONArray(jsonStr);
        message = jsonArray.toString(JSON_INDENT);
      } else {
        message = jsonStr;
      }
    } catch (JSONException e) {
      message = jsonStr;
    }

    message = LINE_SEPARATOR + message;
    String[] lines = message.split(LINE_SEPARATOR);
    printLog(D, lines);
  }
}
 
Example 4
Source File: PageResource.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * TODO COMMENTARE
 *
 */
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public String getDataSets() {
	try {
		JSONArray resultsJSON = new JSONArray();
		Iterator<String> it = pages.keySet().iterator();
		while (it.hasNext()) {
			String pageName = it.next();
			resultsJSON.put(pages.get(pageName));
		}

		return resultsJSON.toString();
	} catch (Exception e) {
		throw SpagoBIEngineServiceExceptionHandler.getInstance().getWrappedException("", getEngineInstance(), e);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 5
Source File: PageResource.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public String getDataSets() {
	try {
		JSONArray resultsJSON = new JSONArray();
		Iterator<String> it = pages.keySet().iterator();
		while (it.hasNext()) {
			String pageName = it.next();
			resultsJSON.put(pages.get(pageName));
		}

		return resultsJSON.toString();
	} catch (Exception e) {
		throw SpagoBIEngineServiceExceptionHandler.getInstance().getWrappedException("", getEngineInstance(), e);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 6
Source File: LivePhoto.java    From sealrtc-android with MIT License 5 votes vote down vote up
public void setMatrixF(float[] matrixF) {
    if (matrixF != null) {
        JSONArray jsonArray = new JSONArray();
        for (float mat : matrixF) {
            try {
                jsonArray.put(mat);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        this.transformMatrixStr = jsonArray.toString();
    }
}
 
Example 7
Source File: AbstractQuery.java    From algoliasearch-client-android with MIT License 5 votes vote down vote up
protected static @NonNull String buildJSONArray(@NonNull String[] values) {
    JSONArray array = new JSONArray();
    for (String value : values) {
        array.put(value);
    }
    return array.toString();
}
 
Example 8
Source File: MagicPhotoEntity.java    From PLDroidShortVideo with Apache License 2.0 5 votes vote down vote up
public void setGroupType(double[] groupType) {
    if (groupType != null) {
        JSONArray jsonArray = new JSONArray();
        for (double groupPoint : groupType) {
            try {
                jsonArray.put(groupPoint);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        this.groupTypeStr = jsonArray.toString();
    }
    this.groupType = groupType;
}
 
Example 9
Source File: JSONArrayAdapter.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
@Override
public String serialize(JSONArray value) {
    if (value == null) {
        return null;
    }

    return value.toString();
}
 
Example 10
Source File: CellLocationUSourceData.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
@Override
public String serialize(@NonNull PluginDataFormat format) {
    String res;
    switch (format) {
        default:
            JSONArray jsonArray = new JSONArray();
            for (CellLocationSingleData singleData : data) {
                jsonArray.put(singleData.toString());
            }
            res = jsonArray.toString();
    }
    return res;
}
 
Example 11
Source File: DashboardResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@GET
@Path(value = "/data")
@Produces(MediaType.APPLICATION_JSON)
public String getData(@QueryParam("type") String type) throws Exception {
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  String response = null;

  String file = null;
  if (type.equals("dataset")) {
    List<String> collections = CACHE_REGISTRY_INSTANCE.getDatasetsCache().getDatasets();
    JSONArray array = new JSONArray(collections);
    response = array.toString();
    // file = "assets/data/getdataset.json";
  } else if (type.equals("metrics")) {
    file = "assets/data/getmetrics.json";
  } else if (type.equals("treemaps")) {
    file = "assets/data/gettreemaps.json";
  } else {
    throw new Exception("Invalid param!!");
  }
  if (response == null) {
    InputStream inputStream = classLoader.getResourceAsStream(file);

    // ClassLoader classLoader = getClass().getClassLoader();
    // InputStream inputStream = classLoader.getResourceAsStream("assets.data/getmetrics.json");

    try {
      response = IOUtils.toString(inputStream);
    } catch (IOException e) {
      response = e.toString();
    }
  }
  return response;
}
 
Example 12
Source File: Request.java    From FacebookNewsfeedSample-Android with Apache License 2.0 5 votes vote down vote up
private static void serializeRequestsAsJSON(Serializer serializer, Collection<Request> requests, Bundle attachments)
        throws JSONException, IOException {
    JSONArray batch = new JSONArray();
    for (Request request : requests) {
        request.serializeToBatch(batch, attachments);
    }

    String batchAsString = batch.toString();
    serializer.writeString(BATCH_PARAM, batchAsString);
}
 
Example 13
Source File: BaseMap.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
public static String toJsonString(List<BaseMap> maps) throws JSONException {
    JSONArray array = new JSONArray();
    for (BaseMap map : maps) {
        array.put(map.toJson());
    }
    return array.toString();
}
 
Example 14
Source File: FileChangeEventBatchUtil.java    From codewind-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void run() {
	List<ChangedFileEntry> entries = new ArrayList<>();

	synchronized (lock) {
		// When the timer task has triggered, we pull all the entries out of the file
		// list and reset the timer.
		entries.addAll(files_synch_lock);
		files_synch_lock.clear();

		timer_synch_lock.cancel();
		timer_synch_lock = null;

		if (entries.size() == 0) {
			return;
		}

	}

	// Sort ascending by timestamp, remove duplicate entries, then flip to
	// descending
	Collections.sort(entries);
	removeDuplicateEventsOfType(entries, EventType.CREATE);
	removeDuplicateEventsOfType(entries, EventType.DELETE);
	Collections.reverse(entries);

	if (entries.size() == 0) {
		return;
	}

	long mostRecentEntryTimestamp = entries.get(0).getTimestamp();

	String changeSummary = generateChangeListSummaryForDebug(entries);
	log.logInfo(
			"Batch change summary for " + projectId + "@ " + mostRecentEntryTimestamp + ": " + changeSummary);

	if (!DISABLE_CWCTL_CLI_SYNC) {
		// Use CWCTL CLI SYNC command
		parent.internal_informCwctlOfFileChanges(projectId);

	} else {

		// Use the old way of communicating file values.

		// TODO: Remove this entire else block once CWCTL sync is mature.

		// Split the entries into separate requests (chunks), to ensure that each
		// request is no larger then a given size.
		List<JSONArray> fileListsToSend = new ArrayList<>();
		while (entries.size() > 0) {

			// Remove at most MAX_REQUEST_SIZE_IN_PATHS paths from paths
			List<JSONObject> currList = new ArrayList<>();
			while (currList.size() < MAX_REQUEST_SIZE_IN_PATHS && entries.size() > 0) {

				// Oldest entries will be at the end of the list, and we want to send those
				// first.
				ChangedFileEntry nextPath = entries.remove(entries.size() - 1);
				try {
					currList.add(nextPath.toJsonObject());
				} catch (JSONException e1) {
					log.logSevere("Unable to convert changed file entry to json", e1, projectId);
				}
			}

			if (currList.size() > 0) {
				fileListsToSend.add(new JSONArray(currList));
			}

		}

		// Compress, convert to base64, then send
		List<String> base64Compressed = new ArrayList<>();
		for (JSONArray array : fileListsToSend) {

			String json = array.toString();

			byte[] compressedData = compressString(json);
			base64Compressed.add(Base64.getEncoder().encodeToString(compressedData));

			if (DEBUG_PRINT_COMPRESSION_RATIO) {
				int uncompressedSize = json.getBytes().length;
				int compressedSize = compressedData.length;
				System.out.println("Compression ratio: " + uncompressedSize + " -> " + compressedSize
						+ " (ratio: " + (int) ((100 * compressedSize) / uncompressedSize) + ") [per path: "
						+ (compressedSize / array.length()) + "]");
			}

		}

		if (base64Compressed.size() > 0) {
			parent.internal_sendBulkFileChanges(projectId, mostRecentEntryTimestamp, base64Compressed);
		}

	}

}
 
Example 15
Source File: PluginResult.java    From pychat with MIT License 4 votes vote down vote up
public PluginResult(Status status, JSONArray message) {
    this.status = status.ordinal();
    this.messageType = MESSAGE_TYPE_JSON;
    encodedMessage = message.toString();
}
 
Example 16
Source File: SakaiReport.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
protected String toJsonString(ResultSet rs) throws SQLException, JSONException {
    ResultSetMetaData rsmd = rs.getMetaData();
    JSONArray array = new JSONArray();
    int numColumns = rsmd.getColumnCount();

    while (rs.next()) {

        JSONObject obj = new JSONObject();
        for (int i = 1; i < numColumns + 1; i++) {

            String column_label = rsmd.getColumnLabel(i);

            log.debug("Column Name=" + column_label + ",type=" + rsmd.getColumnType(i));

            switch (rsmd.getColumnType(i)) {
                case Types.ARRAY:
                    obj.put(column_label, rs.getArray(i));
                    break;
                case Types.BIGINT:
                    obj.put(column_label, rs.getInt(i));
                    break;
                case Types.BOOLEAN:
                    obj.put(column_label, rs.getBoolean(i));
                    break;
                case Types.BLOB:
                    obj.put(column_label, rs.getBlob(i));
                    break;
                case Types.DOUBLE:
                    obj.put(column_label, rs.getDouble(i));
                    break;
                case Types.FLOAT:
                    obj.put(column_label, rs.getFloat(i));
                    break;
                case Types.INTEGER:
                    obj.put(column_label, rs.getInt(i));
                    break;
                case Types.NVARCHAR:
                    obj.put(column_label, rs.getNString(i));
                    break;
                case Types.VARCHAR:
                    obj.put(column_label, rs.getString(i));
                    break;
                case Types.TINYINT:
                    obj.put(column_label, rs.getInt(i));
                    break;
                case Types.SMALLINT:
                    obj.put(column_label, rs.getInt(i));
                    break;
                case Types.DATE:
                    obj.put(column_label, rs.getDate(i));
                    break;
                case Types.TIMESTAMP:
                    obj.put(column_label, rs.getTimestamp(i));
                    break;
                default:
                    obj.put(column_label, rs.getObject(i));
                    break;
            }

        }
        array.put(obj);

    }
    return array.toString();
}
 
Example 17
Source File: PluginResult.java    From countly-sdk-cordova with MIT License 4 votes vote down vote up
public PluginResult(Status status, JSONArray message) {
    this.status = status.ordinal();
    this.messageType = MESSAGE_TYPE_JSON;
    encodedMessage = message.toString();
}
 
Example 18
Source File: QueryJSONDeserializer.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private void deserializeHavings(JSONArray havingsJOSN, IDataSource dataSource, Query query) throws SerializationException {

		JSONObject havingJSON;
		IModelField field;

		String filterId;
		String filterDescription;
		boolean promptable;

		String[] operandValues;
		String operandDescription;
		String operandType;
		String operandFunction;
		String[] operandLasDefaulttValues;
		String[] operandLastValues;
		JSONArray operandValuesJSONArray;
		JSONArray operandDefaultValuesJSONArray;
		JSONArray operandLastValuesJSONArray;
		HavingField.Operand leftOperand;
		HavingField.Operand rightOperand;
		String operator;
		String booleanConnector;
		IAggregationFunction function;

		logger.debug("IN");

		try {

			logger.debug("Query [" + query.getId() + "] have [" + havingsJOSN.length() + "] to deserialize");
			for (int i = 0; i < havingsJOSN.length(); i++) {

				try {
					havingJSON = havingsJOSN.getJSONObject(i);
					filterId = havingJSON.getString(QuerySerializationConstants.FILTER_ID);
					filterDescription = havingJSON.getString(QuerySerializationConstants.FILTER_DESCRIPTION);
					promptable = havingJSON.getBoolean(QuerySerializationConstants.FILTER_PROMPTABLE);

					operandValues = new String[] { havingJSON.getString(QuerySerializationConstants.FILTER_LO_VALUE) };
					operandDescription = havingJSON.getString(QuerySerializationConstants.FILTER_LO_DESCRIPTION);
					operandType = havingJSON.getString(QuerySerializationConstants.FILTER_LO_TYPE);
					operandLasDefaulttValues = new String[] { havingJSON.getString(QuerySerializationConstants.FILTER_LO_DEFAULT_VALUE) };
					operandLastValues = new String[] { havingJSON.getString(QuerySerializationConstants.FILTER_LO_LAST_VALUE) };
					operandFunction = havingJSON.getString(QuerySerializationConstants.FILTER_LO_FUNCTION);
					function = AggregationFunctions.get(operandFunction);
					leftOperand = new HavingField.Operand(operandValues, operandDescription, operandType, operandLasDefaulttValues, operandLastValues,
							function);

					operator = havingJSON.getString(QuerySerializationConstants.FILTER_OPERATOR);

					operandValuesJSONArray = havingJSON.getJSONArray(QuerySerializationConstants.FILTER_RO_VALUE);
					operandValues = JSONUtils.asStringArray(operandValuesJSONArray);
					operandDescription = havingJSON.getString(QuerySerializationConstants.FILTER_RO_DESCRIPTION);
					operandType = havingJSON.getString(QuerySerializationConstants.FILTER_RO_TYPE);
					operandDefaultValuesJSONArray = havingJSON.optJSONArray(QuerySerializationConstants.FILTER_RO_DEFAULT_VALUE);
					operandLasDefaulttValues = JSONUtils.asStringArray(operandDefaultValuesJSONArray);
					operandLastValuesJSONArray = havingJSON.optJSONArray(QuerySerializationConstants.FILTER_RO_LAST_VALUE);
					operandLastValues = JSONUtils.asStringArray(operandLastValuesJSONArray);
					operandFunction = havingJSON.getString(QuerySerializationConstants.FILTER_RO_FUNCTION);
					function = AggregationFunctions.get(operandFunction);
					rightOperand = new HavingField.Operand(operandValues, operandDescription, operandType, operandLasDefaulttValues, operandLastValues,
							function);

					booleanConnector = havingJSON.getString(QuerySerializationConstants.FILTER_BOOLEAN_CONNETOR);

					Assert.assertTrue(!StringUtilities.isEmpty(operator), "Undefined operator for filter: " + havingJSON.toString());
					Assert.assertTrue(!"NONE".equalsIgnoreCase(operator), "Undefined operator NONE for filter: " + havingJSON.toString());

					query.addHavingField(filterId, filterDescription, promptable, leftOperand, operator, rightOperand, booleanConnector);

				} catch (JSONException e) {
					throw new SerializationException(
							"An error occurred while deserializing filter [" + havingsJOSN.toString() + "] of query [" + query.getId() + "]", e);
				}

			}
		} catch (Throwable t) {
			throw new SerializationException("An error occurred while deserializing filters of query [" + query.getId() + "]", t);
		} finally {
			logger.debug("OUT");
		}

	}
 
Example 19
Source File: JsonArrayRequest.java    From pearl with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonArrayRequest(int method, String url, JSONArray jsonRequest,
                        Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
            errorListener);
}
 
Example 20
Source File: JsonArrayRequest.java    From product-emm with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonArrayRequest(int method, String url, JSONArray jsonRequest,
                        Listener<JSONArray> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
            errorListener);
}