Java Code Examples for org.codehaus.jettison.json.JSONObject#toString()

The following examples show how to use org.codehaus.jettison.json.JSONObject#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 Project: ezScrum   File: LoginApi.java    License: GNU General Public License v2.0 6 votes vote down vote up
@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
public String login(String loginJson) throws JSONException {
	// get JSONObject
	JSONObject jsonEntity = new JSONObject(loginJson);
	// confirm User Account
	AccountObject account = AccountObject.confirmAccount(jsonEntity.getString(TokenEnum.USERNAME), jsonEntity.getString(TokenEnum.PASSWORD));
	
	if (account == null) {
		return "";
	}
	
	// create Token Object
	TokenObject token = new TokenObject(account.getId(), jsonEntity.getString(TokenEnum.PLATFORM_TYPE));
	token.save();
	
	// create Response JSONObject
	JSONObject respEntity = new JSONObject();
	respEntity.put(TokenEnum.PUBLIC_TOKEN, token.getPublicToken())
	          .put(TokenEnum.PRIVATE_TOKEN, token.getPrivateToken())
	          .put(TokenEnum.SERVER_TIME, System.currentTimeMillis());
	return respEntity.toString();
}
 
Example 2
Source Project: Crawer   File: AllPriceMapper.java    License: MIT License 6 votes vote down vote up
/**
 * 对象转成json字符串
 * @param mapper
 * @return
 * @throws JSONException
 */
private static String bean2Json(AllPriceMapper mapper) throws JSONException{
	
	JSONArray ja = new JSONArray();
	JSONObject jo = new JSONObject(); 
	
	jo.put(DD_NET, mapper.getDD()==null?"":mapper.getDD());
	jo.put(DB_NET, mapper.getDB()==null?"":mapper.getDB());
	jo.put(AM_NET, mapper.getAM()==null?"":mapper.getAM());
	jo.put(JD_NET, mapper.getJD()==null?"":mapper.getJD());
	jo.put(PUB_NET, mapper.getPUB()==null?"":mapper.getPUB());
	
	ja.put(jo);
	ja.put(new JSONObject());
	return jo.toString();
}
 
Example 3
/****
 * 讀取Product Backlog 所有的 story
 * 
 * @param stories
 * @return resultString
 */
public String readStoryList(ArrayList<StoryObject> stories) {
	JSONArray jsonStories = new JSONArray();
	String resultString = "";
	JSONObject result = new JSONObject();
	try {
		for (StoryObject story : stories) {
			jsonStories.put(story.toJSON());
		}
		result.put("stories", jsonStories);
		resultString = result.toString();
	} catch (JSONException e) {
		resultString = "{\"stories\":[]}";
	}
	return resultString;
}
 
Example 4
Source Project: spork   File: TezDagBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public static String convertToHistoryText(String description, Configuration conf) throws IOException {
    // Add a version if this serialization is changed
    JSONObject jsonObject = new JSONObject();
    try {
        if (description != null && !description.isEmpty()) {
            jsonObject.put("desc", description);
    }
    if (conf != null) {
        JSONObject confJson = new JSONObject();
        Iterator<Entry<String, String>> iter = conf.iterator();
        while (iter.hasNext()) {
            Entry<String, String> entry = iter.next();
            confJson.put(entry.getKey(), entry.getValue());
        }
        jsonObject.put("config", confJson);
    }
    } catch (JSONException e) {
        throw new IOException("Error when trying to convert description/conf to JSON", e);
    }
    return jsonObject.toString();
}
 
Example 5
Source Project: batfish   File: Main.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static String readQuestionTemplate(Path file, Map<String, String> templates)
    throws JSONException, IOException {
  String questionText = CommonUtil.readFile(file);
  JSONObject questionObj = new JSONObject(questionText);
  if (questionObj.has(BfConsts.PROP_INSTANCE) && !questionObj.isNull(BfConsts.PROP_INSTANCE)) {
    JSONObject instanceDataObj = questionObj.getJSONObject(BfConsts.PROP_INSTANCE);
    String instanceDataStr = instanceDataObj.toString();
    InstanceData instanceData =
        BatfishObjectMapper.mapper().readValue(instanceDataStr, InstanceData.class);
    String name = instanceData.getInstanceName();
    String key = name.toLowerCase();
    if (templates.containsKey(key) && _logger != null) {
      _logger.warnf(
          "Found duplicate template having instance name %s, only the last one in the list of templatedirs will be loaded\n",
          name);
    }

    templates.put(key, questionText);
    return name;
  } else {
    throw new BatfishException(String.format("Question in file:%s has no instance name", file));
  }
}
 
