下面列出了org.json.simple.JSONArray#add ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
@SuppressWarnings("unchecked")
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
/**
* @return a {JSONArray} representing the current notitifcations list status.
*/
public JSONArray getNotificationStatus() {
JSONArray nStatus = new JSONArray();
JSONObject nObject = new JSONObject();
for (int i = 0; i < notificationsList.size(); i++) {
Notification n = notificationsList.get(i);
if (n.getNotification() == null) {
continue;
}
nObject.put("message", n.getMessage());
nObject.put("tag", "elsinore-" + i);
nStatus.add(nObject);
}
return nStatus;
}
/**
* Calculates pearson correlation between pair of columns in the in the matrix, assuming that there is a strict
* one to one relationship between the matrix columns and the field specifications in the list.
*
* Writes the correlation, pValue and standard error to a file using JSON format.
*
* @param matrix the input matrix where fields are represented by as columns and subjects by rows
* @param fields a list of field specifications for which the correlations are to be calculated
* @param correlationAnalysisOutputPath is the file to which the results are written
* @throws Exception
*/
public static void calculateAndOutputCorrelations(RealMatrix matrix, List<FieldRecipe> fields,
String correlationAnalysisOutputPath) throws Exception {
PearsonsCorrelation correlation = new PearsonsCorrelation(matrix);
RealMatrix correlationMatrix = correlation.getCorrelationMatrix();
RealMatrix pValueMatrix = correlation.getCorrelationPValues();
RealMatrix standardErrorMatrix = correlation.getCorrelationStandardErrors();
// Output the correlation analysis
JSONArray correlationArray = new JSONArray();
for (int i=0; i<correlationMatrix.getRowDimension(); i++){
for (int j=0; j<correlationMatrix.getColumnDimension(); j++){
JSONObject correlationObject = new JSONObject();
correlationObject.put("xFieldLabel", fields.get(i).toField().getLabel());
correlationObject.put("yFieldLabel", fields.get(j).toField().getLabel());
correlationObject.put("correlationCoefficient", correlationMatrix.getEntry(i,j));
correlationObject.put("pValue", pValueMatrix.getEntry(i,j));
correlationObject.put("standardError", standardErrorMatrix.getEntry(i,j));
correlationArray.add(correlationObject);
}
}
Writer writer = new OutputStreamWriter(new FileOutputStream(correlationAnalysisOutputPath), "UTF-8");
writer.write(correlationArray.toJSONString());
writer.flush();
writer.close();
}
@SuppressWarnings("unchecked")
@GET
public String getNameSales()
{
//CHECK IF WALLET EXISTS
if(!Controller.getInstance().doesWalletExists())
{
throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_WALLET_NO_EXISTS);
}
List<Pair<Account, NameSale>> nameSales = Controller.getInstance().getNameSales();
JSONArray array = new JSONArray();
for(Pair<Account, NameSale> nameSale: nameSales)
{
array.add(nameSale.getB().toJson());
}
return array.toJSONString();
}
private JSONArray addAllSubpages(Long pageId, JSONArray jsonLessons) {
List<SimplePageItem> items = simplePageToolDao.findItemsOnPage(pageId);
String url = getUrlForTool(DateManagerConstants.COMMON_ID_LESSONS);
for (SimplePageItem item : items) {
String toolTitle = toolManager.getTool(DateManagerConstants.COMMON_ID_LESSONS).getTitle();
if (item.getType() == SimplePageItem.PAGE) {
JSONObject lobj = new JSONObject();
lobj.put("id", Long.parseLong(item.getSakaiId()));
lobj.put("title", item.getName());
SimplePage page = simplePageToolDao.getPage(Long.parseLong(item.getSakaiId()));
if(page.getReleaseDate() != null) {
lobj.put("open_date", formatToUserDateFormat(page.getReleaseDate()));
} else {
lobj.put("open_date", null);
}
lobj.put("tool_title", toolTitle);
lobj.put("url", url);
lobj.put("extraInfo", rb.getString("tool.lessons.extra.subpage"));
jsonLessons.add(lobj);
jsonLessons = addAllSubpages(Long.parseLong(item.getSakaiId()), jsonLessons);
}
}
return jsonLessons;
}
@SuppressWarnings("unchecked")
//@Test
public void testQueryAggregate() throws Exception
{
JDBCTestUtils.setConnection(null);
JSONObject obj = new JSONObject();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", "test_name");
map.put("specialchars", "()*&^%[email protected]{}{}:\"\\\';::");
map.put("id", 12345);
map.put("double", 12345.333);
map.put("data_time", "2001-01-01 01:01:01.00");
obj.putAll(map);
JSONArray expectedArray = new JSONArray();
HashMap<String,JSONObject> objMap = new HashMap<String,JSONObject>();
objMap.put("1_testQueryAggregate", obj);
JSONObject expectedObject = new JSONObject();
expectedObject.put("$1", "1");
expectedArray.add(expectedObject);
JDBCTestUtils.insertData(objMap, "default");
String query = "select count(*) from default";
JSONArray actualArray = JDBCTestUtils.runQueryAndExtractMap(query);
assertEquals(expectedArray, actualArray);
}
/**
* Gets the plugin specific data. This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
private JSONArray createVertexArray(DecorativeLine arg0) {
JSONArray verts_array = new JSONArray();
verts_array.add(arg0.getPoint1().get(0)*visualizerScaleFactor);
verts_array.add(arg0.getPoint1().get(1)*visualizerScaleFactor);
verts_array.add(arg0.getPoint1().get(2)*visualizerScaleFactor);
verts_array.add(arg0.getPoint2().get(0)*visualizerScaleFactor);
verts_array.add(arg0.getPoint2().get(1)*visualizerScaleFactor);
verts_array.add(arg0.getPoint2().get(2)*visualizerScaleFactor);
return verts_array;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JSONArray categoryValues = new JSONArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(categoryValue);
}
values.put(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
private void addChild( JSONArray jChildren, IMetaStoreAttribute child ) {
JSONObject jChild = new JSONObject();
jChildren.add(jChild);
jChild.put("id", child.getId());
jChild.put("value", child.getValue());
JSONArray jSubChildren = new JSONArray();
jChild.put("children", jSubChildren);
List<IMetaStoreAttribute> subChildren = child.getChildren();
for (IMetaStoreAttribute subChild : subChildren) {
addChild(jSubChildren, subChild);
}
}
@SuppressWarnings( "unchecked" )
private String buildJsonQueryResult( QueryResult queryResult ) throws KettleException {
JSONArray list = new JSONArray();
for ( SObject sobject : queryResult.getRecords() ) {
list.add( buildJSONSObject( sobject ) );
}
StringWriter sw = new StringWriter();
try {
list.writeJSONString( sw );
} catch ( IOException e ) {
throw new KettleException( e );
}
return sw.toString();
}
private static JSONArray storeFlags(Map<String, Boolean> flags) {
JSONArray array = new JSONArray();
for (Map.Entry<String, Boolean> flag : flags.entrySet()) {
JSONObject obj = newJSONObject();
obj.put(NAME, flag.getKey());
obj.put(VALUE, flag.getValue());
array.add(obj);
}
return array;
}
@SuppressWarnings("unchecked")
protected JSONArray getUserArray(List<String> usernames)
{
JSONArray result = new JSONArray();
if (usernames != null)
{
for (String username : usernames)
{
result.add(getUserDetails(username));
}
}
return result;
}
/**
* Encode the protection flags to JSON
*/
@SuppressWarnings("unchecked")
public void encodeFlags() {
JSONArray root = new JSONArray();
for (Flag flag : flags.values()) {
if (flag != null) {
root.add(flag.getData());
}
}
data.put("flags", root);
}
public JSONArray toJSON(DecimalFormat format) {
JSONArray bins = new JSONArray();
for (Bin<T> bin : getBins()) {
bins.add(bin.toJSON(format));
}
return bins;
}
@SuppressWarnings("unchecked")
public static JSONArray toJSONScriptTransactions(List<ScriptTransactionBean> transs)
{
JSONArray jtranss = new JSONArray();
for (ScriptTransactionBean trans : transs)
jtranss.add(toJSONScriptTransaction(trans));
return jtranss;
}
@SuppressWarnings("unchecked")
@Test
public void testSimpleData() throws Exception
{
JDBCTestUtils.setConnection(null);
JSONObject obj = new JSONObject();
JSONObject jsonObjNew = new JSONObject();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", "test_name");
map.put("specialchars", "()*&^%[email protected]{}{}:\"\\\';::");
map.put("id", 12345);
map.put("double", 12345.333);
map.put("boolean", true);
map.put("data_time", "2001-01-01 01:01:01.00");
map.put("testid", "ProjectionJDBCDriverTests.testSimpleData");
obj.putAll(map);
JSONArray expectedArray = new JSONArray();
HashMap<String,JSONObject> objMap = new HashMap<String,JSONObject>();
objMap.put("1_testSimpleData", obj);
expectedArray.add(obj);
JDBCTestUtils.insertData(objMap, "default");
Thread.sleep(5000);
String query = "select * from default where testid = 'ProjectionJDBCDriverTests.testSimpleData'";
JDBCTestUtils.resetConnection();
try ( Connection con = JDBCTestUtils.con)
{
try (Statement stmt = con.createStatement())
{
try (ResultSet rs = stmt.executeQuery(query))
{
while(rs.next()){
CBResultSet cbrs = (CBResultSet) rs;
java.sql.ResultSetMetaData meta = cbrs.getMetaData();
SQLJSON jsonVal1 = cbrs.getSQLJSON("default");
Map actualMap = jsonVal1.getMap();
if(actualMap != null){
jsonObjNew.putAll(actualMap);
}
assertEquals(obj, jsonObjNew);
}
}
finally{
stmt.executeUpdate("delete from default");
Thread.sleep(10000);
}
}
}
}
public boolean createReplaceGeometryMessage(Component mc, JSONObject msg) {
// Call geberate decorations on
ArrayDecorativeGeometry adg = new ArrayDecorativeGeometry();
// use generic Property interface to save/restore Appearance
boolean hasAppearance =false;
boolean visibleStatus=true;
AbstractProperty visibleProp=null;
if (mc.hasProperty("Appearance")){
visibleProp = mc.getPropertyByName("Appearance").getValueAsObject().getPropertyByName("visible");
visibleStatus = PropertyHelper.getValueBool(visibleProp);
if (!visibleStatus)
PropertyHelper.setValueBool(true, visibleProp);
hasAppearance = true;
}
mc.generateDecorations(true, mdh, state, adg);
mc.generateDecorations(false, mdh, state, adg);
if (hasAppearance && !visibleStatus)
PropertyHelper.setValueBool(visibleStatus, visibleProp);
WrapObject wo = WrapObject.safeDownCast(mc);
boolean isWrapObject = (wo != null);
if (isWrapObject)
dgimp.setQuadrants(wo.get_quadrant());
ArrayList<UUID> uuids = findUUIDForObject(mc);
if (adg.size() == uuids.size()){
JSONArray geoms = new JSONArray();
for (int i=0; i<adg.size(); i++){
UUID uuid = uuids.get(i);
dgimp.setGeomID(uuid);
DecorativeGeometry dg = adg.getElt(i);
dg.implementGeometry(dgimp);
JSONObject jsonObject = dgimp.getGeometryJson();
msg.put("Op", "ReplaceGeometry");
msg.put("uuid", uuid.toString());
geoms.add(jsonObject);
jsonObject.put("matrix", JSONUtilities.createMatrixFromTransform(dg.getTransform(),
dg.getScaleFactors(), visScaleFactor));
}
msg.put("geometries", geoms);
}
return true;
}
/**
* Combine multiple properties resource files to one JSON file
*/
@SuppressWarnings({ "unchecked", "static-access" })
public static void combinePropertiesToJSON() {
MultiComponentsDTO baseTranslationDTO = new MultiComponentsDTO();
baseTranslationDTO.setProductName(productName);
//baseTranslationDTO.setComponents(components);
//baseTranslationDTO.setLocales(TranslationConverterMain.locales);
baseTranslationDTO.setVersion(version);
String jsonFileName = ResourceFilePathGetter.getLocalizedJSONFileName("en");
JSONArray bundles = new JSONArray();
String[] componentArray = StringUtils.split(components, ConstantsChar.COMMA);
String[] localeArray = StringUtils.split(locales, ConstantsChar.COMMA);
SingleComponentDTO singleComponentDTO = new SingleComponentDTO();
singleComponentDTO.setProductName(productName);
singleComponentDTO.setVersion(version);
for (String component : componentArray) {
singleComponentDTO.setComponent(component);
Map<String, Object> bundle = new LinkedHashMap<String, Object>();
bundle.put("component", component);
for (String locale : localeArray) {
singleComponentDTO.setLocale(locale);
String url = "";
// Properties pro= PropertiesFileUtil.loadFromURL(url);//if the resource files to be converted are placed on a remote server,use this code
// Properties pro= PropertiesFileUtil.loadFromStream(url);//if the resource files to be converted are placed in the project path,use this code
Properties pro = PropertiesFileUtil.loadFromFile(url);// if the resource files to be converted are placed in the disk path,use this code
JSONObject pairs = new ProToJSONConverter().getJSONFromProp(pro);
bundle.put(locale, pairs);
}
bundles.add(bundle);
}
baseTranslationDTO.setBundles(bundles);
singleComponentDTO.setComponent("");
ResourceFileWritter bundlesGenerator = new ResourceFileWritter();
try {
bundlesGenerator.writeMultiComponentsDTOToJSONFile(
ResourceFilePathGetter.getLocalizedJSONFilesDir(targetLocation,
singleComponentDTO) + "/" + jsonFileName, baseTranslationDTO);
} catch (VIPResourceOperationException e) {
e.printStackTrace();
}
}