Example usage for org.json.simple JSONArray toString

List of usage examples for org.json.simple JSONArray toString

Introduction

In this page you can find the example usage for org.json.simple JSONArray toString.

Prototype

@Override
    public String toString() 

Source Link

Usage

From source file:hoot.services.controllers.ingest.CustomScriptResource.java

/**
 * <NAME>Custom Script Service Save</NAME>
 * <DESCRIPTION>Create or update user provided script into file.</DESCRIPTION>
 * <PARAMETERS>/*from   w ww  . ja  v a  2s . c  om*/
 * <SCRIPT_NAME>
 *    Name of script. If exists then it will be updated
 * </SCRIPT_NAME>
 * <SCRIPT_DESCRIPTION>
 *    Script description.
 * </SCRIPT_DESCRIPTION>
 * </PARAMETERS>
 * <OUTPUT>
 *    JSON Array containing JSON of name and description of created script
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/ingest/customscript/save?SCRIPT_NAME=MyTest&SCRIPT_DESCRIPTION=my description</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 *    // A non-standard extension to include additional js files within the same dir
 *    // sub-tree.
 *    require("example")
 *
 *    // an optional initialize function that gets called once before any
 *    // translateAttribute calls.
 *    function initialize()
 *    {
 *        // The print method simply prints the string representation to stdout
 *        //print("Initializing.")
 *    }
 *
 *    // an optional finalize function that gets called once after all
 *    // translateAttribute calls.
 *    function finalize()
 *    {
 *        // the debug method prints to stdout when --debug has been specified on
 *        // the hoot command line. (DEBUG log level)
 *        debug("Finalizing.");
 *    }
 *
 *    // A translateAttributes method that is very similar to the python translate
 *    // attributes
 *    function translateAttributes(attrs, layerName)
 *    {
 *        tags = {};
 *        //print(layerName);
 *        for (var key in attrs)
 *        {
 *            k = key.toLowerCase()
 *            //print(k + ": " + attrs[key]);
 *            tags[k] = attrs[key]
 *        }
 *        return tags;
 *    }
 * </INPUT>
 * <OUTPUT>[{"NAME":"MyTest","DESCRIPTION":"my description"}]</OUTPUT>
 * </EXAMPLE>
* @param script
* @param scriptName
* @param scriptDescription
* @return
*/
@POST
@Path("/save")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response processSave(String script, @QueryParam("SCRIPT_NAME") final String scriptName,
        @QueryParam("SCRIPT_DESCRIPTION") final String scriptDescription) {
    JSONArray saveArr = new JSONArray();
    try {
        saveArr.add(saveScript(scriptName, scriptDescription, script));
    } catch (Exception ex) {
        ResourceErrorHandler.handleError(
                "Error processing script save for: " + scriptName + " Error: " + ex.getMessage(),
                Status.INTERNAL_SERVER_ERROR, log);
    }
    return Response.ok(saveArr.toString(), MediaType.TEXT_PLAIN).build();
}

From source file:com.plancake.api.client.PlancakeApiClient.java

/**
 * @param long fromTimestamp - to return only the lists created or edited after this timestamp (GMT)
 * @param long toTimestamp - to return only the lists created or edited till this timestamp (GMT)
 * @return List<Integer> - set of list ids
 *//*from www  .jav a2 s.c  o  m*/
public ArrayList<Integer> getDeletedTags(long fromTimestamp, long toTimestamp)
        throws PlancakeApiException, UnsupportedEncodingException, NoSuchAlgorithmException, URISyntaxException,
        MalformedURLException, IOException {
    Map<String, String> params = new HashMap<String, String>();
    String methodName = "getDeletedTags";

    params.put("from_ts", Long.toString(fromTimestamp));
    params.put("to_ts", Long.toString(toTimestamp));

    JSONObject jsonResponse = this.sendRequest(params, methodName);

    JSONArray jsonArrayTagIds = (JSONArray) jsonResponse.get("tag_ids");

    JSONObject jsonTagId = null;

    PlancakeTagForApi tag;

    ArrayList<Integer> tagIds = new ArrayList<Integer>();

    String[] commaSeparatedTagIds = Utils.fromJsonArrayToStringArray(jsonArrayTagIds.toString());

    int tempItemId = 0;

    for (int i = 0; i < commaSeparatedTagIds.length; i++) {
        try {
            tempItemId = new Integer(commaSeparatedTagIds[i]);
            tagIds.add(tempItemId);
        } catch (NumberFormatException e) {
        }
    }

    return tagIds;
}

