Java Code Examples for org.json.simple.JSONArray#add()

The following examples show how to use org.json.simple.JSONArray#add() . 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: Metrics.java    From IridiumSkyblock with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: Metrics.java    From QualityArmory with GNU General Public License v3.0 6 votes vote down vote up
/**
    * 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;
   }
 
Example 3
Source File: Notifications.java    From SB_Elsinore_Server with MIT License 6 votes vote down vote up
/**
 * @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;
}
 
Example 4
Source File: BStatsMetrics.java    From BedwarsRel with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Source File: CorrelationAnalysisEngine.java    From TomboloDigitalConnector with MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example 6
Source File: ProjectionJDBCDriverTests.java    From jdbc-cb with Apache License 2.0 6 votes vote down vote up
@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", "()*&^%$!@{}{}:\"\\\';::");
	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);
 }
 
Example 7
Source File: DateManagerServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
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;
}
 
Example 8
Source File: NameSalesResource.java    From Qora with MIT License 6 votes vote down vote up
@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();
}
 
Example 9
Source File: Protection.java    From Modern-LWC with MIT License 5 votes vote down vote up
/**
 * 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);
}
 
Example 10
Source File: ToJSONLogic.java    From EchoSim with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static JSONArray toJSONScriptTransactions(List<ScriptTransactionBean> transs)
{
    JSONArray jtranss = new JSONArray();
    for (ScriptTransactionBean trans : transs)
        jtranss.add(toJSONScriptTransaction(trans));
    return jtranss;
}
 
Example 11
Source File: Histogram.java    From streaminer with Apache License 2.0 5 votes vote down vote up
public JSONArray toJSON(DecimalFormat format) {
  JSONArray bins = new JSONArray();
  for (Bin<T> bin : getBins()) {
    bins.add(bin.toJSON(format));
  }
  return bins;
}
 
Example 12
Source File: DecorativeGeometryImplementationJS.java    From opensim-gui with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: AbstractSubscriptionServiceWebScript.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 14
Source File: JSONWriter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: SalesforceConnection.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 16
Source File: SerializableMetaStore.java    From kettle-beam with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 17
Source File: Metrics.java    From skript-yaml with MIT License 5 votes vote down vote up
@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;
}
 
Example 18
Source File: ProjectionJDBCDriverTests.java    From jdbc-cb with Apache License 2.0 4 votes vote down vote up
@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", "()*&^%$!@{}{}:\"\\\';::");
	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);
               }
           }
           
       }
 }
 
Example 19
Source File: ModelVisualizationJson.java    From opensim-gui with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 20
Source File: TranslationConverterMain.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * 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();
    }
}