Example 6
Source Project: Crawer   File: RelationMapper.java    License: MIT License 6 votes vote down vote up
/**
 * 对象转成json字符串
 * @param mapper
 * @return
 * @throws JSONException
 */
private static String bean2Json(RelationMapper mapper) throws JSONException{
	
	JSONArray ja = new JSONArray();
	JSONObject jo = new JSONObject(); 
	
	jo.put(DD_NET, mapper.getDD()==null?"":mapper.getDD());
	jo.put(DB_NET, mapper.getDB()==null?"":mapper.getDB());
	jo.put(AM_NET, mapper.getAM()==null?"":mapper.getAM());
	jo.put(JD_NET, mapper.getJD()==null?"":mapper.getJD());
	jo.put(PUB_NET, mapper.getPUB()==null?"":mapper.getPUB());
	
	ja.put(jo);
	ja.put(new JSONObject());
	return jo.toString();
}
 
Example 7
public void produceMessages() {

        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(createConfig());

        int count = 0;
        while(count < getMessageCount()) {

            // Create the JSON object
            JSONObject obj = new JSONObject();
            try {
                obj.put("id", String.valueOf(count));
                obj.put("msg", "test-message" + 1);
                obj.put("dt", GenerateRandomDay.genRandomDay());
            } catch(JSONException e) {
                e.printStackTrace();
            }
            String payload = obj.toString();

            producer.send(new ProducerRecord<String, String>(getTopic(), payload));
            LOG.info("Sent message: {}", payload.toString());
            count++;
        }
    }
 
Example 8
Source Project: datacollector   File: HBaseStore.java    License: Apache License 2.0 6 votes vote down vote up
private String getValue(HBaseColumn hBaseColumn, Result result) {
  String value = null;
  if (result.isEmpty()) {
    return value;
  }
  if (!hBaseColumn.getCf().isPresent() || !hBaseColumn.getQualifier().isPresent()) {
    Map<String, String> columnMap = new HashMap<>();
    // parse column family, column, timestamp, and value
    for (Map.Entry<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> entry : result.getMap().entrySet()) {
      String columnFamily = Bytes.toString(entry.getKey());
      for (Map.Entry<byte[], NavigableMap<Long, byte[]>> cells : entry.getValue().entrySet()) {
        String column = Bytes.toString(cells.getKey());
        NavigableMap<Long, byte[]> cell = cells.getValue();
        Map.Entry<Long, byte[]> v = cell.lastEntry();
        String columnValue = Bytes.toString(v.getValue());
        columnMap.put(columnFamily + ":" + column, columnValue);
      }
    }
    JSONObject json = new JSONObject(columnMap);
    value = json.toString();
  } else {
    value = Bytes.toString(result.getValue(hBaseColumn.getCf().get(), hBaseColumn.getQualifier().get()));
  }
  return value;
}
 
Example 9
public static String getStoriesIdJsonStringInSprint(ArrayList<StoryObject> stories) throws JSONException {
	JSONObject storiesIdJsonString = new JSONObject();
	JSONArray storyArray = new JSONArray();
	for (StoryObject story : stories) {
		JSONObject stroyJson = new JSONObject();
		stroyJson.put("id", story.getId());
		stroyJson.put("point", story.getEstimate());
		stroyJson.put("status", story.getStatusString());
		storyArray.put(stroyJson);
	}
	storiesIdJsonString.put(SprintPlanUtil.TAG_STORIES, storyArray);
	return storiesIdJsonString.toString();
}
 
Example 10
Source Project: OSTMap   File: JsonHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Response for the webservice: A json object with two elements - "tweets" (json array with the tweets) and "topten" (json array with top ten hashtags as string)
 *
 * @param tweetsArray json array with the accumulo result tweets as string
 * @return the json object as string
 * @throws RuntimeException
 */