From source file:com.plancake.api.client.PlancakeApiClient.java

/**
 * @param long fromTimestamp - to return only the lists deleted after this timestamp (GMT)
 * @param long toTimestamp - to return only the lists deleted till this timestamp (GMT)
 * @return List<Integer> - set of list ids
 *///from  w  ww .  jav a  2  s  .  co m
public ArrayList<Integer> getDeletedLists(long fromTimestamp, long toTimestamp)
        throws PlancakeApiException, UnsupportedEncodingException, NoSuchAlgorithmException, URISyntaxException,
        MalformedURLException, IOException {
    Map<String, String> params = new HashMap<String, String>();
    String methodName = "getDeletedLists";

    params.put("from_ts", Long.toString(fromTimestamp));
    params.put("to_ts", Long.toString(toTimestamp));

    JSONObject jsonResponse = this.sendRequest(params, methodName);

    JSONArray jsonArrayListIds = (JSONArray) jsonResponse.get("list_ids");

    JSONObject jsonListId = null;

    PlancakeListForApi list;

    ArrayList<Integer> listIds = new ArrayList<Integer>();

    String[] commaSeparatedListIds = Utils.fromJsonArrayToStringArray(jsonArrayListIds.toString());

    int tempItemId = 0;

    for (int i = 0; i < commaSeparatedListIds.length; i++) {
        try {
            tempItemId = new Integer(commaSeparatedListIds[i]);
            listIds.add(tempItemId);
        } catch (NumberFormatException e) {
        }
    }

    return listIds;
}

From source file:hoot.services.controllers.job.ExportJobResource.java

/**
 * <NAME>Export Service Get Translation Scripts List For Export</NAME>
 * <DESCRIPTION>/*  ww  w . ja va  2 s.  c o  m*/
 *    Based on the existence of translation script extension, it will send the list of available translations script for export.
 * </DESCRIPTION>
 * <PARAMETERS>
 * </PARAMETERS>
 * <OUTPUT>
 *    List of translation script resources
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/job/export/resources</URL>
 *    <REQUEST_TYPE>GET</REQUEST_TYPE>
 *    <INPUT>
 *   </INPUT>
 * <OUTPUT>[{"description":"LTDS 4.0","name":"NFDD"},{"description":"MGCP","name":"MGCP"},{"description":"UTP","name":"UTP"}]</OUTPUT>
 * </EXAMPLE>
 * @return
 */
@GET
@Path("/resources")
@Produces(MediaType.TEXT_PLAIN)
public Response getExportResources() {
    String transExtPath = homeFolder + "/" + "/plugins-local/script/utp";
    if (translationExtPath != null && translationExtPath.length() > 0) {
        transExtPath = translationExtPath;
    }
    JSONArray srvList = new JSONArray();
    try {
        JSONObject o = new JSONObject();
        o.put("name", "TDS");
        o.put("description", "LTDS 4.0");
        srvList.add(o);

        o = new JSONObject();
        o.put("name", "MGCP");
        o.put("description", "MGCP");
        srvList.add(o);

        File f = new File(transExtPath);
        if (f.exists() && f.isDirectory()) {
            o = new JSONObject();
            o.put("name", "UTP");
            o.put("description", "UTP");
            srvList.add(o);
        }

    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error retrieving exported resource list: " + ex.toString(),
                Status.INTERNAL_SERVER_ERROR, log);
    }

    return Response.ok(srvList.toString(), MediaType.APPLICATION_JSON).build();
}

