Java Code Examples for org.json.JSONObject#append()

The following examples show how to use org.json.JSONObject#append() . 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: ResponseUtilsTest.java    From dcos-commons with Apache License 2.0 7 votes vote down vote up
@Test
public void testObjectFormatting() {
    JSONObject obj = new JSONObject();
    checkJsonOkResponse("{}", jsonOkResponse(obj));
    obj.put("hello", "hi");
    checkJsonOkResponse("{\"hello\": \"hi\"}", jsonOkResponse(obj));
    obj.append("hey", "hello");
    checkJsonOkResponse("{\n  \"hello\": \"hi\",\n  \"hey\": [\"hello\"]\n}", jsonOkResponse(obj));
    obj.append("hey", "hey");
    checkJsonOkResponse("{\n  \"hello\": \"hi\",\n  \"hey\": [\n    \"hello\",\n    \"hey\"\n  ]\n}",
            jsonOkResponse(obj));
}
 
Example 2
Source File: JsonFromRdf.java    From EventCoreference with Apache License 2.0 6 votes vote down vote up
static JSONObject getLabelsJSONObjectFromInstanceStatement (ArrayList<Statement> statements) throws JSONException {
    JSONObject jsonClassesObject = new JSONObject();
    ArrayList<String> coveredValues = new ArrayList<String>();
    for (int i = 0; i < statements.size(); i++) {
        Statement statement = statements.get(i);

        String predicate = statement.getPredicate().getURI();
        if (predicate.endsWith("#label")) {
            String object = "";
            if (statement.getObject().isLiteral()) {
                object = statement.getObject().asLiteral().toString();
            } else if (statement.getObject().isURIResource()) {
                object = statement.getObject().asResource().getURI();
            }
            String [] values = object.split(",");
            for (int j = 0; j < values.length; j++) {
                String value = values[j];
                if (!coveredValues.contains(value)) {
                    coveredValues.add(value);
                    jsonClassesObject.append("labels", value);
                }
            }
        }
    }
    return jsonClassesObject;
}
 
Example 3
Source File: JsonEvent.java    From EventCoreference with Apache License 2.0 6 votes vote down vote up
public static JSONObject createJsonDate (String startDate,
                                          String endDate,
                                          String headline,
                                          String text,
                                          String tag,
                                          String classname,
                                          JSONObject asset) throws JSONException {

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("startDate", startDate);
    jsonObject.put("endDate", endDate);
    jsonObject.put("headline", headline);
    jsonObject.put("text", text);
    jsonObject.put("tag", tag);
    jsonObject.put("classname", classname);
    jsonObject.append("asset", asset);
    return jsonObject;
}
 
Example 4
Source File: UniprotInstaller.java    From act with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks if the new value already exists in the field. If so, doesn't update the metadata. If it doesn't exist,
 * appends the new value to the data.
 * @param field the key referring to the array in the metadata we wish to update
 * @param value the value we wish to add to the array
 * @param data the metadata
 * @return the updated metadata JSONObject
 */
private JSONObject updateArrayField(String field, String value, JSONObject data) {
  if (value == null || value.isEmpty()) {
    return data;
  }

  if (data.has(field)) {
    JSONArray fieldData = data.getJSONArray(field);

    for (int i = 0; i < fieldData.length(); i++) {
      if (fieldData.get(i).toString().equals(value)) {
        return data;
      }
    }
  }

  return data.append(field, value);
}
 
Example 5
Source File: OneM2MApiService.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public JSONObject updateResourceNew(String resuri, String origin, String body) throws Exception {
	String host = this.GLOBALS_IP;
	String xM2MRi = "pm_12233254546";
	String xM2MOrigin = origin; 
	
	JSONObject jsonResult = new JSONObject();
	
	String targetAddr  = this.cseAddr + resuri;
	
	OneM2MHttpClient hc = new OneM2MHttpClient(targetAddr);
	
	hc.openConnection();
	hc.setRequestHeaderBase(host, xM2MRi, "", xM2MOrigin, 0);
	hc.setRequestMethod("PUT");
	hc.sendRequest(body);
	String response = hc.getResponseString();
	
	jsonResult.append("responseCode", hc.getResponseCode());
	jsonResult.append("content", response);
	
	return jsonResult;
}
 