public static String createTweetsWithHashtagRanking(String tweetsArray) throws RuntimeException {
    JSONObject returnJsonObj = new JSONObject();
    try {

        JSONArray tweetsJsonArray = new JSONArray(tweetsArray);

        returnJsonObj.put(KEY_TWEETS, tweetsJsonArray);
        returnJsonObj.put(KEY_TOPTEN, extractTopTenHashtags(tweetsArray));

    } catch (JSONException e) {
        throw new RuntimeException("Failure during create json object with hashtag search.");
    }
    return returnJsonObj.toString();
}
 
Example 11
/***
 * 取得 story history list 的 json string
 * 
 * @param histories
 * @return String
 */
public String getStoryHistory(ArrayList<HistoryObject> histories) {
	JSONObject historyJson = new JSONObject();
	JSONArray historiesJson = new JSONArray();
	try {
		for (HistoryObject history : histories) {
			historiesJson.put(history.toJSON());
		}
		historyJson.put("histories", historiesJson);
	} catch (JSONException e) {
		return "{\"hsitories\":[]}";
	}
	return historyJson.toString();
}
 
Example 12
/***
 * 取得 taglist 的json string
 * 
 * @param tags
 * @return JSON String
 */
public String getTagList(ArrayList<TagObject> tags) {
	JSONObject tagJsonObject = new JSONObject();
	JSONArray tagListJsonArray = new JSONArray();
	try {
		for (TagObject tag : tags) {
			tagListJsonArray.put(tag.toJSON());
		}
		tagJsonObject.put("tags", tagListJsonArray);
	} catch (JSONException e) {
		return "{\"tags\": []}";
	}
	return tagJsonObject.toString();
}
 
Example 13
public static String translateSprintInfoToJson(long currentSprintId,
		double InitialPoint, double CurrentPoint, double InitialHours,
		double CurrentHours, long releaseId, String SprintGoal,
		String StoryChartUrl, String TaskChartUrl, boolean isCurrentSprint)
		throws JSONException {

	TranslateSpecialChar translateChar = new TranslateSpecialChar();
	JSONObject responseText = new JSONObject();
	responseText.put("success", true);
	responseText.put("Total", 1);
	JSONObject sprint = new JSONObject();
	sprint.put("Id", currentSprintId);
	sprint.put(
			"Name",
			"Sprint #"
					+ translateChar.TranslateJSONChar(String
							.valueOf(currentSprintId)));
	sprint.put("InitialPoint", String.valueOf(InitialPoint));
	sprint.put("CurrentPoint", String.valueOf(CurrentPoint));
	sprint.put("InitialHours", String.valueOf(InitialHours));
	sprint.put("CurrentHours", String.valueOf(CurrentHours));
	sprint.put(
			"ReleaseID",
			"Release #"
					+ translateChar.HandleNullString(Long
							.toString(releaseId)));
	sprint.put("SprintGoal", translateChar.TranslateJSONChar(SprintGoal));
	sprint.put("StoryChartUrl", StoryChartUrl);
	sprint.put("TaskChartUrl", TaskChartUrl);
	sprint.put("IsCurrentSprint", isCurrentSprint);
	responseText.put("Sprint", sprint);

	return responseText.toString();
}
 
Example 14
Source Project: incubator-atlas   File: Multiplicity.java    License: Apache License 2.0 5 votes vote down vote up
public String toJson() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("lower", lower);
    json.put("upper", upper);
    json.put("isUnique", isUnique);
    return json.toString();
}
 
Example 15
Source Project: attic-apex-malhar   File: JsonGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static String getJson()
{

  JSONObject obj = new JSONObject();
  try {
    obj.put("campaignId", 1234);
    obj.put("campaignName", "SimpleCsvFormatterExample");
    obj.put("campaignBudget", 10000.0);
    obj.put("weatherTargeting", "false");
    obj.put("securityCode", "APEX");
  } catch (JSONException e) {
    return null;
  }
  return obj.toString();
}
 
Example 16
/**
 * 轉換多個 task information 的 json string
 * 
 * @param tasks
 * @return
 * @throws JSONException
 */