From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java

public String getCollectionValues(JsonSimple emailConfig, JsonSimple tfPackage, String varField) {
    String formattedCollectionValues = "";
    JSONArray subKeys = emailConfig.getArray("collections", varField, "subKeys");
    String tfPackageField = emailConfig.getString("", "collections", varField, "payloadKey");
    if (StringUtils.isNotBlank(tfPackageField) && subKeys instanceof JSONArray) {
        List<JsonObject> jsonList = new StorageDataUtil().getJavaList(tfPackage, tfPackageField);
        log.debug("Collating collection values for email template...");
        JSONArray fieldSeparators = emailConfig.getArray("collections", varField, "fieldSeparators");
        String recordSeparator = emailConfig.getString(IOUtils.LINE_SEPARATOR, "collections", varField,
                "recordSeparator");
        String nextDelimiter = " ";

        for (JsonObject collectionRow : jsonList) {
            if (fieldSeparators instanceof JSONArray && fieldSeparators.size() > 0) {
                // if no more delimiters, continue to use the last one specified
                Object nextFieldSeparator = fieldSeparators.remove(0);
                if (nextFieldSeparator instanceof String) {
                    nextDelimiter = (String) nextFieldSeparator;
                } else {
                    log.warn("Unable to retrieve String value from fieldSeparator: "
                            + fieldSeparators.toString());
                }// www.  j av a2 s  .  c  om
            }
            List<String> collectionValuesList = new ArrayList<String>();
            for (Object requiredKey : subKeys) {
                Object rawKeyValue = collectionRow.get(requiredKey);
                if (rawKeyValue instanceof String) {
                    String keyValue = StringUtils.trim((String) rawKeyValue);
                    if (StringUtils.isNotBlank(keyValue)) {
                        collectionValuesList.add(keyValue);
                    } else if (!isVariableNameHiddenIfEmpty) {
                        collectionValuesList.add("$" + requiredKey);
                    } else {
                        log.info("blank variable name will be hidden: " + keyValue);
                    }
                } else {
                    log.warn("No string value returned from: " + requiredKey);
                }
            }
            formattedCollectionValues += StringUtils.join(collectionValuesList, nextDelimiter)
                    + recordSeparator;
        }
        formattedCollectionValues = StringUtils.chomp(formattedCollectionValues, recordSeparator);
        log.debug("email formatted collection values: " + formattedCollectionValues);
    }
    return formattedCollectionValues;
}

From source file:au.edu.ausstage.networks.LookupManager.java

@SuppressWarnings("unchecked")
public String getCollaboration(int id1, int id2) {

    Set<Integer> evtSet_1 = new HashSet<Integer>();
    Set<Integer> evtSet_2 = new HashSet<Integer>();

    evtSet_1 = getAssociatedEvents(id1);
    evtSet_2 = getAssociatedEvents(id2);

    Event evt = null;//from  www .j a  v  a 2 s. c  om
    JSONArray evt_jsonArr = new JSONArray();
    //first_date comparator used to sort Event nodes
    EvtComparator evtComp = new EvtComparator();

    if (evtSet_1 != null && evtSet_2 != null) {
        Set<Integer> intersection = new HashSet<Integer>(evtSet_1);
        intersection.retainAll(evtSet_2);

        if (intersection != null) {
            List<Event> evtList = db.selectBatchingEventDetails(intersection);
            // Sorting Event List on the basis of Event first Date by passing Comparator
            Collections.sort(evtList, evtComp);

            if (evtList != null)
                for (int i = 0; i < evtList.size(); i++) {
                    evt = evtList.get(i);
                    evt_jsonArr.add(evt.toJSONObj(i));
                }
        }
    }

    return evt_jsonArr.toString();
}

From source file:dbProcs.Getter.java