Example 6
Source File: JsonSimpleConfigParserTest.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void parseInvalidAudienceConditions() throws Exception {
    thrown.expect(InvalidAudienceCondition.class);

    JSONArray conditions = new JSONArray();
    conditions.put("and");
    conditions.put("1");
    conditions.put("2");
    JSONObject userAttribute = new JSONObject();
    userAttribute.append("match", "exact");
    userAttribute.append("type", "custom_attribute");
    userAttribute.append("value", "string");
    userAttribute.append("name", "StringCondition");
    conditions.put(userAttribute);

    ConditionUtils.parseConditions(AudienceIdCondition.class, conditions);
}
 
Example 7
Source File: JSONObjectTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testAppendPutArray() throws JSONException {
    JSONObject object = new JSONObject();
    object.append("foo", 5);
    assertEquals("{\"foo\":[5]}", object.toString());
    object.append("foo", new JSONArray());
    assertEquals("{\"foo\":[5,[]]}", object.toString());
}
 
Example 8
Source File: JsonConfigParserTest.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void parseAudience() throws Exception {
    JSONObject jsonObject = new JSONObject();

    jsonObject.append("id", "123");
    jsonObject.append("name", "blah");
    jsonObject.append("conditions",
        "[\"and\", [\"or\", [\"or\", {\"name\": \"doubleKey\", \"type\": \"custom_attribute\", \"match\":\"lt\", \"value\":100.0}]]]");

    Condition<UserAttribute> condition = ConditionUtils.parseConditions(UserAttribute.class, new JSONArray("[\"and\", [\"or\", [\"or\", {\"name\": \"doubleKey\", \"type\": \"custom_attribute\", \"match\":\"lt\", \"value\":100.0}]]]"));

    assertNotNull(condition);
}
 
Example 9
Source File: ListFileAppendersJob.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected IStatus performJob() {
	try {
		List<FileAppender<ILoggingEvent>> appenders = logService
				.getFileAppenders();

		JSONObject appendersJSON = new JSONObject();
		appendersJSON.put(ProtocolConstants.KEY_CHILDREN, new JSONArray());
		for (FileAppender<ILoggingEvent> appender : appenders) {

			FileAppenderResource fileAppender = null;
			if (appender instanceof RollingFileAppender<?>)
				fileAppender = new RollingFileAppenderResource(appender,
						baseLocation);
			else
				fileAppender = new FileAppenderResource(appender,
						baseLocation);

			appendersJSON.append(ProtocolConstants.KEY_CHILDREN,
					fileAppender.toJSON());
		}

		return new ServerStatus(Status.OK_STATUS,
				HttpServletResponse.SC_OK, appendersJSON);

	} catch (Exception e) {
		return new ServerStatus(IStatus.ERROR,
				HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
				"An error occured when listing file appenders", e);
	}
}
 
Example 10
Source File: BuildJson1.java    From javase with MIT License 5 votes vote down vote up
public static void main(String[] args) {
try {
       JSONObject dataset = new JSONObject();
       dataset.put("genre_id", 1); 
       dataset.put("genre_parent_id", JSONObject.NULL);
       dataset.put("genre_title", "International");
       // use the accumulate function to add to an existing value. The value
       // will now be converted to a list
       dataset.accumulate("genre_title", "Pop");
       // append to the key
       dataset.append("genre_title", "slow");
       dataset.put("genre_handle", "International");
       dataset.put("genre_color", "#CC3300");
       // get the json array for a string
       System.out.println(dataset.getJSONArray("genre_title"));
       // prints ["International","Pop","slow"]
       // increment a number by 1
       dataset.increment("genre_id");
       // quote a string allowing the json to be delivered within html
       System.out.println(JSONObject.quote(dataset.toString()));
System.out.println("\n\nWrite to the file:\n\n");
System.out.println(dataset.toString());

FileWriter fw = new FileWriter(new File("myJsonObj.json"));
       fw.write(dataset.toString());
       fw.close();

       // prints
       // "{\"genre_color\":\"#CC3300\",\"genre_title\":[\"International\",\"Pop\",\"slow\"],
       // \"genre_handle\":\"International\",\"genre_parent_id\":null,\"genre_id\":2}"
} catch (JSONException jsone) {
	jsone.printStackTrace();
} catch (IOException ioe) {
	ioe.printStackTrace();
}
   }
 
