Java Examples for org.json.simple.JSONObject
The following java examples will help you to understand the usage of org.json.simple.JSONObject. These source code samples are taken from different open source projects.
Example 1
| Project: Cardinal-Plus-master File: MojangUtils.java View source code |
public static String getNameByUUID(UUID uuid) {
try {
JSONObject response = (JSONObject) new JSONParser().parse(new InputStreamReader(new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid.toString().replace("-", "")).openStream()));
return (String) response.get("name");
} catch (IOExceptionParseException | e) {
e.printStackTrace();
return null;
}
}Example 2
| Project: CardinalPGM-master File: MojangUtil.java View source code |
public static String getName(UUID uuid) {
try {
JSONObject response = (JSONObject) new JSONParser().parse(new InputStreamReader(new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid.toString().replace("-", "")).openStream()));
return (String) response.get("name");
} catch (IOExceptionParseException | e) {
return null;
}
}Example 3
| Project: jStellarAPI-master File: StellarSignerTest.java View source code |
@Test
public void testSubmitSignedTransaction() throws Exception {
StellarBinarySerializer binSer = new StellarBinarySerializer();
StellarPrivateKey privateKey = TestUtilities.getTestSeed().getPrivateKey();
StellarSigner signer = new StellarSigner(privateKey);
JSONArray allTx = (JSONArray) new JSONParser().parse(new FileReader("testdata/unittest-tx.json"));
for (Object obj : allTx) {
JSONObject jsonTx = (JSONObject) obj;
String hexTx = (String) jsonTx.get("tx");
ByteBuffer inputBytes = ByteBuffer.wrap(DatatypeConverter.parseHexBinary(hexTx));
StellarBinaryObject originalSignedRBO = binSer.readBinaryObject(inputBytes);
assertTrue("Verification failed for " + hexTx, signer.isSignatureVerified(originalSignedRBO));
StellarBinaryObject reSignedRBO = signer.sign(originalSignedRBO.getUnsignedCopy());
byte[] signedBytes = binSer.writeBinaryObject(reSignedRBO).array();
GenericJSONSerializable submitResult = new StellarDaemonWebsocketConnection(StellarDaemonWebsocketConnection.TEST_SERVER_URL).submitTransaction(signedBytes);
// assertNull(submitResult.jsonCommandResult.get("error_exception"));
assertEquals("This sequence number has already past.", submitResult.jsonCommandResult.get("engine_result_message"));
assertTrue(signer.isSignatureVerified(reSignedRBO));
}
}Example 4
| Project: justrelease-master File: NPMProjectConfig.java View source code |
@Override
public void readCurrentVersion() {
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(new InputStreamReader(projectConfigurationIS));
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
this.currentVersion = (String) jsonObject.get("version");
}Example 5
| Project: tern.java-master File: RunCommand.java View source code |
public static void main(String[] args) throws IOException {
TernDoc doc = new TernDoc();
// query
TernCompletionQuery query = new TernCompletionQuery();
query.setTypes(true);
query.setFile("#0");
query.setEnd(13);
doc.setQuery(query);
// files
String name = "myfile.js";
String text = "var a = [];a.";
doc.addFile(name, text, null);
System.out.println(doc);
JSONObject json = TernProtocolHelper.makeRequest("http://localhost:12345/", doc, false, null, null, null);
System.err.println(json);
}Example 6
| Project: deep-spark-master File: DeepCqlRecordWriterTest.java View source code |
private static List<Cells> prepareData() throws IllegalAccessException, InvocationTargetException, InstantiationException {
List<Cells> teams = new ArrayList<>(6);
String teamJson;
Cells team;
teamJson = "{\"id\":1, \"name\":\"FC Bayern München\", \"short_name\":\"FCB\", \"arena_name\":\"Allianz" + " Arena\", \"coach_name\":\"Josep Guardiola\", \"city_name\":\"München\", " + "\"league_name\":\"Bundesliga\"}";
team = CellsUtils.getCellFromJson((org.json.simple.JSONObject) JSONValue.parse(teamJson), "testTable");
teams.add(team);
teamJson = "{\"id\":2, \"name\":\"Hamburger SV\", \"short_name\":\"HSV\", \"arena_name\":\"Imtech Arena\", " + "\"coach_name\":\"Josef Zinnbauer\", \"city_name\":\"Hamburg\", \"league_name\":\"Bundesliga\"}";
team = CellsUtils.getCellFromJson((org.json.simple.JSONObject) JSONValue.parse(teamJson), "testTable");
teams.add(team);
teamJson = "{\"id\":3, \"name\":\"Herta BSC Berlin\", \"short_name\":\"Herta\", \"arena_name\":\"Olympiastaion Berlin\"," + " \"coach_name\":\"Jos Luhukay\", \"city_name\":\"Berlin\", \"league_name\":\"Bundesliga\"}";
team = CellsUtils.getCellFromJson((org.json.simple.JSONObject) JSONValue.parse(teamJson), "testTable");
teams.add(team);
teamJson = "{\"id\":4, \"name\":\"FC Basel 1893\", \"short_name\":\"FCB\", \"arena_name\":\"St. Jakob-Park\", " + "\"coach_name\":\"Paulo Sousa\", \"city_name\":\"Basel\", \"league_name\":\"Raiffeisen Super League\"}";
team = CellsUtils.getCellFromJson((org.json.simple.JSONObject) JSONValue.parse(teamJson), "testTable");
teams.add(team);
teamJson = "{\"id\":5, \"name\":\"FC Paris Saint-Germain\", \"short_name\":\"PSG\", \"arena_name\":\"Parc des Princes\"," + " \"coach_name\":\"Laurent Blanc\", \"city_name\":\"Paris\", \"league_name\":\"Ligue 1\"}";
team = CellsUtils.getCellFromJson((org.json.simple.JSONObject) JSONValue.parse(teamJson), "testTable");
teams.add(team);
teamJson = "{\"id\":6, \"name\":\"HJK Helsinki\", \"short_name\":\"HJK\", \"arena_name\":\"Sonera Stadium\", " + "\"coach_name\":\"Mika Lehkosuo\", \"city_name\":\"Helsinki\", \"league_name\":\"Veikkausliiga\"}";
team = CellsUtils.getCellFromJson((org.json.simple.JSONObject) JSONValue.parse(teamJson), "testTable");
teams.add(team);
return teams;
}Example 7
| Project: records-management-master File: FilePlanDoclistActionGroupResolver.java View source code |
/**
* Will return the action group id matching rm action group configs in rm-share-config.xml.
*
* @param jsonObject An item (i.e. document or folder) in the doclist.
* @param view Name of the type of view in which the action will be displayed. I.e. "details"
* @param isDocLib <code>true</code> if we are in the doc lib, <code>false</code> otherwise.
* @return The action group id to use for displaying actions
*/
public String resolve(JSONObject jsonObject, String view, boolean isDocLib) {
String actionGroupId = "rm-";
if (isDocLib) {
actionGroupId += "doclib-";
}
JSONObject node = (org.json.simple.JSONObject) jsonObject.get("node");
boolean isLink = (Boolean) node.get("isLink");
if (isLink) {
actionGroupId += "link-";
} else {
JSONObject rmNode = (JSONObject) node.get("rmNode");
actionGroupId += (String) rmNode.get("uiType") + "-";
}
if (view.equals("details")) {
actionGroupId += "details";
} else {
actionGroupId += "browse";
}
return actionGroupId;
}Example 8
| Project: AIDR-master File: TaskQueueServiceTest.java View source code |
//@Autowired
//TaskQueueService taskQueueService;
// @Autowired
// TaskLogService taskLogService;
@Test
public void testCreateTaskQueue() throws Exception {
//long taskQueueID = 86526;
// taskLogService.deleteAbandonedTaskLog(taskQueueID);
// taskQueueService.deleteAbandonedTaskQueue(taskQueueID);
/**
JSONParser parser = new JSONParser();
List<Long> arrayList = new ArrayList<Long>();
Object obj = parser.parse(new FileReader("/Users/jlucas/Downloads/pybossaDownload/nov9_11_02am.json"));
JSONArray objs = (JSONArray) obj;
for(int i = 0; i < objs.size(); i++){
JSONObject item = (JSONObject)objs.get(i);
Long userID = (Long) item.get("user_id");
if(arrayList.size() > 0){
if(!arrayList.contains(userID)) {
arrayList.add(userID);
}
}
else{
arrayList.add(userID);
}
System.out.println("userID;: " + arrayList.size());
}
**/
// Long clientAppID = new Long(94);
// List<TaskQueue> taskQueues = taskQueueService.getTaskQueueByClientAppStatus(clientAppID,1);
// System.out.println("taskQueues : " + taskQueues.size());
// System.out.println(taskQueueService.getCountTaskQeueByStatus("status", 1));
//System.out.println(taskQueueService.getTaskQueueByDocument(clientAppID, new Long(359250)));
/**
Long taskID = new Long(1);
Long clientAppID = new Long(1);
Long docID = new Long(1);
int status = 1;
TaskQueue taskQueue = new TaskQueue(taskID, clientAppID, docID, status);
taskQueueService.createTaskQueue(taskQueue);
TaskLog taskLog = new TaskLog(taskQueue.getTaskQueueID(), taskQueue.getStatus());
taskLogService.createTaskLog(taskLog); **/
}Example 9
| Project: chatty-master File: FrankerFaceZTest.java View source code |
@Test
public void testParseEmote() throws Exception {
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(loadJSON("FFZ_emote_regular"));
Emoticon emote = FrankerFaceZParsing.parseEmote(obj, null, null, null);
assertNotNull(emote);
assertEquals(emote.code, "joshWASTED");
assertEquals(emote.creator, "Joshimuz");
assertEquals(emote.getWidth(), 100);
assertEquals(emote.getHeight(), 16);
obj = (JSONObject) parser.parse(loadJSON("FFZ_emote_no_height"));
emote = FrankerFaceZParsing.parseEmote(obj, null, null, null);
assertNotNull(emote);
assertEquals(emote.code, "joshWASTED");
assertEquals(emote.creator, "Joshimuz");
assertEquals(emote.getWidth(), 100);
assertEquals(emote.getHeight(), -1);
testParseEmoteError("FFZ_emote_id_string");
}Example 10
| Project: CZ3003_Backend-master File: CSMSHandler.java View source code |
@Override
public void update(Observable o, Object arg) {
Socket objSocket = (Socket) arg;
int intSeq = -1;
try {
JSONParser jsonParser = new JSONParser();
JSONObject objJSON = (JSONObject) jsonParser.parse(new InputStreamReader(objSocket.getInputStream()));
int intTempSeq = Integer.parseInt(objJSON.get("id").toString());
for (CSMS objSMS : CSMSManager.loadFromJson((JSONArray) objJSON.get("sms"))) {
CSMSFactory.getSMSSender().sendSMS(objSMS);
}
intSeq = intTempSeq;
} catch (Exception ex) {
System.out.println(ex);
} finally {
try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()), StandardCharsets.US_ASCII.name())) {
objWriter.write(intSeq + "");
objWriter.flush();
} catch (IOException ex) {
System.out.println(ex);
}
}
}Example 11
| Project: FRC1778-master File: GetKeysServlet.java View source code |
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader("Access-Control-Allow-Origin", "*");
JSONObject json = SystemManager.getInstance().get();
JSONObject out = new JSONObject();
System.out.println(json + " | " + out);
for (Object key : json.keySet()) {
Object o = json.get(key);
if (o != null) {
out.put(key, o.getClass().getName());
}
}
response.getWriter().println(out.toJSONString());
}Example 12
| Project: GoldBank-master File: NameFetcher.java View source code |
public static String getUsername(UUID uuid) throws Exception {
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection();
JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
String name = (String) response.get("name");
String cause = (String) response.get("cause");
String errorMessage = (String) response.get("errorMessage");
if (cause != null && cause.length() > 0) {
throw new IllegalStateException(errorMessage);
}
return name;
}Example 13
| Project: Octobot-master File: TaskExecutor.java View source code |
@SuppressWarnings("unchecked")
public static void execute(String taskName, JSONObject message) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Method method = null;
if (taskCache.containsKey(taskName)) {
method = taskCache.get(taskName);
} else {
Class task = Class.forName(taskName);
method = task.getMethod("run", new Class[] { JSONObject.class });
taskCache.put(taskName, method);
}
method.invoke(null, new Object[] { message });
}Example 14
| Project: opensoc-streaming-master File: GrokSourcefireParser.java View source code |
@Override public JSONObject parse(byte[] raw_message) { JSONObject payload = new JSONObject(); String toParse = ""; JSONObject toReturn; try { toParse = new String(raw_message, "UTF-8"); Match gm = grok.match(toParse); gm.captures(); toReturn = new JSONObject(); toReturn.putAll(gm.toMap()); toReturn.remove("SOURCEFIRE"); String proto = toReturn.get("protocol").toString(); proto = proto.replace("{", ""); proto = proto.replace("}", ""); toReturn.put("protocol", proto); return toReturn; } catch (Exception e) { e.printStackTrace(); return null; } }
Example 15
| Project: passtools-java-master File: Location.java View source code |
public static Long create(LocationInfo locationInfo) {
try {
LocationInfo.validate(locationInfo);
String url = PassTools.API_BASE + "/location";
Map formFields = new HashMap<String, Object>();
formFields.put("json", locationInfo.toJSON());
PassToolsResponse response = post(url, formFields);
JSONObject jsonObjResponse = response.getBodyAsJSONObject();
LocationInfo createdLocationInfo = LocationInfo.fromJSON(jsonObjResponse);
if (createdLocationInfo != null) {
return createdLocationInfo.id;
} else {
throw new InternalServerException("please check response info! ");
}
} catch (RuntimeException rte) {
throw rte;
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 16
| Project: useful-java-links-master File: JsonSimpleHelloWorld.java View source code |
public static void main(String[] args) {
// convert Java to json
JSONObject root = new JSONObject();
root.put("message", "Hi");
JSONObject place = new JSONObject();
place.put("name", "World!");
root.put("place", place);
String json = root.toJSONString();
System.out.println(json);
System.out.println();
// convert json to Java
JSONObject obj = (JSONObject) JSONValue.parse(json);
String message = (String) obj.get("message");
place = (JSONObject) obj.get("place");
String name = (String) place.get("name");
System.out.println(message + " " + name);
}Example 17
| Project: Web-Karma-master File: ValueOnlyJSONReducer.java View source code |
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
JSONObject accumulatorObject = null;
try {
accumulatorObject = JSONLDUtilSimple.mergeJSONObjects(new TextToStringIterator(values.iterator()));
} catch (ParseException e) {
throw new IOException(e);
}
reusableOutputValue.set(accumulatorObject.toString());
context.write(NullWritable.get(), reusableOutputValue);
}Example 18
| Project: nodeclipse-1-master File: GeneratedToolsProtocolParser.java View source code |
@Override public org.json.simple.JSONObject asDebuggerData() throws org.chromium.sdk.internal.protocolparser.JsonProtocolParseException { org.json.simple.JSONObject result = lazyCachedField_1.get(); if (result != null) { return result; } org.json.simple.JSONObject parseResult0 = (org.json.simple.JSONObject) underlying; if (parseResult0 != null) { lazyCachedField_1.compareAndSet(null, parseResult0); org.json.simple.JSONObject cachedResult = lazyCachedField_1.get(); parseResult0 = cachedResult; } return parseResult0; }
Example 19
| Project: alfresco-enhanced-script-environment-master File: StandardToSimpleJSONObjectConverter.java View source code |
protected boolean canConvertImpl(final Object value, final ValueConverter globalDelegate, final Class<?> expectedClass, final boolean forScript) {
boolean canConvert = value instanceof JSONObject && org.json.simple.JSONObject.class.equals(expectedClass);
if (canConvert) {
final JSONObject jsonObj = (JSONObject) value;
try {
final Iterator<?> keys = jsonObj.keys();
for (Object key = keys.next(); keys.hasNext(); key = keys.next()) {
final Object subValue = jsonObj.get(String.valueOf(key));
canConvert = canConvert && (forScript ? globalDelegate.canConvertValueForScript(subValue) : globalDelegate.canConvertValueForJava(subValue));
}
} catch (final JSONException ex) {
canConvert = false;
}
}
return canConvert;
}Example 20
| Project: AP2DX-master File: HelloMessage.java View source code |
public void specializedParseMessage() {
try {
JSONObject jsonObject = new JSONObject(messageString);
setBidirection(jsonObject.getBoolean("Bidirection"));
//Boolean.parseBoolean(values.get("Bidirection").toString()));
} catch (Exception e) {
System.out.println("Error in AP2DX.specializedMessages.HelloMessage.specializedParseMessage()... things went south!");
System.out.println("e.getMessage(): " + e.getMessage());
e.printStackTrace();
}
}Example 21
| Project: ASSISTmentsDirect-master File: UserNameTaken.java View source code |
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String email = req.getParameter("email");
ExternalUserDAO userDAO = new ExternalUserDAO(LiteUtility.PARTNER_REF);
JSONObject json = new JSONObject();
if (userDAO.isUserExist(email)) {
ExternalUser user = userDAO.findByPartnerExternalRef(email);
if (user.getPartnerAccessToken() != null && !user.getPartnerAccessToken().equals("")) {
json.put("result", "true");
} else {
json.put("result", "false");
}
} else {
json.put("result", "false");
}
PrintWriter pw = resp.getWriter();
pw.write(json.toJSONString());
pw.flush();
pw.close();
}Example 22
| Project: Dragonet-master File: ChatMessageTranslator.java View source code |
@Override
public PEPacket[] handleSpecific(ChatMessage packet) {
String msg = "";
try {
//String msg = ((ChatMessage) message).text.asPlaintext();
Object json = new JSONParser().parse(packet.text.encode());
if (json instanceof JSONObject) {
msg = this.getTranslator().translateChatMessage((JSONObject) json);
} else {
msg = packet.text.asPlaintext();
}
} catch (ParseException ex) {
return null;
}
//if(json)
ChatPacket pkMessage = new ChatPacket();
pkMessage.source = "";
pkMessage.type = ChatPacket.TextType.RAW;
pkMessage.message = msg;
return new PEPacket[] { pkMessage };
}Example 23
| Project: Exceptional4j-master File: SanitizingTest.java View source code |
@Test
public void testSanitizing() {
final ExceptionalAppender appender = new ExceptionalAppender("fake_key", false);
appender.addSanitizer(new IPv4Sanitizer());
appender.addSanitizer(new RegexSanitizer("bob", "bubba"));
final String fqnOfCategoryClass = getClass().getName();
final Category logger = Logger.getLogger(getClass());
final Priority level = Level.ERROR;
final Object message = "Message containing an ip of 192.168.0.1 and an ip of 10.65.1.1 with bob";
final Object expectedSanitizedMessage = "Message containing an ip of ???.???.???.??? and an ip of ???.???.???.??? with bubba";
final Throwable throwable = new IOException();
final LoggingEvent le = new LoggingEvent(fqnOfCategoryClass, logger, level, message, throwable);
JSONObject exceptionData = appender.exceptionData(le);
String sanitizedMessage = (String) exceptionData.get("message");
assertEquals(expectedSanitizedMessage, sanitizedMessage);
}Example 24
| Project: FallUML2013-master File: Refresh.java View source code |
@SuppressWarnings("unchecked")
@Override
public JSONObject request(JSONObject jsonObj, XmiClassDiagramComparer comparer) {
// Implements the refresh JSON structure
JSONObject response = new JSONObject();
ArrayList<String> diagram1 = new ArrayList<String>();
ArrayList<String> diagram2 = new ArrayList<String>();
ArrayList<String> same = new ArrayList<String>();
ArrayList<String> similar = new ArrayList<String>();
// Read elements in uniqueClass1
for (XmiClassElement element : comparer.getUniqueClass1()) {
diagram1.add(element.getName());
}
// Read elements in uniqueClass2
for (XmiClassElement element : comparer.getUniqueClass2()) {
diagram2.add(element.getName());
}
// Read elements in sameClass
for (XmiMergedClass element : comparer.getSameClass()) {
same.add(element.getNewName());
}
// Run SimilarityCheck to find similar class names
for (String d1 : diagram1) {
for (String d2 : diagram2) {
SimilarityCheck simCheck = new SimilarityCheck(d1, d2);
if (simCheck.doSimilarityCheck()) {
similar.add(d1 + " is similar to " + d2);
}
}
}
// Input three ArrayLists in our return obj
response.put(TITLE_RESPONSE, "Success");
response.put(TITLE_DIAGRAM1, diagram1);
response.put(TITLE_DIAGRAM2, diagram2);
response.put(TITLE_SAME, same);
response.put(TITLE_SIMILAR, similar);
return response;
}Example 25
| Project: gscrot-imgur-master File: ImgurUploader.java View source code |
@Override
public UploadResponse process(Capture capture) throws Exception {
String response = Imgur.upload(capture.getBinary());
JSONObject jo = (JSONObject) JSONValue.parse(response);
if (!jo.get("success").toString().equalsIgnoreCase("true")) {
throw new Exception(jo.get("status").toString());
}
JSONObject data = (JSONObject) jo.get("data");
Object link = data.get("link");
Object delhash = data.get("deletehash");
if (link != null && delhash != null) {
String rmlink = "https://imgur.com/delete/" + delhash;
UploadResponse ur = new UploadResponse(link.toString().replace("http://", "https://"), rmlink);
ur.setRaw(response);
return ur;
} else {
throw new Exception("Error: " + response);
}
}Example 26
| Project: gscrot-minfil-master File: MinfilUploader.java View source code |
@Override
public UploadResponse process(Capture capture) throws Exception {
String response = Minfil.upload(capture.getBinary(), capture.getFormat());
JSONObject jo = (JSONObject) JSONValue.parse(response);
if (!jo.get("status").toString().equalsIgnoreCase("true")) {
throw new Exception(jo.get("status").toString());
}
JSONObject file = (JSONObject) jo.get("file");
JSONObject url = (JSONObject) file.get("url");
Object link = url.get("full");
if (link != null) {
UploadResponse ur = new UploadResponse(link.toString(), null);
ur.setRaw(response);
return ur;
} else {
throw new Exception("Error: " + response);
}
}Example 27
| Project: intellij-thesaurus-master File: MashapeDownloader.java View source code |
@Override
protected List<String> parseRawJsonToSynonymsList(String rawJson) {
List<String> synonyms = new ArrayList<String>();
JSONObject fullJSON = (JSONObject) JSONValue.parse(rawJson);
JSONArray arr = (JSONArray) fullJSON.get("terms");
for (int i = 0; i < arr.toArray().length; i++) {
JSONObject term = (JSONObject) arr.get(i);
synonyms.add(term.get("term").toString());
}
return synonyms;
}Example 28
| Project: jat-master File: JSONFileOutputReader.java View source code |
@Override
public List<JATETerm> read(String file) throws IOException {
// JSONObject jo=gson.fromJson(file, JSONObject.class);
Type listType = new TypeToken<ArrayList<JATETerm>>() {
}.getType();
List<JATETerm> terms = gson.fromJson(new InputStreamReader(new FileInputStream(file), "UTF8"), listType);
Collections.sort(terms);
return terms;
}Example 29
| Project: jReddit-master File: MoreTest.java View source code |
@SuppressWarnings("unchecked")
@Test
public void testConstructor() {
// Variables
long count = 2894;
String parent_id = "djk9fa";
String child_id_1 = "ddafe2";
String child_id_2 = "ddaf22";
// Create JSON Object
JSONObject data = new JSONObject();
data.put("count", count);
data.put("parent_id", parent_id);
JSONArray array = new JSONArray();
array.add(child_id_1);
array.add(child_id_2);
data.put("children", array);
// Parse
More m = new More(data);
Assert.assertEquals((Long) count, m.getCount());
Assert.assertEquals(parent_id, m.getParentId());
Assert.assertEquals(2, m.getChildrenSize());
Assert.assertEquals(child_id_1, m.getChildren().get(0));
Assert.assertEquals(child_id_2, m.getChildren().get(1));
// Test that the toString does not throw an exception an is not null
Assert.assertNotNull(m.toString());
}Example 30
| Project: many-ql-master File: DoneButtonListener.java View source code |
@Override
public void actionPerformed(ActionEvent e) {
JSONObject json = new JSONObject();
for (Identifier key : evaluator.getMap().keySet()) {
Value value = evaluator.getValue(key);
json.put(key.toString(), value.toString());
}
try {
PrintWriter writer;
writer = new PrintWriter("form.json");
writer.println(json.toJSONString());
writer.close();
System.out.println("Made JSON file in the root of the project folder.w");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
System.out.println("Couldn't make JSON File.");
}
System.out.println(json);
}Example 31
| Project: mc-servermagic-master File: Config.java View source code |
// shush.
@SuppressWarnings("unchecked")
public static void createJSONObjects() throws IOException {
File json_file = new File(Reference.home_folder + File.separator + "config.json");
if (!json_file.exists()) {
json_file.getParentFile().mkdirs();
json_file.createNewFile();
JSONObject head = new JSONObject();
JSONObject global = new JSONObject();
JSONArray servers = new JSONArray();
JSONObject server = new JSONObject();
server.put("name", "MyServer");
server.put("minecraft", "1.8");
servers.add(server);
global.put("arguments", "nogui");
head.put("global", global);
head.put("servers", servers);
FileWriter writer = new FileWriter(json_file);
head.writeJSONString(writer);
writer.close();
}
try {
FileReader reader = new FileReader(json_file);
JSONParser jsonParser = new JSONParser();
Config.json = (JSONObject) jsonParser.parse(reader);
Config.servers = (JSONArray) Config.json.get("servers");
Config.global = (JSONObject) Config.json.get("global");
if (Config.servers.get(0) == null) {
Logger.log("At least one server must be in your config.json file to continue.");
System.exit(1);
}
} catch (IOExceptionParseException | e) {
e.printStackTrace();
}
}Example 32
| Project: MultiverseKing_JME-master File: JSONLoader.java View source code |
/**
* Load the file using the binary importer.
*
* @param assetInfo
* @return
* @throws IOException
*/
@Override
public Object load(AssetInfo assetInfo) throws IOException {
InputStream is = assetInfo.openStream();
JSONObject data = null;
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
bufferedReader = new BufferedReader(new InputStreamReader(is));
String s;
while ((s = bufferedReader.readLine()) != null) {
stringBuilder.append(s);
}
data = (JSONObject) parser.parse(stringBuilder.toString());
} catch (ParseException ex) {
Logger.getLogger(JSONLoader.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
Logger.getLogger(JSONLoader.class.getName()).log(Level.SEVERE, null, ex);
}
}
is.close();
}
if (data != null) {
return data;
} else {
Logger.getGlobal().log(Level.WARNING, "{0} : Data couldn't be loaded.", new Object[] { getClass().getName() });
return null;
}
}Example 33
| Project: nxt-master File: GetOffer.java View source code |
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws ParameterException {
JSONObject response = new JSONObject();
CurrencyBuyOffer buyOffer = ParameterParser.getBuyOffer(req);
CurrencySellOffer sellOffer = ParameterParser.getSellOffer(req);
response.put("buyOffer", JSONData.offer(buyOffer));
response.put("sellOffer", JSONData.offer(sellOffer));
return response;
}Example 34
| Project: oicsns-master File: PosUpdate.java View source code |
@Override public void ActionEvent(JSONObject json, WebSocketListener webSocket) { JSONObject responseJSON = new JSONObject(); responseJSON.put("method", "posupdate"); responseJSON.put("status", 0); if (validate(json)) { MapFactory mapFactory = MapFactory.getInstance(); OicMap map = mapFactory.getMap(Integer.parseInt(json.get("mapid").toString())); map.BroadCastMap(responseJSON); } else { OicCharacter c = webSocket.getCharacter(); c.getMap().BroadCastMap(responseJSON); } }
Example 35
| Project: ossus-client-old-master File: Version.java View source code |
static Version buildFromJson(JSONObject json, Machine machine) {
try {
String id = ((Long) json.get("id")).toString();
String name = (String) json.get("name");
String updater_link = (String) json.get("updater_link");
String agent_link = (String) json.get("agent_link");
return new Version(id, name, updater_link, agent_link);
} catch (NullPointerException e) {
machine.log_error("Error getting info about the Client version");
}
return null;
}Example 36
| Project: PATRIC-master File: TestPRIDEInterface.java View source code |
public void testGetResult() {
if (testmode == true) {
PRIDEInterface i = new PRIDEInterface();
JSONObject result = null;
try {
result = i.getResults("Salmonella typhimurium");
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(result.toString());
}
}Example 37
| Project: Qora-master File: PeersResource.java View source code |
@SuppressWarnings("unchecked")
@GET
@Path("height")
public String getTest() {
Map<Peer, Integer> peers = Controller.getInstance().getPeerHeights();
JSONArray array = new JSONArray();
for (Map.Entry<Peer, Integer> peer : peers.entrySet()) {
JSONObject o = new JSONObject();
o.put("peer", peer.getKey().getAddress().getHostAddress());
o.put("height", peer.getValue());
array.add(o);
}
return array.toJSONString();
}Example 38
| Project: Raigad-master File: TestElasticsearchUtils.java View source code |
@Test
public void TestInstanceToJson() {
System.out.println("Starting a test...");
List<RaigadInstance> instances = getRaigadInstances();
JSONObject jsonInstances = ElasticsearchUtils.transformRaigadInstanceToJson(instances);
System.out.println(jsonInstances);
List<RaigadInstance> returnedInstances = ElasticsearchUtils.getRaigadInstancesFromJson(jsonInstances);
System.out.println("Number of returned instances = " + returnedInstances.size());
for (RaigadInstance raigadInstance : returnedInstances) {
System.out.println("-->" + raigadInstance);
}
}Example 39
| Project: storm-applications-master File: JsonParser.java View source code |
@Override
public List<StreamValues> parse(String input) {
input = input.trim();
if (input.isEmpty() || (!input.startsWith("{") && !input.startsWith("[")))
return null;
try {
JSONObject json = (JSONObject) jsonParser.parse(input);
return ImmutableList.of(new StreamValues(json));
} catch (ParseException e) {
LOG.error(String.format("Error parsing JSON object: %s", input), e);
}
return null;
}Example 40
| Project: strata2012-master File: HashTagSplitter.java View source code |
@Override
public void execute(TridentTuple tuple, TridentCollector collector) {
String json = (String) tuple.getValueByField("tweet");
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(json);
if (jsonObject.containsKey("entities")) {
JSONObject entities = (JSONObject) jsonObject.get("entities");
if (entities.containsKey("hashtags")) {
for (Object obj : (JSONArray) entities.get("hashtags")) {
JSONObject hashObj = (JSONObject) obj;
collector.emit(new Values(hashObj.get("text").toString().toLowerCase()));
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}Example 41
| Project: trait_workflow_runner-master File: JsonUtilitiesTest.java View source code |
/**
* Test the getJsonString method.
*/
@Test
public void testGetJsonString() {
final String key = "name";
final String value = "Concatenate datasets";
final JSONObject jsonObject = new JSONObject(ImmutableMap.of(key, value));
assertEquals(value, JsonUtilities.getJsonString(jsonObject, key));
assertNull(JsonUtilities.getJsonString(jsonObject, "unknown-key"));
}Example 42
| Project: Zephyrus-II-master File: ItemSerializer.java View source code |
@SuppressWarnings("deprecation")
public static ItemStack fromString(String item) {
JSONObject obj;
try {
obj = (JSONObject) new JSONParser().parse(item);
} catch (ParseException e) {
System.out.println("Error loading itemstack " + item);
return null;
}
int id = ((Long) obj.get("id")).intValue();
short data = ((Long) obj.get("data")).shortValue();
int amount = ((Long) obj.get("amount")).intValue();
return new ItemStack(id, amount, (short) data);
}Example 43
| Project: epicsarchiverap-master File: NamedFlagsSet.java View source code |
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp, ConfigService configService) throws IOException {
String name = req.getParameter("name");
if (name == null || name.equals("")) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
String value = req.getParameter("value");
if (value == null || value.equals("")) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
resp.setContentType(MimeTypeConstants.APPLICATION_JSON);
try (PrintWriter out = resp.getWriter()) {
configService.setNamedFlag(name, Boolean.parseBoolean(value));
HashMap<String, String> ret = new HashMap<String, String>();
ret.put("status", "ok");
out.println(JSONObject.toJSONString(ret));
} catch (Exception ex) {
logger.error("Exception getting named value for name " + name, ex);
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}Example 44
| Project: json-simple-master File: JSONValue.java View source code |
/**
* Encode an object into JSON text and write it to out.
* <p>
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
* <p>
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
* "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
*
* @see org.json.simple.JSONObject#writeJSONString(Map, Writer)
* @see org.json.simple.JSONArray#writeJSONString(List, Writer)
*
* @param value
* @param writer
*/
public static void writeJSONString(Object value, Writer out) throws IOException {
if (value == null) {
out.write("null");
return;
}
if (value instanceof String) {
out.write('\"');
out.write(escape((String) value));
out.write('\"');
return;
}
if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Number) {
out.write(value.toString());
return;
}
if (value instanceof Boolean) {
out.write(value.toString());
return;
}
if ((value instanceof JSONStreamAware)) {
((JSONStreamAware) value).writeJSONString(out);
return;
}
if ((value instanceof JSONAware)) {
out.write(((JSONAware) value).toJSONString());
return;
}
if (value instanceof Map) {
JSONObject.writeJSONString((Map) value, out);
return;
}
if (value instanceof Collection) {
JSONArray.writeJSONString((Collection) value, out);
return;
}
if (value instanceof byte[]) {
JSONArray.writeJSONString((byte[]) value, out);
return;
}
if (value instanceof short[]) {
JSONArray.writeJSONString((short[]) value, out);
return;
}
if (value instanceof int[]) {
JSONArray.writeJSONString((int[]) value, out);
return;
}
if (value instanceof long[]) {
JSONArray.writeJSONString((long[]) value, out);
return;
}
if (value instanceof float[]) {
JSONArray.writeJSONString((float[]) value, out);
return;
}
if (value instanceof double[]) {
JSONArray.writeJSONString((double[]) value, out);
return;
}
if (value instanceof boolean[]) {
JSONArray.writeJSONString((boolean[]) value, out);
return;
}
if (value instanceof char[]) {
JSONArray.writeJSONString((char[]) value, out);
return;
}
if (value instanceof Object[]) {
JSONArray.writeJSONString((Object[]) value, out);
return;
}
out.write(value.toString());
}Example 45
| Project: oozie-master File: V1AdminServlet.java View source code |
/**
* Get a json array of queue dump and a json array of unique map dump
*
* @param JSONObject the result json object that contains a JSONArray for the callable dump
*
* @see
* org.apache.oozie.servlet.BaseAdminServlet#getQueueDump(org.json.simple
* .JSONObject)
*/
@SuppressWarnings("unchecked")
@Override
protected void getQueueDump(JSONObject json) throws XServletException {
List<String> queueDumpList = Services.get().get(CallableQueueService.class).getQueueDump();
JSONArray queueDumpArray = new JSONArray();
for (String str : queueDumpList) {
JSONObject jObject = new JSONObject();
jObject.put(JsonTags.CALLABLE_DUMP, str);
queueDumpArray.add(jObject);
}
json.put(JsonTags.QUEUE_DUMP, queueDumpArray);
List<String> uniqueDumpList = Services.get().get(CallableQueueService.class).getUniqueDump();
JSONArray uniqueDumpArray = new JSONArray();
for (String str : uniqueDumpList) {
JSONObject jObject = new JSONObject();
jObject.put(JsonTags.UNIQUE_ENTRY_DUMP, str);
uniqueDumpArray.add(jObject);
}
json.put(JsonTags.UNIQUE_MAP_DUMP, uniqueDumpArray);
}Example 46
| Project: prjvmac-master File: V1AdminServlet.java View source code |
/**
* Get a json array of queue dump and a json array of unique map dump
*
* @param JSONObject the result json object that contains a JSONArray for the callable dump
*
* @see
* org.apache.oozie.servlet.BaseAdminServlet#getQueueDump(org.json.simple
* .JSONObject)
*/
@SuppressWarnings("unchecked")
@Override
protected void getQueueDump(JSONObject json) throws XServletException {
List<String> queueDumpList = Services.get().get(CallableQueueService.class).getQueueDump();
JSONArray queueDumpArray = new JSONArray();
for (String str : queueDumpList) {
JSONObject jObject = new JSONObject();
jObject.put(JsonTags.CALLABLE_DUMP, str);
queueDumpArray.add(jObject);
}
json.put(JsonTags.QUEUE_DUMP, queueDumpArray);
List<String> uniqueDumpList = Services.get().get(CallableQueueService.class).getUniqueDump();
JSONArray uniqueDumpArray = new JSONArray();
for (String str : uniqueDumpList) {
JSONObject jObject = new JSONObject();
jObject.put(JsonTags.UNIQUE_ENTRY_DUMP, str);
uniqueDumpArray.add(jObject);
}
json.put(JsonTags.UNIQUE_MAP_DUMP, uniqueDumpArray);
}Example 47
| Project: angus-sdk-java-master File: GenericService.java View source code |
public Service getService(int version) throws IOException {
Map<String, String> filters = new HashMap<String, String>();
filters.put("version", Integer.toString(version));
JSONObject result = this.list(filters);
JSONObject versions = ((JSONObject) result.get("versions"));
JSONObject description;
if (version < 0) {
List<String> toSort = new ArrayList<String>(versions.keySet());
java.util.Collections.sort(toSort);
version = Integer.parseInt(toSort.get(toSort.size() - 1));
}
description = (JSONObject) versions.get(Integer.toString(version));
return this.conf.getFactoryRepository().getServiceFactory().create(this.endpoint, (String) description.get("url"), conf);
}Example 48
| Project: ambari-master File: ServiceFormattedException.java View source code |
protected static Response errorEntity(String message, Throwable e) {
HashMap<String, Object> response = new HashMap<String, Object>();
response.put("message", message);
String trace = null;
if (e != null) {
trace = ExceptionUtils.getStackTrace(e);
}
response.put("trace", trace);
response.put("status", STATUS);
return Response.status(STATUS).entity(new JSONObject(response)).type(MediaType.APPLICATION_JSON).build();
}Example 49
| Project: android-sync-master File: JSONValue.java View source code |
/**
* Encode an object into JSON text and write it to out.
* <p>
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
* <p>
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
* "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
*
* @see org.json.simple.JSONObject#writeJSONString(Map, Writer)
* @see org.json.simple.JSONArray#writeJSONString(List, Writer)
*
* @param value
* @param writer
*/
public static void writeJSONString(Object value, Writer out) throws IOException {
if (value == null) {
out.write("null");
return;
}
if (value instanceof String) {
out.write('\"');
out.write(escape((String) value));
out.write('\"');
return;
}
if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Number) {
out.write(value.toString());
return;
}
if (value instanceof Boolean) {
out.write(value.toString());
return;
}
if ((value instanceof JSONStreamAware)) {
((JSONStreamAware) value).writeJSONString(out);
return;
}
if ((value instanceof JSONAware)) {
out.write(((JSONAware) value).toJSONString());
return;
}
if (value instanceof Map) {
JSONObject.writeJSONString((Map) value, out);
return;
}
if (value instanceof List) {
JSONArray.writeJSONString((List) value, out);
return;
}
out.write(value.toString());
}Example 50
| Project: ankush-master File: CallableRestJsonData.java View source code |
@Override public JSONObject call() throws Exception { JSONObject json = null; AnkushRestClient restClient = new AnkushRestClient(); String data = restClient.getRequest(this.url); if (data == null) { throw new AnkushException("Could not fetch data from " + url); } else { json = (JSONObject) new JSONParser().parse(data); } return json; }
Example 51
| Project: ArretadoGames-master File: JSONGenerator.java View source code |
public JSONObject generateJson() { HashMap<String, JSONArray> hm = new HashMap<String, JSONArray>(); JSONArray jArrayEntities = new JSONArray(); for (int i = 0; i < entities.size(); i++) { jArrayEntities.add(entities.get(i).toJSON()); } jArrayEntities.add(flag.toJSON()); float yOffset = Utils.convertPixelToMeter(totalHeight - groundHeight); for (int i = 0; i < jArrayEntities.size(); i++) { // Update Y based on ground float previousY = (Float) ((JSONObject) jArrayEntities.get(i)).get("y"); ((JSONObject) jArrayEntities.get(i)).put("y", yOffset - previousY); } hm.put("entities", jArrayEntities); JSONObject object = new JSONObject(hm); object.put("height", totalHeight); object.put("width", totalWidth); return object; }
Example 52
| Project: Assignments-master File: Helper.java View source code |
@SuppressWarnings("unchecked")
public void saveInJSONFile(Map<String, List<String>> dictionaryData) {
JSONObject obj = new JSONObject();
for (Map.Entry<String, List<String>> entry : dictionaryData.entrySet()) {
obj.put(entry.getKey(), entry.getValue());
}
try {
File file = new File("dictionary.json");
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(obj.toString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}Example 53
| Project: bbs.newgxu.cn-master File: JSONParseTest.java View source code |
@Test
@Ignore
public void testResloveJson() throws ParseException {
String json = RemoteContent.getRemoteResult("http://localhost:8080/resources/t.json", "utf8");
System.out.println(json);
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(json);
for (int i = 0; i < a.size(); i++) {
JSONObject o = (JSONObject) a.get(i);
L.info("tid:{}, title:{}, author:{}, uid:{}, ctime:{}, clickTimes{}", o.get("tid"), o.get("title"), o.get("author"), o.get("uid"), o.get("ctime"), o.get("clickTimes"));
}
}Example 54
| Project: bFundamentals-master File: GuiHandler.java View source code |
public static void loadGui(Module plugin) throws Exception {
File file = new File(plugin.getDataFolder(), "gui.json");
if (!file.exists()) {
throw new Exception("Could not find gui file");
}
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(new FileReader(new File(plugin.getDataFolder(), "gui.json")));
Gui gui = new Gui(json);
plugin.getLogger().info("Loaded gui '" + gui.getName() + "'");
GuiHandler.gui = gui;
}Example 55
| Project: blueflood-master File: BatchedMetricsJSONOutputSerializer.java View source code |
@Override public JSONObject transformRollupData(Map<Locator, MetricData> metricData, Set<MetricStat> filterStats) throws SerializationException { final JSONObject globalJSON = new JSONObject(); final JSONArray metricsArray = new JSONArray(); for (Map.Entry<Locator, MetricData> one : metricData.entrySet()) { final JSONObject singleMetricJSON = new JSONObject(); singleMetricJSON.put("metric", one.getKey().getMetricName()); singleMetricJSON.put("unit", one.getValue().getUnit() == null ? Util.UNKNOWN : one.getValue().getUnit()); singleMetricJSON.put("type", one.getValue().getType()); Set<MetricStat> oneFilterStats = fixFilterStats(one.getValue(), filterStats); JSONArray values = transformDataToJSONArray(one.getValue(), oneFilterStats); singleMetricJSON.put("data", values); metricsArray.add(singleMetricJSON); } globalJSON.put("metrics", metricsArray); return globalJSON; }
Example 56
| Project: cassandra-rest-master File: MarshallingTest.java View source code |
@Test
public void testSlice() throws Exception {
Column column1 = new Column(ByteBufferUtil.bytes("ADDR1"));
column1.setValue(ByteBufferUtil.bytes("1234 Fun St."));
column1.setTimestamp(System.currentTimeMillis() * 1000);
ColumnOrSuperColumn col1 = new ColumnOrSuperColumn();
col1.setColumn(column1);
Column column2 = new Column(ByteBufferUtil.bytes("CITY"));
column2.setValue(ByteBufferUtil.bytes("Souderton."));
column2.setTimestamp(System.currentTimeMillis() * 1000);
ColumnOrSuperColumn col2 = new ColumnOrSuperColumn();
col2.setColumn(column2);
List<ColumnOrSuperColumn> slice = new ArrayList<ColumnOrSuperColumn>();
slice.add(col1);
slice.add(col2);
JSONObject json = JsonMarshaller.marshallSlice(slice);
assertEquals(JSON.parse("{\"ADDR1\":\"1234 Fun St.\",\"CITY\":\"Souderton.\"}"), json);
}Example 57
| Project: CC-android-master File: JSONValue.java View source code |
/**
* Encode an object into JSON text and write it to out.
* <p>
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
* <p>
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
* "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
*
* @see org.json.simple.JSONObject#writeJSONString(Map, Writer)
* @see org.json.simple.JSONArray#writeJSONString(List, Writer)
*
* @param value
* @param writer
*/
public static void writeJSONString(Object value, Writer out) throws IOException {
if (value == null) {
out.write("null");
return;
}
if (value instanceof String) {
out.write('\"');
out.write(escape((String) value));
out.write('\"');
return;
}
if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Number) {
out.write(value.toString());
return;
}
if (value instanceof Boolean) {
out.write(value.toString());
return;
}
if ((value instanceof JSONStreamAware)) {
((JSONStreamAware) value).writeJSONString(out);
return;
}
if ((value instanceof JSONAware)) {
out.write(((JSONAware) value).toJSONString());
return;
}
if (value instanceof Map) {
JSONObject.writeJSONString((Map) value, out);
return;
}
if (value instanceof List) {
JSONArray.writeJSONString((List) value, out);
return;
}
out.write(value.toString());
}Example 58
| Project: chukwa-master File: PbsNodePlugin.java View source code |
public static void main(String[] args) {
IPlugin plugin = new PbsNodePlugin();
JSONObject result = plugin.execute();
System.out.print("Result: " + result);
if ((Integer) result.get("status") < 0) {
System.out.println("Error");
log.warn("[ChukwaError]:" + PbsNodePlugin.class + ", " + result.get("stderr"));
} else {
log.info(result.get("stdout"));
}
}Example 59
| Project: Cloud-Stenography-master File: EditSession.java View source code |
public List<JSONObject> getEditsSinceLastSave() { if (edits == null) return new ArrayList<JSONObject>(0); if (lastEditBeforeSave > edits.size() - 1) throw new IllegalStateException("lastEditBeforeSave set too high!"); if (lastEditBeforeSave == edits.size() - 1) return new ArrayList<JSONObject>(0); return new ArrayList<JSONObject>(edits.subList(lastEditBeforeSave + 1, edits.size())); }
Example 60
| Project: csound-wizard-master File: Param.java View source code |
public static Param parse(Object obj) {
if (Json.isObject(obj)) {
JSONObject jobj = (JSONObject) obj;
LayoutParam layout = LayoutParam.parse(jobj);
ColorParam color = ColorParam.parse(jobj);
TextParam text = TextParam.parse(jobj);
RangeParam range = RangeParam.parse(jobj);
NamesParam names = NamesParam.parse(jobj);
TouchParam touch = TouchParam.parse(jobj);
return new Param(layout, color, text, range, names, touch);
}
return null;
}Example 61
| Project: Cytomine-client-autobuilder-master File: AbstractSequencePossibilties.java View source code |
public void build(JSONObject json) throws Exception {
this.c = JSONUtils.extractJSONList(json.get("c"));
this.channel = JSONUtils.extractJSONList(json.get("channel"));
this.imageGroup = JSONUtils.extractJSONList(json.get("imageGroup"));
this.s = JSONUtils.extractJSONList(json.get("s"));
this.slice = JSONUtils.extractJSONList(json.get("slice"));
this.t = JSONUtils.extractJSONList(json.get("t"));
this.time = JSONUtils.extractJSONList(json.get("time"));
this.z = JSONUtils.extractJSONList(json.get("z"));
this.zStack = JSONUtils.extractJSONList(json.get("zStack"));
}Example 62
| Project: Cytomine-java-client-master File: CytomineException.java View source code |
private String getMessage(JSONObject json) {
try {
String msg = "";
if (json != null) {
Iterator iter = json.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
msg = msg + entry.getValue();
}
}
message = msg;
} catch (Exception e) {
log.error(e);
}
return message;
}Example 63
| Project: DiamondCore-master File: ClientDisconnectPacket.java View source code |
@SuppressWarnings("unchecked")
public void disconnect() throws IOException {
JSONObject object = new JSONObject();
object.put("text", this.reason.toString());
DesktopPacket packet = new DesktopPacket(PacketIDList.CLIENT_DISCONNECT);
packet.writeString(object.toString());
output.write(packet.toByteArray());
output.flush();
if (shouldLog && username != null)
Diamond.logger.info("Disconnected player " + username + " for \"" + reason + "\"");
}Example 64
| Project: droidtowers-master File: RavenReportSender.java View source code |
@Override
public void send(CrashReportData data) throws ReportSenderException {
RavenClient ravenClient = new RavenClient(HappyDroidConsts.SENTRY_DSN);
JSONObject extra = new JSONObject();
extra.put("app_version", data.getProperty(ReportField.APP_VERSION_CODE));
extra.put("android_version", data.getProperty(ReportField.ANDROID_VERSION));
extra.put("available_mem_size", data.getProperty(ReportField.AVAILABLE_MEM_SIZE));
extra.put("total_mem_size", data.getProperty(ReportField.TOTAL_MEM_SIZE));
extra.put("user_email", data.getProperty(ReportField.USER_EMAIL));
extra.put("user_comment", data.getProperty(ReportField.USER_COMMENT));
extra.put("display", data.getProperty(ReportField.DISPLAY));
if (TowerGameService.hasBeenInitialised()) {
extra.put("device_id", TowerGameService.instance().getDeviceId());
}
extra.put("device_build", data.getProperty(ReportField.BUILD));
extra.put("device_brand", data.getProperty(ReportField.BRAND));
extra.put("device_product", data.getProperty(ReportField.PRODUCT));
extra.put("device_model", data.getProperty(ReportField.PHONE_MODEL));
ravenClient.captureException(data.getProperty(ReportField.STACK_TRACE), RavenUtils.getTimestampLong(), "root", 50, null, null, extra);
}Example 65
| Project: DynmapCore-master File: JSONUtils.java View source code |
// Gets a value at the specified path. public static Object g(JSONObject o, String path) { int index = path.indexOf('/'); if (index == -1) { return o.get(path); } else { String key = path.substring(0, index); String subpath = path.substring(index + 1); Object oo = o.get(key); JSONObject subobject; if (oo == null) { return null; } else /*if (oo instanceof JSONObject)*/ { subobject = (JSONObject) o; } return g(subobject, subpath); } }
Example 66
| Project: ecologylabFundamental-master File: ReferenceType.java View source code |
@Override
public void appendValue(T instance, Appendable buffy, boolean needsEscaping, TranslationContext serializationContext, Format format) throws IOException {
String instanceString = "";
if (instance != null && serializationContext != null)
// andruid 1/4/10
instanceString = marshall(instance, serializationContext);
// instance.toString();
if (needsEscaping) {
switch(format) {
case JSON:
buffy.append(JSONObject.escape(instanceString));
;
break;
case XML:
XMLTools.escapeXML(buffy, instanceString);
break;
default:
XMLTools.escapeXML(buffy, instanceString);
break;
}
} else
buffy.append(instanceString);
}Example 67
| Project: Eggscraper-master File: JSONhandler.java View source code |
public static ArrayList<String> getJSONValues(String jsonString, List<String> objectKeys) {
ArrayList<String> result = new ArrayList<String>();
// convert the given string to a json object
JSONObject jobj = null;
try {
jobj = (JSONObject) JSONValue.parse(jsonString);
} catch (Exception ex) {
JSONArray jray = null;
try {
jray = (JSONArray) JSONValue.parse(jsonString);
if (jray.size() == 1) {
jobj = (JSONObject) jray.get(0);
} else {
return null;
}
} catch (Exception excep) {
System.err.println("Couldn't convert the following to a JSON object...");
System.err.println(jsonString);
System.out.println(ex.toString());
}
}
// loop through all of the given keys and extract their values as a string
for (String jsonKey : objectKeys) {
// use a try statement inside the loop iteration so that breaking only skips this key
try {
Object objectValue = jobj.get(jsonKey);
if (objectValue != null) {
result.add(objectValue.toString());
}
} catch (Exception ex) {
System.err.println("Couldn't get " + jsonKey + " from...");
System.err.println(jsonString);
System.out.println(ex.toString());
}
}
return result;
}Example 68
| Project: geoserver-enterprise-master File: PagedUniqueProcessPPIO.java View source code |
@Override
public void encode(Object value, OutputStream os) throws Exception {
PagedUniqueProcess.Results result = (PagedUniqueProcess.Results) value;
JSONObject obj = new JSONObject();
obj.put("featureTypeName", result.getFeatureTypeName());
obj.put("fieldName", result.getFieldName());
obj.put("size", result.getSize());
obj.put("values", result.getValues());
Writer writer = new OutputStreamWriter(os);
obj.writeJSONString(writer);
writer.flush();
}Example 69
| Project: geoserver-master File: PagedUniqueProcessPPIO.java View source code |
@Override
public void encode(Object value, OutputStream os) throws Exception {
PagedUniqueProcess.Results result = (PagedUniqueProcess.Results) value;
JSONObject obj = new JSONObject();
obj.put("featureTypeName", result.getFeatureTypeName());
obj.put("fieldName", result.getFieldName());
obj.put("size", result.getSize());
obj.put("values", result.getValues());
Writer writer = new OutputStreamWriter(os);
obj.writeJSONString(writer);
writer.flush();
}Example 70
| Project: geotools-master File: MBFilterIntegrationTest.java View source code |
/**
* Create a style with three layers, each of them with a filter requiring a '$type' (or a list of them).
*
* Assert that the transformed {@link FeatureTypeStyle}s have the correct derived {@link SemanticType}s.
*/
@Test
public void testSemanticTypes() throws IOException, ParseException {
JSONObject jsonObject = MapboxTestUtils.parseTestStyle("filterSemanticTypeTest.json");
MBStyle mbStyle = new MBStyle(jsonObject);
StyledLayerDescriptor sld = mbStyle.transform();
FeatureTypeStyle[] ftss = SLD.featureTypeStyles(sld);
assertEquals(3, ftss.length);
FeatureTypeStyle circleLayerFts = ftss[0];
assertEquals("circle-layer", circleLayerFts.getName());
assertEquals(1, circleLayerFts.semanticTypeIdentifiers().size());
assertEquals(SemanticType.POINT, circleLayerFts.semanticTypeIdentifiers().iterator().next());
FeatureTypeStyle lineLayerFts = ftss[1];
assertEquals("line-layer", lineLayerFts.getName());
assertEquals(1, lineLayerFts.semanticTypeIdentifiers().size());
assertEquals(SemanticType.LINE, lineLayerFts.semanticTypeIdentifiers().iterator().next());
FeatureTypeStyle symbolLayerFts = ftss[2];
assertEquals("symbol-layer", symbolLayerFts.getName());
assertEquals(2, symbolLayerFts.semanticTypeIdentifiers().size());
Set<SemanticType> semanticTypes = symbolLayerFts.semanticTypeIdentifiers();
assertTrue(semanticTypes.contains(SemanticType.POINT) && semanticTypes.contains(SemanticType.POLYGON));
}Example 71
| Project: Glowstone-Legacy-master File: StatusRequestHandler.java View source code |
@Override
@SuppressWarnings("unchecked")
public void handle(GlowSession session, StatusRequestMessage message) {
// create and call the event
GlowServer server = session.getServer();
int online = server.getOnlinePlayers().size();
InetAddress address = session.getAddress().getAddress();
StatusEvent event = new StatusEvent(address, server.getMotd(), online, server.getMaxPlayers());
event.icon = server.getServerIcon();
EventFactory.callEvent(event);
// build the json
JSONObject json = new JSONObject();
JSONObject version = new JSONObject();
version.put("name", "Glowstone " + GlowServer.GAME_VERSION);
version.put("protocol", GlowServer.PROTOCOL_VERSION);
json.put("version", version);
JSONObject players = new JSONObject();
players.put("max", event.getMaxPlayers());
players.put("online", online);
json.put("players", players);
JSONObject description = new JSONObject();
description.put("text", event.getMotd());
json.put("description", description);
if (event.icon.getData() != null) {
json.put("favicon", event.icon.getData());
}
// send it off
session.send(new StatusResponseMessage(json));
}Example 72
| Project: Glowstone-master File: TellrawCommand.java View source code |
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
if (!testPermission(sender))
return true;
if (args.length < 2) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
return false;
}
Player player = Bukkit.getPlayerExact(args[0]);
if (player == null || sender instanceof Player && !((Player) sender).canSee(player)) {
sender.sendMessage("There's no player by that name online.");
} else {
StringBuilder message = new StringBuilder();
for (int i = 1; i < args.length; i++) {
if (i > 1)
message.append(" ");
message.append(args[i]);
}
GlowPlayer glowPlayer = (GlowPlayer) player;
Object obj = JSONValue.parse(message.toString());
if (!(obj instanceof JSONObject)) {
sender.sendMessage(ChatColor.RED + "Failed to parse JSON");
} else {
glowPlayer.getSession().send(new ChatMessage((JSONObject) obj));
}
}
return true;
}Example 73
| Project: GlowstonePlusPlus-master File: StatusRequestHandler.java View source code |
@Override
@SuppressWarnings("unchecked")
public void handle(GlowSession session, StatusRequestMessage message) {
// create and call the event
GlowServer server = session.getServer();
int online = server.getOnlinePlayers().size();
InetAddress address = session.getAddress().getAddress();
StatusEvent event = new StatusEvent(address, server.getMotd(), online, server.getMaxPlayers());
event.icon = server.getServerIcon();
EventFactory.callEvent(event);
// build the json
JSONObject json = new JSONObject();
JSONObject version = new JSONObject();
version.put("name", "Glowstone " + GlowServer.GAME_VERSION);
version.put("protocol", GlowServer.PROTOCOL_VERSION);
json.put("version", version);
JSONObject players = new JSONObject();
players.put("max", event.getMaxPlayers());
players.put("online", online);
json.put("players", players);
JSONObject description = new JSONObject();
description.put("text", event.getMotd());
json.put("description", description);
if (event.icon.getData() != null) {
json.put("favicon", event.icon.getData());
}
// send it off
session.send(new StatusResponseMessage(json));
}Example 74
| Project: google-docs-master File: IsMimetypeEvaluator.java View source code |
@Override public boolean evaluate(JSONObject jsonObject) { JSONObject importFormats = (JSONObject) getJSONValue(getMetadata(), accessor); try { JSONObject node = (JSONObject) jsonObject.get("node"); if (node == null) { return false; } else { String mimetype = (String) node.get("mimetype"); if (mimetype == null || !importFormats.containsKey(mimetype)) { log.debug("NodeRef: " + node.get("nodeRef") + "; Mimetype not supported: " + mimetype); return false; } log.debug("NodeRef: " + node.get("nodeRef") + "; Mimetype supported: " + mimetype); } } catch (Exception err) { throw new AlfrescoRuntimeException("Failed to run action evaluator: " + err.getMessage()); } return true; }
Example 75
| Project: GW2-master File: Main.java View source code |
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// System.out.println("-------------- ITEMS MAP START --------------\n");
// /* Récupère les items depuis la base de données */
// Map<Integer, Item> items = DataDBReader.extractData();
// System.out.println(items.toString());
// System.out.println("-------------- ITEMS MAP END --------------\n\n");
//
// System.out.println("-------------- RECIPES MAP START --------------\n");
// /* Récupère les recettes depuis la base de données */
// Map<Integer, Tree> recipes = RecipeDBReader.extractRecipe();
// System.out.println(recipes.toString());
// System.out.println("-------------- RECIPES MAP END --------------\n\n");
GW2API api = new GW2API();
JSONToJavaTransformer transformer = new JSONToJavaTransformer();
api.setDao(new OfflineJsonDao());
try {
JSONObject items = (JSONObject) new JSONParser().parse(new InputStreamReader(new FileInputStream(new File("res/items.json")), Charset.forName("UTF16")));
JSONObject obj = new JSONObject();
Set<String> ids = items.keySet();
List<Long> result = new ArrayList<Long>(ids.size());
for (String object : ids) {
result.add(Long.valueOf(object));
}
obj.put("items", result);
//
} catch (IOExceptionParseException | e) {
Logger.getGlobal().log(null, e.toString());
}
}Example 76
| Project: hadaps-master File: TestJSONProvider.java View source code |
@Test
@SuppressWarnings("unchecked")
public void test() throws Exception {
JSONProvider p = new JSONProvider();
assertTrue(p.isWriteable(JSONObject.class, null, null, null));
assertFalse(p.isWriteable(this.getClass(), null, null, null));
assertEquals(p.getSize(null, null, null, null, null), -1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JSONObject json = new JSONObject();
json.put("a", "A");
p.writeTo(json, JSONObject.class, null, null, null, null, baos);
baos.close();
assertEquals(new String(baos.toByteArray()).trim(), "{\"a\":\"A\"}");
}Example 77
| Project: hadoop-master File: TestJSONProvider.java View source code |
@Test
@SuppressWarnings("unchecked")
public void test() throws Exception {
JSONProvider p = new JSONProvider();
assertTrue(p.isWriteable(JSONObject.class, null, null, null));
assertFalse(p.isWriteable(this.getClass(), null, null, null));
assertEquals(p.getSize(null, null, null, null, null), -1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JSONObject json = new JSONObject();
json.put("a", "A");
p.writeTo(json, JSONObject.class, null, null, null, null, baos);
baos.close();
assertEquals(new String(baos.toByteArray()).trim(), "{\"a\":\"A\"}");
}Example 78
| Project: hadoop-on-lustre2-master File: TestJSONProvider.java View source code |
@Test
@SuppressWarnings("unchecked")
public void test() throws Exception {
JSONProvider p = new JSONProvider();
assertTrue(p.isWriteable(JSONObject.class, null, null, null));
assertFalse(p.isWriteable(this.getClass(), null, null, null));
assertEquals(p.getSize(null, null, null, null, null), -1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JSONObject json = new JSONObject();
json.put("a", "A");
p.writeTo(json, JSONObject.class, null, null, null, null, baos);
baos.close();
assertEquals(new String(baos.toByteArray()).trim(), "{\"a\":\"A\"}");
}Example 79
| Project: hadoop-release-2.6.0-master File: TestJSONProvider.java View source code |
@Test
@SuppressWarnings("unchecked")
public void test() throws Exception {
JSONProvider p = new JSONProvider();
assertTrue(p.isWriteable(JSONObject.class, null, null, null));
assertFalse(p.isWriteable(this.getClass(), null, null, null));
assertEquals(p.getSize(null, null, null, null, null), -1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JSONObject json = new JSONObject();
json.put("a", "A");
p.writeTo(json, JSONObject.class, null, null, null, null, baos);
baos.close();
assertEquals(new String(baos.toByteArray()).trim(), "{\"a\":\"A\"}");
}Example 80
| Project: HDP-2.2-Patched-master File: TestJSONProvider.java View source code |
@Test
@SuppressWarnings("unchecked")
public void test() throws Exception {
JSONProvider p = new JSONProvider();
assertTrue(p.isWriteable(JSONObject.class, null, null, null));
assertFalse(p.isWriteable(this.getClass(), null, null, null));
assertEquals(p.getSize(null, null, null, null, null), -1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JSONObject json = new JSONObject();
json.put("a", "A");
p.writeTo(json, JSONObject.class, null, null, null, null, baos);
baos.close();
assertEquals(new String(baos.toByteArray()).trim(), "{\"a\":\"A\"}");
}Example 81
| Project: hoop-master File: TestJSONProvider.java View source code |
@Test
@SuppressWarnings("unchecked")
public void test() throws Exception {
JSONProvider p = new JSONProvider();
Assert.assertTrue(p.isWriteable(JSONObject.class, null, null, null));
Assert.assertFalse(p.isWriteable(XTest.class, null, null, null));
Assert.assertEquals(p.getSize(null, null, null, null, null), -1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JSONObject json = new JSONObject();
json.put("a", "A");
p.writeTo(json, JSONObject.class, null, null, null, null, baos);
baos.close();
Assert.assertEquals(new String(baos.toByteArray()).trim(), "{\"a\":\"A\"}");
}Example 82
| Project: hops-master File: TestJSONProvider.java View source code |
@Test
@SuppressWarnings("unchecked")
public void test() throws Exception {
JSONProvider p = new JSONProvider();
assertTrue(p.isWriteable(JSONObject.class, null, null, null));
assertFalse(p.isWriteable(this.getClass(), null, null, null));
assertEquals(p.getSize(null, null, null, null, null), -1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JSONObject json = new JSONObject();
json.put("a", "A");
p.writeTo(json, JSONObject.class, null, null, null, null, baos);
baos.close();
assertEquals(new String(baos.toByteArray()).trim(), "{\"a\":\"A\"}");
}Example 83
| Project: incubator-atlas-master File: AtlasAuthenticationFailureHandler.java View source code |
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
LOG.debug("Login Failure ", e);
JSONObject json = new JSONObject();
ObjectMapper mapper = new ObjectMapper();
json.put("msgDesc", e.getMessage());
String jsonAsStr = mapper.writeValueAsString(json);
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonAsStr);
}Example 84
| Project: indextank-engine-master File: Autocomplete.java View source code |
/**
* @see java.lang.Runnable#run()
*/
public void run() {
IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api");
HttpServletResponse res = res();
String characterEncoding = api.getCharacterEncoding();
try {
req().setCharacterEncoding(characterEncoding);
res.setCharacterEncoding(characterEncoding);
res.setContentType("application/json");
} catch (UnsupportedEncodingException ignored) {
}
String query = params("query");
String field = params("field");
String callback = params("callback");
if (field == null || field.isEmpty()) {
field = "text";
}
List<String> complete = api.complete(query, field);
JSONObject json = new JSONObject();
json.put("query", query);
json.put("suggestions", complete);
if (callback != null && !callback.trim().isEmpty()) {
print(callback.trim() + "(" + json.toJSONString() + ")");
} else {
print(json.toJSONString());
}
}Example 85
| Project: java-oss-lib-master File: JSONValue.java View source code |
/**
* Encode an object into JSON text and write it to out.
* <p>
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
* <p>
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
* "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
*
* @see org.json.simple.JSONObject#writeJSONString(Map, Writer)
* @see org.json.simple.JSONArray#writeJSONString(List, Writer)
*
* @param value
* @param writer
*/
public static void writeJSONString(Object value, Writer out) throws IOException {
if (value == null) {
out.write("null");
return;
}
// check if there is a registered formatter here.
JSONFormatter formatter = findFormatter(value.getClass());
if (formatter != null) {
out.write(formatter.toJSONString(value));
return;
}
if (value instanceof String) {
out.write('\"');
out.write(escape((String) value));
out.write('\"');
return;
}
if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Number) {
out.write(value.toString());
return;
}
if (value instanceof Boolean) {
out.write(value.toString());
return;
}
if ((value instanceof JSONStreamAware)) {
((JSONStreamAware) value).writeJSONString(out);
return;
}
if ((value instanceof JSONAware)) {
out.write(((JSONAware) value).toJSONString());
return;
}
if (value instanceof Map) {
JSONObject.writeJSONString((Map) value, out);
return;
}
if (value instanceof DynMapConvertable) {
JSONObject.writeJSONString(((DynMapConvertable) value).toDynMap(), out);
return;
}
if (value instanceof Collection) {
JSONArray.writeJSONString((Collection) value, out);
return;
}
writeJSONString(value.toString(), out);
}Example 86
| Project: java_practical_semantic_web-master File: JSONValue.java View source code |
/** * Encode an object into JSON text and write it to out. * <p/> * If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly. * <p/> * DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with * "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead. * * @param value * @param writer * @see org.json.simple.JSONObject#writeJSONString(Map, Writer) * @see org.json.simple.JSONArray#writeJSONString(List, Writer) */ public static void writeJSONString(Object value, Writer out) throws IOException { if (value == null) { out.write("null"); return; } if (value instanceof String) { out.write('\"'); out.write(escape((String) value)); out.write('\"'); return; } if (value instanceof Double) { if (((Double) value).isInfinite() || ((Double) value).isNaN()) out.write("null"); else out.write(value.toString()); return; } if (value instanceof Float) { if (((Float) value).isInfinite() || ((Float) value).isNaN()) out.write("null"); else out.write(value.toString()); return; } if (value instanceof Number) { out.write(value.toString()); return; } if (value instanceof Boolean) { out.write(value.toString()); return; } if ((value instanceof JSONStreamAware)) { ((JSONStreamAware) value).writeJSONString(out); return; } if ((value instanceof JSONAware)) { out.write(((JSONAware) value).toJSONString()); return; } if (value instanceof Map) { JSONObject.writeJSONString((Map) value, out); return; } if (value instanceof List) { JSONArray.writeJSONString((List) value, out); return; } out.write(value.toString()); }
Example 87
| Project: jogetworkflow-master File: StringUtil.java View source code |
public static String escapeString(String inStr, String format, Map<String, String> replaceMap) {
if (replaceMap != null) {
Iterator it = replaceMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
inStr = inStr.replaceAll(pairs.getKey(), escapeRegex(pairs.getValue()));
}
}
if (format == null) {
return inStr;
}
if (format.equals(TYPE_REGEX)) {
return escapeRegex(inStr);
}
if (format.equals(TYPE_JSON)) {
return escapeRegex(JSONObject.escape(inStr));
}
return inStr;
}Example 88
| Project: jolokia-master File: ValidatingResponseExtractor.java View source code |
public <RESP extends J4pResponse<REQ>, REQ extends J4pRequest> RESP extract(REQ pRequest, JSONObject pJsonResp) throws J4pRemoteException {
int status = 0;
if (pJsonResp.containsKey("status")) {
Object o = pJsonResp.get("status");
if (o instanceof Long) {
status = ((Long) o).intValue();
}
}
if (!allowedCodes.contains(status)) {
throw new J4pRemoteException(pRequest, pJsonResp);
}
return status == 200 ? pRequest.<RESP>createResponse(pJsonResp) : null;
}Example 89
| Project: json-simple-kalle-master File: JSONValue.java View source code |
/**
* Encode an object into JSON text and write it to out.
* <p>
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
* <p>
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
* "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
*
* @see org.json.simple.JSONObject#writeJSONString(Map, Writer)
* @see org.json.simple.JSONArray#writeJSONString(List, Writer)
*
* @param value
* @param writer
*/
public static void writeJSONString(Object value, Writer out) throws IOException {
if (value == null) {
out.write("null");
return;
}
if (value instanceof String) {
out.write('\"');
out.write(escape((String) value));
out.write('\"');
return;
}
if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Number) {
out.write(value.toString());
return;
}
if (value instanceof Boolean) {
out.write(value.toString());
return;
}
if ((value instanceof JSONStreamAware)) {
((JSONStreamAware) value).writeJSONString(out);
return;
}
if ((value instanceof JSONAware)) {
out.write(((JSONAware) value).toJSONString());
return;
}
if (value instanceof Map) {
JSONObject.writeJSONString((Map) value, out);
return;
}
if (value instanceof List) {
JSONArray.writeJSONString((List) value, out);
return;
}
out.write(value.toString());
}Example 90
| Project: JSONTopicMap-master File: StatisticsUtility.java View source code |
private void loadStats() {
TextFileHandler h = new TextFileHandler();
java.io.File f = new java.io.File(FILE_NAME);
if (f.exists()) {
String json = h.readFile(FILE_NAME);
if (json == null)
data = new JSONObject();
else {
try {
data = (JSONObject) new JSONParser(JSONParser.MODE_JSON_SIMPLE).parse(json);
} catch (Exception e) {
e.printStackTrace();
}
}
} else
data = new JSONObject();
}Example 91
| Project: Khepera_simulation-master File: ActuatorBehaviour.java View source code |
public void action() {
/* receive message*/
ACLMessage msg = this.myAgent.receive();
if (msg != null) {
/* parse the json message */
// to optimize performance we can avoid this object
// creation and reuse an existing one.
JSONParser parser = new JSONParser();
Object parsed_content = null;
try {
parsed_content = (JSONObject) parser.parse(msg.getContent());
} catch (ParseException e) {
System.out.println("Actuator:error:" + e);
}
JSONObject json_content = (JSONObject) parsed_content;
/* access and process the received values from the controller */
try {
long u = (Long) json_content.get("u");
System.out.println("Actuator: u = " + u + ", timestamp = " + json_content.get("timestamp"));
/* actualize the state of the world */
this.world.move(u);
} catch (java.lang.NullPointerException e) {
System.out.println("no value");
}
} else {
block();
}
}Example 92
| Project: KnightOfWor-master File: Maze.java View source code |
private double[][] loadJSON(String levelName) {
double[][] result = null;
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("./src/main/resources/de/sanguinik/model/" + levelName + ".json"));
JSONObject jsonObject = (JSONObject) obj;
double[][] blockValues = new double[jsonObject.size()][4];
for (int i = 1; i <= jsonObject.size(); i++) {
JSONObject block = (JSONObject) jsonObject.get("Block" + i);
long x = (Long) block.get("x");
blockValues[i - 1][0] = (double) x;
long y = (Long) block.get("y");
blockValues[i - 1][1] = (double) y;
long width = (Long) block.get("width");
blockValues[i - 1][2] = (double) width;
long height = (Long) block.get("height");
blockValues[i - 1][3] = (double) height;
}
result = blockValues;
} catch (IOExceptionParseException | e) {
e.printStackTrace();
}
return result;
}Example 93
| Project: KnxAutomationDaemon-master File: AsyncReadRunnable.java View source code |
@Override
public void run() {
try {
String value = knx.read(address);
if (value != null) {
JSONObject jsonResponse = new JSONObject();
JSONObject jsonData = new JSONObject();
jsonData.put(address, value);
jsonResponse.put(BackendServer.PARAM_DATA, jsonData);
log.info("async response: {}", jsonResponse.toJSONString());
sse.sendMessage(null, null, jsonResponse.toJSONString());
} else {
log.warn("Cannot read '" + address + "' async. Timeout?");
}
} catch (KnxServiceException ex) {
log.error("Error reading data from '" + address + "'", ex);
}
}Example 94
| Project: librivox-java-master File: JSONValue.java View source code |
/**
* Encode an object into JSON text and write it to out.
* <p>
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
* <p>
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
* "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
*
* @see org.json.simple.JSONObject#writeJSONString(Map, Writer)
* @see org.json.simple.JSONArray#writeJSONString(List, Writer)
*
* @param value
* @param writer
*/
public static void writeJSONString(Object value, Writer out) throws IOException {
if (value == null) {
out.write("null");
return;
}
if (value instanceof String) {
out.write('\"');
out.write(escape((String) value));
out.write('\"');
return;
}
if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Number) {
out.write(value.toString());
return;
}
if (value instanceof Boolean) {
out.write(value.toString());
return;
}
if ((value instanceof JSONStreamAware)) {
((JSONStreamAware) value).writeJSONString(out);
return;
}
if ((value instanceof JSONAware)) {
out.write(((JSONAware) value).toJSONString());
return;
}
if (value instanceof Map) {
JSONObject.writeJSONString((Map) value, out);
return;
}
if (value instanceof List) {
JSONArray.writeJSONString((List) value, out);
return;
}
out.write(value.toString());
}Example 95
| Project: LWC-master File: NameFetcher.java View source code |
public Map<UUID, String> call() throws Exception {
Map<UUID, String> uuidStringMap = new HashMap<UUID, String>();
for (UUID uuid : uuids) {
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection();
JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
String name = (String) response.get("name");
if (name == null) {
continue;
}
String cause = (String) response.get("cause");
String errorMessage = (String) response.get("errorMessage");
if (cause != null && cause.length() > 0) {
throw new IllegalStateException(errorMessage);
}
uuidStringMap.put(uuid, name);
}
return uuidStringMap;
}Example 96
| Project: Mangue-master File: StateStorage.java View source code |
public String getChapter(String mangaId) {
String chapterNumber = null;
JSONArray jsonMangas = null;
try {
jsonMangas = (JSONArray) readJSON().get("mangas");
} catch (Exception e) {
}
if (jsonMangas == null)
jsonMangas = new JSONArray();
JSONObject jsonManga = findManga(jsonMangas, mangaId);
if (jsonManga != null)
chapterNumber = jsonManga.get("chapterNumber").toString();
return chapterNumber;
}Example 97
| Project: MDP-Group-10-master File: BluetoothListener.java View source code |
private void processCommand(int bytes, byte[] buffer) {
JSONObject map = null;
String string = new String(buffer, 0, bytes);
if (!string.equals("Map Reset")) {
map = (JSONObject) JSONValue.parse(string);
string = map.get("type").toString();
}
switch(string) {
case "movement":
//System.out.println("movement");
RTexploration.client.sendJSON("movement", map.get("data").toString());
break;
case "command":
//System.out.println("command");
RTexploration.client.sendJSON("command", map.get("data").toString());
break;
case "status":
//System.out.println("status");
RTexploration.client.sendJSON("status", map.get("data").toString());
break;
case "Map Reset":
System.out.println("Map Reset");
break;
default:
System.out.println(string);
break;
}
}Example 98
| Project: MinecraftAutoInstaller-master File: JSONValue.java View source code |
/**
* Encode an object into JSON text and write it to out.
* <p>
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
* <p>
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
* "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
*
* @see org.json.simple.JSONObject#writeJSONString(Map, Writer)
* @see org.json.simple.JSONArray#writeJSONString(List, Writer)
*
* @param value
* @param writer
*/
public static void writeJSONString(Object value, Writer out) throws IOException {
if (value == null) {
out.write("null");
return;
}
if (value instanceof String) {
out.write('\"');
out.write(escape((String) value));
out.write('\"');
return;
}
if (value instanceof Double) {
if (((Double) value).isInfinite() || ((Double) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Float) {
if (((Float) value).isInfinite() || ((Float) value).isNaN())
out.write("null");
else
out.write(value.toString());
return;
}
if (value instanceof Number) {
out.write(value.toString());
return;
}
if (value instanceof Boolean) {
out.write(value.toString());
return;
}
if ((value instanceof JSONStreamAware)) {
((JSONStreamAware) value).writeJSONString(out);
return;
}
if ((value instanceof JSONAware)) {
out.write(((JSONAware) value).toJSONString());
return;
}
if (value instanceof Map) {
JSONObject.writeJSONString((Map) value, out);
return;
}
if (value instanceof List) {
JSONArray.writeJSONString((List) value, out);
return;
}
out.write(value.toString());
}Example 99
| Project: moddle-master File: YggdrasilRequest.java View source code |
public YggdrasilResult send() throws Exception {
JSONObject agent = new JSONObject();
agent.put("name", "Minecraft");
agent.put("version", "1");
JSONObject payload = new JSONObject();
payload.put("agent", agent);
payload.put("username", Username);
payload.put("password", Password);
String resultString = doJSONPost("https://authserver.mojang.com/authenticate", payload);
YggdrasilResult result = new YggdrasilResult(resultString);
return result;
}Example 100
| Project: MorphMiner-master File: Snippet.java View source code |
public static Snippet createSnipet(String name, JSONObject a, SemanticContextBridge scb) throws IOException { Snippet s = new Snippet(); s.src = "www.semanpix.de::###"; s.namne = name; System.out.println("> " + a.size()); Iterator i = a.keySet().iterator(); while (i.hasNext()) { System.out.println(i.next()); } JSONArray array = (JSONArray) a.get("Original Dokumentation"); System.out.println(">> " + array.size()); if (array.size() > 0) { s.doc = (String) array.get(0); } JSONArray array2 = (JSONArray) a.get("Snippet"); System.out.println(">> " + array2.size()); if (array2.size() > 0) { JSONObject layerName = (JSONObject) array2.get(0); String sname = (String) layerName.get("fulltext"); System.out.println("Snippet.code layer pagename : " + sname); // pages are nodes and have layers // - code // - termvector // - entities // we take the code layer of the Node, found in the snippet table. Wiki wiki = scb.getWiki(); if (wiki != null) { String code = wiki.getPageText(sname); s.snip = code; System.out.println(code); } } return s; }
Example 101
| Project: MyPet-master File: UpdateCheck.java View source code |
public static Optional<String> checkForUpdate(String plugin) {
try {
String parameter = "";
parameter += "&package=" + MyPetApi.getCompatUtil().getInternalVersion();
parameter += "&build=" + MyPetVersion.getBuild();
// no data will be saved on the server
String content = Util.readUrlContent("http://update.mypet-plugin.de/" + plugin + "?" + parameter);
JSONParser parser = new JSONParser();
JSONObject result = (JSONObject) parser.parse(content);
if (result.containsKey("latest")) {
return Optional.of(result.get("latest").toString());
}
} catch (Exception ignored) {
}
return Optional.absent();
}