public static String getTasksJsonString(ArrayList<TaskObject> tasks) throws JSONException {
	JSONObject tasksJsonString = new JSONObject();
	JSONArray taskArray = new JSONArray();
	if (tasks == null)
		return "";
	for (TaskObject task : tasks) {
		taskArray.put(task.toJSON());
	}
	tasksJsonString.put(SprintBacklogUtil.TAG_TASKS, taskArray);
	return tasksJsonString.toString();
}
 
Example 17
private String serializeHelper(Message message, ResultFormatter resultFormatter) throws JSONException
{
  MockResult result = (MockResult)message;

  JSONObject jo = new JSONObject();

  jo.put(Result.FIELD_ID, result.getId());
  jo.put(Result.FIELD_TYPE, result.getType());

  return jo.toString();
}
 
Example 18
@Test
public void testTypeDiscovery() throws Exception
{
  String[] classFilePath = OperatorDiscoveryTest.getClassFileInClasspath();
  OperatorDiscoverer od = new OperatorDiscoverer(classFilePath);
  od.buildTypeGraph();

  JSONObject Desc = od.describeClassByASM(ExtendsParameterizedOperator.class.getName());
  JSONArray json = Desc.getJSONArray("portTypeInfo");

  String debug = "\n(ASM)type info for " + ExtendsParameterizedOperator.class + ":\n" + Desc.toString(2) + "\n";

  ObjectMapper mapper = new ObjectMapper();
  //List<?> l = mapper.convertValue(json, List.class);
  JsonNode root = mapper.readTree(json.toString(2));
  String val = root.get(0).path("name").asText();
  Assert.assertEquals(debug + "port name", "inputT1", val);

  val = root.get(3).path("name").asText();
  Assert.assertEquals(debug + "port name", "outportString", val);

  val = root.get(3).path("type").asText();
  Assert.assertEquals(debug + "outportList type", "java.lang.String", val);

  val = root.get(4).path("name").asText();
  Assert.assertEquals(debug + "port name", "outportList", val);

  val = root.get(4).path("type").asText();
  Assert.assertEquals(debug + "outportList type", "java.util.List", val);

  val = root.get(4).path("typeArgs").get(0).path("type").asText();
  Assert.assertEquals(debug + "outportList type", "java.lang.Number", val);

  val = root.get(5).path("name").asText();
  Assert.assertEquals(debug + "port name", "outClassObject", val);

  val = root.get(5).path("type").asText();
  Assert.assertEquals(debug + "outportList type", "com.datatorrent.stram.webapp.TypeDiscoveryTest$B", val);

  val = root.get(5).path("typeArgs").get(0).path("type").asText();
  Assert.assertEquals(debug + "outportList type", "java.lang.Number", val);
}
 
Example 19
public static String translateStoriesToJson(ArrayList<StoryObject> stories) {
	TranslateSpecialChar translateChar = new TranslateSpecialChar();

	JSONObject responseText = new JSONObject();
	try {
		responseText.put("success", true);
		responseText.put("Total", stories.size());
		JSONArray jsonStroies = new JSONArray();
		for (int i = 0; i < stories.size(); i++) {
			JSONObject jsonStory = new JSONObject();

			jsonStory.put("Id", stories.get(i).getId());
			jsonStory.put("Type", "Story");
			jsonStory.put("Name", translateChar.TranslateJSONChar((stories.get(i).getName())));
			jsonStory.put("Value", stories.get(i).getValue());
			jsonStory.put("Estimate", stories.get(i).getEstimate());
			jsonStory.put("Importance", stories.get(i).getImportance());
			jsonStory.put("Tag", translateChar.TranslateJSONChar(Join(stories.get(i).getTags(), ",")));
			jsonStory.put("Status", stories.get(i).getStatusString());
			jsonStory.put("Notes", translateChar.TranslateJSONChar(stories.get(i).getNotes()));
			jsonStory.put("HowToDemo", translateChar.TranslateJSONChar(stories.get(i).getHowToDemo()));
			jsonStory.put("Link", "");
			jsonStory.put("Release", "");
			if (stories.get(i).getSprintId() == StoryObject.NO_PARENT) {
				jsonStory.put("Sprint", "None");
			} else {
				jsonStory.put("Sprint", stories.get(i).getSprintId());				
			}
			jsonStory.put("FilterType", getFilterType(stories.get(i)));

			if (stories.get(i).getAttachFiles().size() == 0)
				jsonStory.put("Attach", false);
			else
				jsonStory.put("Attach", true);

			ArrayList<AttachFileObject> attachFiles = stories.get(i).getAttachFiles();
			JSONArray jsonAttachFiles = new JSONArray();
			for (AttachFileObject attachFile : attachFiles) {
				JSONObject jsonAttachFile = new JSONObject();
				jsonAttachFile.put("IssueId", attachFile.getIssueId());
				jsonAttachFile.put("FileId", attachFile.getId());
				jsonAttachFile.put("FileName", translateChar.TranslateJSONChar(attachFile.getName()));

				// parse Dateformat as Gson Default DateFormat (TaskBoard
				// page)
				DateFormat dateFormat = DateFormat.getDateTimeInstance(
						DateFormat.DEFAULT, DateFormat.DEFAULT);
				Date date = new Date(attachFile.getCreateTime());
				String attachTime = dateFormat.format(date);
				ProjectObject project = ProjectObject.get(stories.get(i)
						.getId());
				jsonAttachFile.put("UploadDate", attachTime);
				jsonAttachFile.put("FilePath",
						"fileDownload.do?projectName=" + project.getName()
								+ "&fileId=" + attachFile.getId()
								+ "&fileName=" + attachFile.getName());
				jsonAttachFiles.put(jsonAttachFile);
			}
			jsonStory.put("AttachFileList", jsonAttachFiles);

			jsonStroies.put(jsonStory);
		}
		responseText.put("Stories", jsonStroies);
	} catch (JSONException e) {
		e.printStackTrace();
	}
	return responseText.toString();
}
 