Example 11
Source File: JsonFromRdf.java    From EventCoreference with Apache License 2.0 5 votes vote down vote up
static JSONObject getTopicsJSONObjectFromInstanceStatement (ArrayList<Statement> statements) throws JSONException {

        // skos:related    "air transport" , "aeronautical industry" , "transport regulations" , "air law" , "carrier" , "air safety" .
        JSONObject jsonClassesObject = new JSONObject();
        ArrayList<String> coveredValues = new ArrayList<String>();
        for (int i = 0; i < statements.size(); i++) {
            Statement statement = statements.get(i);

            String predicate = statement.getPredicate().getURI();
            // System.out.println("predicate = " + predicate);
            if ((predicate.toLowerCase().endsWith("skos/core#relatedmatch")) ||
                    (predicate.toLowerCase().endsWith("skos/core#related"))) {
                // System.out.println("predicate = " + predicate);
                String object = "";
                if (statement.getObject().isLiteral()) {
                    object = statement.getObject().asLiteral().toString();
                } else if (statement.getObject().isURIResource()) {
                    object = statement.getObject().asResource().getURI();
                }
                String [] values = object.split(",");
                for (int j = 0; j < values.length; j++) {
                    String value = values[j];
                    if (!coveredValues.contains(value)) {
                        coveredValues.add(value);
                        jsonClassesObject.append("topics", value);
                    }
                }
            }
        }
        return jsonClassesObject;
    }
 
Example 12
Source File: DrawRectanglesOnFaces.java    From pixlab with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws IOException, JSONException {
	
	HttpUrl httpUrl = new HttpUrl.Builder()
               .scheme("https")
               .host("api.pixlab.io")
               .addPathSegment("drawrectangles").build();

	JSONObject Obj1 = new JSONObject();
	Obj1.append("x", "164");
	Obj1.append("y", "95");
	Obj1.append("width", "145");
	Obj1.append("height", "145");
	
	JSONObject jObj = new JSONObject();
	jObj.append("img", img);
	jObj.append("cord", new JSONArray().put(Obj1));
	jObj.append("key", key);
	
	RequestBody body = RequestBody.create(JSON, jObj.toString());

	Request requesthttp = new Request.Builder()
               .addHeader("Content-Type","application/json")
               .url(httpUrl)
               .post(body)
               .build();
	Response response = client.newCall(requesthttp).execute();

	JSONObject jResponse = new JSONObject(response.body().string());
	if (jResponse.getInt("status") != 200) { 
		System.out.println("Error :: " + jResponse.getString("error"));
		System.exit(1);
	}else {
		System.out.println("Picture Link: "+ jResponse.getString("link"));
	}
}
 
Example 13
Source File: JsonConfigParserTest.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void parseAudienceLeaf() throws Exception {
    JSONObject jsonObject = new JSONObject();

    jsonObject.append("id", "123");
    jsonObject.append("name", "blah");
    jsonObject.append("conditions",
        "{\"name\": \"doubleKey\", \"type\": \"custom_attribute\", \"match\":\"lt\", \"value\":100.0}");

    Condition<UserAttribute> condition = ConditionUtils.parseConditions(UserAttribute.class, new JSONObject("{\"name\": \"doubleKey\", \"type\": \"custom_attribute\", \"match\":\"lt\", \"value\":100.0}"));

    assertNotNull(condition);
}
 