/**
 * Use to return the current progress of a class in JSON format with information like user name, score and completed modules
 * @param applicationRoot The current running context of the application
 * @param classId The identifier of the class to use in lookup
 * @return A JSON representation of a class's progress in the application
 *///from   w  w w.  j a  v a  2 s  .  c om
@SuppressWarnings("unchecked")
public static String getProgressJSON(String applicationRoot, String classId) {
    log.debug("*** Getter.getProgressJSON ***");

    String result = new String();
    Encoder encoder = ESAPI.encoder();
    Connection conn = Database.getCoreConnection(applicationRoot);
    try {
        log.debug("Preparing userProgress call");
        //Returns User's: Name, # of Completed modules and Score
        CallableStatement callstmnt = conn.prepareCall("call userProgress(?)");
        callstmnt.setString(1, classId);
        log.debug("Executing userProgress");
        ResultSet resultSet = callstmnt.executeQuery();
        JSONArray json = new JSONArray();
        JSONObject jsonInner = new JSONObject();
        int resultAmount = 0;
        while (resultSet.next()) //For each user in a class
        {
            resultAmount++;
            jsonInner = new JSONObject();
            if (resultSet.getString(1) != null) {
                jsonInner.put("userName", new String(encoder.encodeForHTML(resultSet.getString(1)))); //User Name
                jsonInner.put("progressBar", new Integer(resultSet.getInt(2) * widthOfUnitBar)); //Progress Bar Width
                jsonInner.put("score", new Integer(resultSet.getInt(3))); //Score
                log.debug("Adding: " + jsonInner.toString());
                json.add(jsonInner);
            }
        }
        if (resultAmount > 0)
            result = json.toString();
        else
            result = new String();
    } catch (SQLException e) {
        log.error("getProgressJSON Failure: " + e.toString());
        result = null;
    } catch (Exception e) {
        log.error("getProgressJSON Unexpected Failure: " + e.toString());
        result = null;
    }
    Database.closeConnection(conn);
    log.debug("*** END getProgressJSON ***");
    return result;
}

From source file:au.edu.ausstage.networks.LookupManager.java

/**
 * A method to take a group of collaborators and output JSON encoded text
 * Unchecked warnings are suppressed due to internal issues with the org.json.simple package
 *
 * @param collaborators the list of collaborators
 * @return              the JSON encoded string
 *///from   w  w  w . j av  a  2 s  .  c  o m
@SuppressWarnings("unchecked")
private String createJSONOutput(LinkedList<Collaborator> collaborators) {

    // assume that all sorting and ordering has already been carried out
    // loop through the list of collaborators and add them to the new JSON objects
    ListIterator iterator = collaborators.listIterator(0);

    // declare helper variables
    JSONArray list = new JSONArray();
    JSONObject object = null;
    Collaborator collaborator = null;

    while (iterator.hasNext()) {

        // get the collaborator
        collaborator = (Collaborator) iterator.next();

        // start a new JSON object
        object = new JSONObject();

        // build the object
        object.put("id", collaborator.getId());
        object.put("url", collaborator.getUrl());
        object.put("givenName", collaborator.getGivenName());
        object.put("familyName", collaborator.getFamilyName());
        object.put("name", collaborator.getName());
        object.put("function", collaborator.getFunction());
        object.put("firstDate", collaborator.getFirstDate());
        object.put("lastDate", collaborator.getLastDate());
        object.put("collaborations", new Integer(collaborator.getCollaborations()));

        // add the new object to the array
        list.add(object);
    }

    // return the JSON encoded string
    return list.toString();

}

From source file:com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImplTest.java

/**
 * Test method for//from   w  w w . j  a  v  a  2 s  .c o m
 * {@link com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImpl#getQueryResponse(java.lang.String)}
 * .
 */