Example 20
Source Project: attic-apex-malhar   File: GPOUtilsTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void validDeserializeTest() throws Exception
{
  final Map<String, Type> fieldToType = Maps.newHashMap();

  final String tboolean = "tboolean";
  final Boolean tbooleanv = true;
  final String tchar = "tchar";
  final Character tcharv = 'A';
  final String tstring = "tstring";
  final String tstringv = "hello";
  final String tfloat = "tfloat";
  final Float tfloatv = 1.0f;
  final String tdouble = "tdouble";
  final Double tdoublev = 2.0;
  final String tbyte = "tbyte";
  final Byte tbytev = 50;
  final String tshort = "tshort";
  final Short tshortv = 1000;
  final String tinteger = "tinteger";
  final Integer tintegerv = 100000;
  final String tlong = "tlong";
  final Long tlongv = 10000000000L;

  fieldToType.put(tboolean, Type.BOOLEAN);
  fieldToType.put(tchar, Type.CHAR);
  fieldToType.put(tstring, Type.STRING);
  fieldToType.put(tfloat, Type.FLOAT);
  fieldToType.put(tdouble, Type.DOUBLE);
  fieldToType.put(tbyte, Type.BYTE);
  fieldToType.put(tshort, Type.SHORT);
  fieldToType.put(tinteger, Type.INTEGER);
  fieldToType.put(tlong, Type.LONG);

  JSONObject jo = new JSONObject();
  jo.put(tboolean, tbooleanv);
  jo.put(tchar, tcharv);
  jo.put(tstring, tstringv);
  jo.put(tfloat, tfloatv);
  jo.put(tdouble, tdoublev);
  jo.put(tbyte, tbytev);
  jo.put(tshort, tshortv);
  jo.put(tinteger, tintegerv);
  jo.put(tlong, tlongv);

  String json = jo.toString(2);
  logger.debug("Input json: {}", json);

  GPOMutable gpom = GPOUtils.deserialize(new FieldsDescriptor(fieldToType), jo);

  Assert.assertEquals("Results must equal", tbooleanv, gpom.getField(tboolean));
  Assert.assertEquals("Results must equal", tcharv, gpom.getField(tchar));
  Assert.assertEquals("Results must equal", tfloatv, gpom.getField(tfloat));
  Assert.assertEquals("Results must equal", tdoublev, gpom.getField(tdouble));
  Assert.assertEquals("Results must equal", tbytev, gpom.getField(tbyte));
  Assert.assertEquals("Results must equal", tshortv, gpom.getField(tshort));
  Assert.assertEquals("Results must equal", tintegerv, gpom.getField(tinteger));
  Assert.assertEquals("Results must equal", tlongv, gpom.getField(tlong));
}