Example 14
Source File: JSONObjectTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testAppendExistingInvalidKey() throws JSONException {
    JSONObject object = new JSONObject();
    object.put("foo", 5);
    try {
        object.append("foo", 6);
        fail();
    } catch (JSONException expected) {
    }
}
 
Example 15
Source File: ProcedureCreatePostController.java    From JspMyAdmin2 with GNU General Public License v2.0 5 votes vote down vote up
@HandlePost
@ValidateToken
private JSONObject procedureCreate() throws JSONException, EncodingException {

	RoutineLogic routineLogic = null;
	JSONObject jsonObject = new JSONObject();
	try {
		routineLogic = new RoutineLogic();
		if (routineLogic.isExisted(bean.getName(), Constants.PROCEDURE, bean.getRequest_db())) {
			jsonObject.put(Constants.ERR, messages.getMessage(AppConstants.MSG_PROCEDURE_ALREADY_EXISTED));
		} else {
			String result = routineLogic.saveProcedure(bean);
			jsonObject.append(Constants.ERR, Constants.BLANK);
			if (result != null) {
				jsonObject.append(Constants.DATA, result);
			} else {
				JSONObject msg = new JSONObject();
				msg.put(Constants.MSG_KEY, AppConstants.MSG_PROCEDURE_SAVE_SUCCESS);
				jsonObject.append(Constants.MSG, encodeObj.encode(msg.toString()));
			}
		}
	} catch (SQLException e) {
		jsonObject.append(Constants.ERR, e.getMessage());
	} finally {
		routineLogic = null;
	}
	jsonObject.put(Constants.TOKEN, requestAdaptor.generateToken());
	return jsonObject;
}
 