@Ignore
@Test
public void testGetQueryResponse() {
    logger.debug("RUNNING TEST FOR BASIC QUERY RESPONSE");
    jiraDataFactory = new JiraDataFactoryImpl(properties.getProperty("jira.credentials"),
            properties.getProperty("jira.base.url"), properties.getProperty("jira.query.endpoint"));
    jiraDataFactory.buildBasicQuery(query);
    try {
        JSONArray rs = jiraDataFactory.getQueryResponse();

        /*
         * Testing actual JSON for values
         */
        JSONArray dataMainArry = new JSONArray();
        JSONObject dataMainObj = new JSONObject();
        dataMainArry = (JSONArray) rs.get(0);
        dataMainObj = (JSONObject) dataMainArry.get(0);

        logger.info("Basic query response: " + dataMainObj.get("fields").toString());
        // fields
        assertTrue("No valid Number was found", dataMainObj.get("fields").toString().length() >= 1);
    } catch (NullPointerException npe) {
        fail("There was a problem with an object used to connect to Jira during the test\n" + npe.getMessage()
                + " caused by: " + npe.getCause());
    } catch (ArrayIndexOutOfBoundsException aioobe) {
        fail("The object returned from Jira had no JSONObjects in it during the test; try increasing the scope of your test case query and try again\n"
                + aioobe.getMessage() + " caused by: " + aioobe.getCause());
    } catch (IndexOutOfBoundsException ioobe) {
        logger.info("JSON artifact may be empty - re-running test to prove this out...");
        JSONArray rs = jiraDataFactory.getQueryResponse();

        /*
         * Testing actual JSON for values
         */
        String strRs = new String();
        strRs = rs.toString();

        logger.info("Basic query response: " + strRs);
        assertEquals("There was nothing returned from Jira that is consistent with a valid response.", "[[]]",
                strRs);
    } catch (Exception e) {
        fail("There was an unexpected problem while connecting to Jira during the test\n" + e.getMessage()
                + " caused by: " + e.getCause());
    }
}

From source file:com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImplTest.java

/**
 * Test method for/* ww w . j a  va 2s.  com*/
 * {@link com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImpl#getPagingQueryResponse()}
 * .
 */
@Ignore
@Test
public void testGetPagingQueryResponse() {
    logger.debug("RUNNING TEST FOR PAGING QUERY RESPONSE");
    jiraDataFactory = new JiraDataFactoryImpl(1, properties.getProperty("jira.credentials"),
            properties.getProperty("jira.base.url"), properties.getProperty("jira.query.endpoint"));
    jiraDataFactory.buildBasicQuery(query);
    jiraDataFactory.buildPagingQuery(0);
    try {
        JSONArray rs = jiraDataFactory.getPagingQueryResponse();

        /*
         * Testing actual JSON for values
         */
        JSONArray dataMainArry = new JSONArray();
        JSONObject dataMainObj = new JSONObject();
        dataMainArry = (JSONArray) rs.get(0);
        dataMainObj = (JSONObject) dataMainArry.get(0);

        logger.info("Paging query response: " + dataMainObj.get("fields").toString());
        // fields
        assertTrue("No valid Number was found", dataMainObj.get("fields").toString().length() >= 1);
    } catch (NullPointerException npe) {
        fail("There was a problem with an object used to connect to Jira during the test:\n" + npe.getMessage()
                + " caused by: " + npe.getCause());
    } catch (ArrayIndexOutOfBoundsException aioobe) {
        fail("The object returned from Jira had no JSONObjects in it during the test; try increasing the scope of your test case query and try again.\n"
                + aioobe.getMessage() + " caused by: " + aioobe.getCause());
    } catch (IndexOutOfBoundsException ioobe) {
        logger.info("JSON artifact may be empty - re-running test to prove this out...");

        JSONArray rs = jiraDataFactory.getPagingQueryResponse();

        /*
         * Testing actual JSON for values
         */
        String strRs = new String();
        strRs = rs.toString();

        logger.info("Paging query response: " + strRs);
        assertEquals("There was nothing returned from Jira that is consistent with a valid response.", "[[]]",
                strRs);
    } catch (Exception e) {
        fail("There was an unexpected problem while connecting to Jira during the test:\n" + e.getMessage()
                + " caused by: " + e.getCause());
    }
}