Example 16
Source File: ReadFtData.java    From EventCoreference with Apache License 2.0 5 votes vote down vote up
static public ArrayList<JSONObject> convertFtDataToJsonEventArray(HashMap<String, ArrayList<DataFt>> dataFtMap) {
    ArrayList<JSONObject> ftEvents = new ArrayList<JSONObject>();
    Set keySet = dataFtMap.keySet();
    Iterator<String> keys = keySet.iterator();
    while (keys.hasNext()) {
        String dateString = keys.next();
        ArrayList<DataFt> dataFt = dataFtMap.get(dateString);
        DataFt averageFt = new DataFt(dataFt);
        String outcome = averageFt.getBrexit();
        Integer diff = averageFt.getDifferenceStayLeave();
        if (!outcome.isEmpty()) {
            JSONObject event = new JSONObject();
            try {
                JSONObject actorObject = new JSONObject();
                // actorObject.append("-", "Brexit");
                actorObject.append("-", "brexit:" + outcome);
                //actorObject.append("-", "brexit:Stay");
                //actorObject.append("-", "brexit:Leave");
                //actorObject.append("-", "brexit:Undecided");
                JSONObject mentionObject = createMentionForPoll(averageFt.source);
                event.append("mentions", mentionObject);
                event.put("actors", actorObject);
                event.put("climax", diff.toString());
                event.put("time", dateString);
                event.put("group", "100:[" + outcome + "]");
                event.put("groupName", outcome);
                event.append("prefLabel", averageFt.getLabel());
                event.append("labels", averageFt.getLabel());
                ftEvents.add(event);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    return ftEvents;
}
 
Example 17
Source File: TrigToJsonTimeLine.java    From EventCoreference with Apache License 2.0 5 votes vote down vote up
static JSONObject getMentionsJSONObjectFromInstanceStatement (ArrayList<Statement> statements) throws JSONException {
    JSONObject jsonClassesObject = new JSONObject();
    ArrayList<String> coveredValues = new ArrayList<String>();

    for (int i = 0; i < statements.size(); i++) {
        Statement statement = statements.get(i);

        String predicate = statement.getPredicate().getURI();
        if (predicate.endsWith("#denotedBy")) {
            String object = "";
            if (statement.getObject().isLiteral()) {
                object = statement.getObject().asLiteral().toString();
            } else if (statement.getObject().isURIResource()) {
                object = statement.getObject().asResource().getURI();
            }
            
            //"http://www.w3.org/1999/02/22-rdf-syntax-ns#type":"http://www.newsreader-project.eu/ontologies/framenet/Manufacturing"
            String [] values = object.split(",");
            for (int j = 0; j < values.length; j++) {
                String value = values[j];
                if (!coveredValues.contains(value)) {
                    coveredValues.add(value);
                    jsonClassesObject.append("mentions", value);
                }
            }
        }
    }
    return jsonClassesObject;
}
 
Example 18
Source File: SlackGenerationService.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
@Override
public JSONObject generateNotifyEndTagExecution(String tag, String channel) throws Exception {

    Tag mytag = tagService.convert(tagService.readByKey(tag));

    String cerberusUrl = parameterService.getParameterStringByKey("cerberus_gui_url", "", "");
    if (StringUtil.isNullOrEmpty(cerberusUrl)) {
        cerberusUrl = parameterService.getParameterStringByKey("cerberus_url", "", "");
    }
    cerberusUrl = StringUtil.addSuffixIfNotAlready(cerberusUrl, "/");
    cerberusUrl += "ReportingExecutionByTag.jsp?Tag=" + tag;

    JSONObject slackMessage = new JSONObject();
    JSONObject attachementObj = new JSONObject();

    attachementObj.put("fallback", "Execution Tag '" + tag + "' Ended. <" + cerberusUrl + "|Click here> for details.");
    attachementObj.put("pretext", "Execution Tag '" + tag + "' Ended. <" + cerberusUrl + "|Click here> for details.");
    
    JSONObject slackattaMessage = new JSONObject();
    if ("OK".equalsIgnoreCase(mytag.getCiResult())) {
        attachementObj.put("color", TestCaseExecution.CONTROLSTATUS_OK_COL);
        slackattaMessage.put("title", "Campaign successfully Executed. CI Score = " + mytag.getCiScore() + " < " + mytag.getCiScoreThreshold());
    } else {
        attachementObj.put("color", TestCaseExecution.CONTROLSTATUS_KO_COL);
        slackattaMessage.put("title", "Campaign failed. CI Score = " + mytag.getCiScore() + " >= " + mytag.getCiScoreThreshold());

    }
    slackattaMessage.put("value", mytag.getNbExeUsefull() + " Execution(s) - " + mytag.getNbOK() + " OK - " + mytag.getNbKO() + " KO - " + mytag.getNbFA() + " FA.");
    slackattaMessage.put("short", false);
    attachementObj.append("fields", slackattaMessage);

    slackMessage.append("attachments", attachementObj);

    if (!StringUtil.isNullOrEmpty(channel)) {
        slackMessage.put("channel", channel);
    }
    slackMessage.put("username", "Cerberus");

    return slackMessage;

}
 
Example 19
Source File: TrigToJsonTimeLine.java    From EventCoreference with Apache License 2.0 4 votes vote down vote up
static void getFrameNetSuperFramesJSONObjectFromInstanceStatement (JSONObject parent,
                                                                   ArrayList<Statement> statements
) throws JSONException {
    ArrayList<String> coveredValues = new ArrayList<String>();
    for (int i = 0; i < statements.size(); i++) {
        Statement statement = statements.get(i);

        String predicate = statement.getPredicate().getURI();
        if (predicate.endsWith("#type")) {
            String object = "";
            if (statement.getObject().isLiteral()) {
                object = statement.getObject().asLiteral().toString();
            } else if (statement.getObject().isURIResource()) {
                object = statement.getObject().asResource().getURI();
            }
            String [] values = object.split(",");
            for (int j = 0; j < values.length; j++) {
                String value = values[j];
                String property = getNameSpaceString(value);
                if (property.equalsIgnoreCase("fn")) {
                    value = getValue(value);
                   // System.out.println("value = " + value);
                    ArrayList<String> parents = new ArrayList<String>();

                    frameNetReader.getParentChain(value, parents, topFrames);
                    if (parents.size()==0) {
                        parent.append("fnsuperframes", value);
                    }
                    else {
                        for (int k = 0; k < parents.size(); k++) {
                            String parentFrame = parents.get(k);
                            if (!coveredValues.contains(parentFrame)) {
                                coveredValues.add(parentFrame);
                                parent.append("fnsuperframes", parentFrame);
                            }
                        }
                    }
                  //  System.out.println("value = " + value);
                  //  System.out.println("\tparents = " + parents.toString());

                   /*   String superFrame = "";
                        if (frameNetReader.subToSuperFrame.containsKey(value)) {
                        ArrayList<String> superFrames = frameNetReader.subToSuperFrame.get(value);
                        for (int k = 0; k < superFrames.size(); k++) {
                            superFrame =  superFrames.get(k);
                            if (!coveredValues.contains(superFrame)) {
                                coveredValues.add(superFrame);
                                parent.append("fnsuperframes", superFrame);
                            }

                        }
                    }*/
                }
            }
        }
    }
}
 
Example 20
Source File: ReadBuildRevisionParameters.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
private AnswerItem<JSONObject> findSVNBuildRevisionParametersBySystem(String system, String country, String environment, String build, String revision, String lastbuild, String lastrevision, ApplicationContext appContext, boolean userHasPermissions) throws JSONException {

        AnswerItem<JSONObject> item = new AnswerItem<>();
        JSONObject object = new JSONObject();
        brpService = appContext.getBean(IBuildRevisionParametersService.class);
        appService = appContext.getBean(IApplicationService.class);
        cedtService = appContext.getBean(ICountryEnvDeployTypeService.class);

        if (StringUtil.isNullOrEmpty(lastbuild)) {
            lastbuild = build;
        }

        AnswerList<BuildRevisionParameters> resp = brpService.readMaxSVNReleasePerApplication(system, build, revision, lastbuild, lastrevision);

        JSONArray jsonArray = new JSONArray();
        JSONObject newSubObj = new JSONObject();
        if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {//the service was able to perform the query, then we should get all values
            for (BuildRevisionParameters brp : (List<BuildRevisionParameters>) resp.getDataList()) {
                newSubObj = convertBuildRevisionParametersToJSONObject(brp);

                // We get here the links of all corresponding deployTypes.
                Application app;
                try {
                    app = appService.convert(appService.readByKey(brp.getApplication()));
                    for (CountryEnvDeployType JenkinsAgent : cedtService.convert(cedtService.readByVarious(system, country, environment, app.getDeploytype()))) {
                        String DeployURL = "JenkinsDeploy?application=" + brp.getApplication() + "&jenkinsagent=" + JenkinsAgent.getJenkinsAgent() + "&country=" + country + "&deploytype=" + app.getDeploytype() + "&release=" + brp.getRelease() + "&jenkinsbuildid=" + brp.getJenkinsBuildId() + "&repositoryurl=" + brp.getRepositoryUrl();
                        JSONObject newSubObjContent = new JSONObject();
                        newSubObjContent.put("jenkinsAgent", JenkinsAgent.getJenkinsAgent());
                        newSubObjContent.put("link", DeployURL);
                        newSubObj.append("install", newSubObjContent);
                    }
                } catch (CerberusException ex) {
                    LOG.warn(ex);
                }
                jsonArray.put(newSubObj);
            }
        }

        object.put("contentTable", jsonArray);
        object.put("iTotalRecords", resp.getTotalRows());
        object.put("iTotalDisplayRecords", resp.getTotalRows());
        object.put("hasPermissions", userHasPermissions);

        item.setItem(object);
        item.setResultMessage(resp.getResultMessage());
        return item;
    }