Java Examples for org.json.simple.JSONArray
The following java examples will help you to understand the usage of org.json.simple.JSONArray. These source code samples are taken from different open source projects.
Example 1
| Project: FRC1778-master File: StateStreamSocket.java View source code |
public void onWebSocketText(String message) {
JSONParser parser = new JSONParser();
Object obj;
try {
obj = parser.parse(message);
} catch (ParseException e) {
e.printStackTrace();
return;
}
JSONObject cmd = (JSONObject) obj;
if (cmd != null) {
String action = (String) cmd.get("action");
if ("pause".equals(action)) {
running = false;
} else if ("start".equals(action)) {
running = true;
}
if ("subscribe".equals(action)) {
JSONArray keys = (JSONArray) cmd.get("keys");
for (Object key : keys) {
subscribe((String) key);
}
} else if ("unsubscribe".equals(action)) {
JSONArray keys = (JSONArray) cmd.get("keys");
for (Object key : keys) {
unsubscribe((String) key);
}
}
}
if (isConnected()) {
update();
}
}Example 2
| 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 3
| Project: AIDR-master File: GISUtil.java View source code |
public String getDisplayName(String lat, String lon) throws Exception {
String disName = null;
if (!lat.isEmpty() && !lon.isEmpty()) {
String key = lat + "," + lon;
String returnJson = communicator.sendGet(urlBase + key + urlTail);
if (returnJson.trim().length() > 10) {
JSONArray jsonArray = (JSONArray) parser.parse(returnJson);
Iterator itr = jsonArray.iterator();
while (itr.hasNext()) {
JSONObject featureJsonObj = (JSONObject) itr.next();
JSONObject info = (JSONObject) featureJsonObj.get("address");
String state = (String) info.get("state");
String city = (String) info.get("city");
String county = (String) info.get("county");
disName = (String) featureJsonObj.get("display_name");
}
}
}
return disName;
}Example 4
| Project: BioHoward-master File: HelpUtil.java View source code |
public static String getHelp(String filename) {
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(filename), "UTF-8");
JSONArray helpMsgArray = (JSONArray) MapUtil.parser.parse(isr);
StringBuffer buf = new StringBuffer();
for (Object ooo : helpMsgArray) buf.append((String) ooo + "\n");
return buf.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}Example 5
| Project: cassandra-rest-master File: CassandraHealthCheck.java View source code |
@Override
public Result check() throws Exception {
Result result = null;
try {
String host = VirgilConfiguration.getHost();
int port = VirgilConfiguration.getPort();
JSONArray keyspaces = this.service.getStorage().getKeyspaces();
String output = "Connected to [" + host + ":" + port + "] w/ " + keyspaces.size() + " keyspaces.";
result = Result.healthy(output);
} catch (Throwable e) {
result = Result.unhealthy("Unable to connect to cluster: " + e.getMessage());
}
return result;
}Example 6
| Project: CZ3003_Backend-master File: TestingStuff.java View source code |
public static void formTrialJsonObject() throws IOException {
for (int i = 1; i <= 3; i++) {
messagesToSend.put(i, new ArrayList<MessageToSend>());
}
jsonArrayOfMails = new JSONArray();
MessageToSend m = new MessageToSend("cz3003timecrisis@gmail.com", "akritivij18@gmail.com", "Subject", "Body text", 3);
messagesToSend.get(3).add(m);
m = new MessageToSend("cz3003timecrisis@gmail.com", "akritivij18@gmail.com", "Subject", "Body text", 1);
messagesToSend.get(1).add(m);
m = new MessageToSend("cz3003timecrisis@gmail.com", "akritivij18@gmail.com", "Subject", "Body text", 1);
messagesToSend.get(1).add(m);
jsonObject = new JSONObject();
jsonObject.put("from", "cz3003timecrisis@gmail.com");
jsonObject.put("recipients", "akritivij18@gmail.com");
jsonObject.put("subject", "Subject ");
jsonObject.put("messageText", "body here");
jsonObject.put("priority", 3);
jsonArrayOfMails.add(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("from", "cz3003timecrisis@gmail.com");
jsonObject.put("recipients", "akritivij18@gmail.com");
jsonObject.put("subject", "Subject ");
jsonObject.put("messageText", "body here");
jsonObject.put("priority", 3);
jsonArrayOfMails.add(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("from", "cz3003timecrisis@gmail.com");
jsonObject.put("recipients", "akritivij18@gmail.com");
jsonObject.put("subject", "Subject ");
jsonObject.put("messageText", "body here");
jsonObject.put("priority", 1);
jsonArrayOfMails.add(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("messagesToBeSent", jsonArrayOfMails);
System.out.println(jsonArrayOfMails.toJSONString());
System.out.println(jsonObject.toJSONString());
FileWriter file = new FileWriter("trialJson.txt");
try {
file.write(jsonObject.toJSONString());
System.out.println("Successfully Copied JSON Object to File...");
} catch (IOException e) {
e.printStackTrace();
} finally {
file.flush();
file.close();
}
}Example 7
| Project: shopizer-master File: IndexProduct.java View source code |
@SuppressWarnings("unchecked")
@Override
public String toJSONString() {
JSONObject obj = new JSONObject();
obj.put("name", this.getName());
obj.put("price", this.getPrice());
obj.put("description", this.getDescription());
obj.put("highlight", this.getHighlight());
obj.put("store", this.getStore());
obj.put("manufacturer", this.getManufacturer());
obj.put("lang", this.getLang());
obj.put("id", this.getId());
if (categories != null) {
JSONArray categoriesArray = new JSONArray();
for (String category : categories) {
categoriesArray.add(category);
}
obj.put("categories", categoriesArray);
}
if (tags != null) {
JSONArray tagsArray = new JSONArray();
for (String tag : tags) {
tagsArray.add(tag);
}
obj.put("tags", tagsArray);
}
return obj.toJSONString();
}Example 8
| Project: cello-master File: JsonWriter.java View source code |
public static void writeToJson(HashMap<String, ArrayList<Circuit>> foundTruthValues, String dir, double runtime, Date d, double currCost, HashSet<String> allowedOps) {
ArrayList<JSONObject> content = new ArrayList<JSONObject>();
JSONObject details = new JSONObject();
details.put("collection", "run_details");
details.put("operations_used", allowedOps);
details.put("operation_costs", ConstantProperties.costPerOp);
details.put("number_found", Integer.toString(foundTruthValues.size()));
details.put("runtime", runtime);
details.put("date_started", d);
details.put("max_cost", currCost);
content.add(details);
ArrayList<String> truthValues = new ArrayList<String>(foundTruthValues.keySet());
Collections.sort(truthValues);
for (String tv : truthValues) {
JSONObject tvCircPair = new JSONObject();
JSONArray circList = new JSONArray();
for (Circuit circ : foundTruthValues.get(tv)) {
circList.add(circ.toString());
}
tvCircPair.put("truthValue", tv);
tvCircPair.put("circuits", circList);
content.add(tvCircPair);
}
prettyPrintJSONArray(content, dir, false);
}Example 9
| Project: chatty-master File: EmoticonManager.java View source code |
/**
* Parses the list of emoticons from the Twitch API.
*
* @param json
* @return
*/
private Set<Emoticon> parseEmoticons(String json) {
Set<Emoticon> result = new HashSet<>();
if (json == null) {
return null;
}
JSONParser parser = new JSONParser();
int errors = 0;
try {
JSONObject root = (JSONObject) parser.parse(json);
JSONArray emoticons = (JSONArray) root.get("emoticons");
for (Object obj : emoticons) {
if (obj instanceof JSONObject) {
JSONObject emote_json = (JSONObject) obj;
Emoticon emote = parseEmoticon(emote_json);
if (emote == null) {
if (errors < 10) {
LOGGER.warning("Error loading emote: " + emote_json);
}
errors++;
} else {
result.add(emote);
}
}
}
if (errors > 0) {
LOGGER.warning(errors + " emotes couldn't be loaded");
}
if (errors > 100) {
return null;
}
return result;
} catch (ParseExceptionNullPointerException | ClassCastException | ex) {
LOGGER.warning("Error parsing emoticons: " + ex);
return null;
}
}Example 10
| Project: csound-wizard-master File: Tabs.java View source code |
@Override
public View getView(LayoutContext ctx, Object tagValue, final Param param, final Param defaults, TrackState trackState, final LayoutParent layoutParent) {
if (isTabs(tagValue)) {
ActionBar bar = ((Activity) ctx.getContext()).getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
JSONArray alts = (JSONArray) tagValue;
for (Object rawEntry : alts) {
JSONObject entry = (JSONObject) rawEntry;
Iterator<String> it = entry.keySet().iterator();
String key = it.next();
bar.addTab(initTab(bar, ctx, key, Layout.getView(ctx, entry.get(key), defaults, LayoutParent.NONE, trackState)));
}
return new View(ctx.getContext());
} else {
return Layout.errorMalformedTabs(ctx, getTag() + ": " + tagValue.toString(), defaults);
}
}Example 11
| Project: epicsarchiverap-master File: PolicyConfig.java View source code |
// We need this SuppressWarnings here as JSON is too dynamic.
@SuppressWarnings("unchecked")
public String generateStringRepresentation() {
JSONObject stringRep = new JSONObject();
stringRep.put("samplingMethod", samplingMethod.toString());
stringRep.put("samplingPeriod", Float.toString(samplingPeriod));
stringRep.put("policyName", policyName);
stringRep.put("controlPV", controlPV);
JSONArray stores = new JSONArray();
for (String store : dataStores) stores.add(store);
stringRep.put("dataStores", stores);
if (this.appliance != null) {
stringRep.put("appliance", appliance);
}
return stringRep.toJSONString();
}Example 12
| 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 13
| Project: jolokia-master File: CollectionExtractorTest.java View source code |
@Test
public void json() throws AttributeNotFoundException {
assertFalse(extractor.canSetValue());
Set set = new HashSet(Arrays.asList("jolokia", "habanero"));
List ret = (List) extractor.extractObject(converter, set, new Stack<String>(), true);
assertEquals(ret.size(), 2);
assertTrue(ret.contains("jolokia"));
assertTrue(ret.contains("habanero"));
assertTrue(ret instanceof JSONArray);
}Example 14
| 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 15
| Project: Qora-master File: ApiClient.java View source code |
public String executeCommand(String command) {
if (command.equals("help")) {
String help = "<method> <url> <data> \n" + "Type quit to stop.";
return help;
}
try {
//SPLIT
String[] args = command.split(" ");
//GET METHOD
String method = args[0].toUpperCase();
//GET PATH
String path = args[1];
//GET CONTENT
String content = "";
if (method.equals("POST")) {
content = command.substring((method + " " + path + " ").length());
}
//CREATE CONNECTION
URL url = new URL("http://127.0.0.1:" + Settings.getInstance().getRpcPort() + "/" + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//EXECUTE
connection.setRequestMethod(method);
if (method.equals("POST")) {
connection.setDoOutput(true);
connection.getOutputStream().write(content.getBytes());
connection.getOutputStream().flush();
connection.getOutputStream().close();
}
//READ RESULT
InputStream stream;
if (connection.getResponseCode() == 400) {
stream = connection.getErrorStream();
} else {
stream = connection.getInputStream();
}
InputStreamReader isReader = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(isReader);
//TODO READ ALL OR HARDCODE HELP
String result = br.readLine();
try {
Writer writer = new JSonWriter();
Object jsonResult = JSONValue.parse(result);
if (jsonResult instanceof JSONArray) {
((JSONArray) jsonResult).writeJSONString(writer);
return writer.toString();
}
if (jsonResult instanceof JSONObject) {
((JSONObject) jsonResult).writeJSONString(writer);
return writer.toString();
}
writer.close();
return result;
} catch (Exception e) {
return result;
}
} catch (IOError ioe) {
return "Invalid command! \n" + "Type help to get a list of commands.";
} catch (Exception e) {
return "Invalid command! \n" + "Type help to get a list of commands.";
}
}Example 16
| Project: strata2012-master File: TwitterDataExtractor.java View source code |
@Override
public void execute(Tuple input, BasicOutputCollector collector) {
String json = (String) input.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(input.getString(0), hashObj.get("text").toString().toLowerCase()));
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}Example 17
| Project: nodeclipse-1-master File: GeneratedToolsProtocolParser.java View source code |
@Override
public java.util.List<java.util.List<java.lang.Object>> asListTabsData() throws org.chromium.sdk.internal.protocolparser.JsonProtocolParseException {
java.util.List<java.util.List<java.lang.Object>> result = lazyCachedField_0.get();
if (result != null) {
return result;
}
if (underlying instanceof org.json.simple.JSONArray == false) {
throw new org.chromium.sdk.internal.protocolparser.JsonProtocolParseException("Array value expected");
}
final org.json.simple.JSONArray arrayValue1 = (org.json.simple.JSONArray) underlying;
int size2 = arrayValue1.size();
java.util.List<java.util.List<java.lang.Object>> list3 = new java.util.ArrayList<java.util.List<java.lang.Object>>(size2);
for (int index4 = 0; index4 < size2; index4++) {
if (arrayValue1.get(index4) instanceof org.json.simple.JSONArray == false) {
throw new org.chromium.sdk.internal.protocolparser.JsonProtocolParseException("Array value expected");
}
final org.json.simple.JSONArray arrayValue6 = (org.json.simple.JSONArray) arrayValue1.get(index4);
int size7 = arrayValue6.size();
java.util.List<java.lang.Object> list8 = new java.util.ArrayList<java.lang.Object>(size7);
for (int index9 = 0; index9 < size7; index9++) {
java.lang.Object arrayComponent10 = (java.lang.Object) arrayValue6.get(index9);
list8.add(arrayComponent10);
}
java.util.List<java.lang.Object> arrayComponent5 = java.util.Collections.unmodifiableList(list8);
list3.add(arrayComponent5);
}
java.util.List<java.util.List<java.lang.Object>> parseResult0 = java.util.Collections.unmodifiableList(list3);
if (parseResult0 != null) {
lazyCachedField_0.compareAndSet(null, parseResult0);
java.util.List<java.util.List<java.lang.Object>> cachedResult = lazyCachedField_0.get();
parseResult0 = cachedResult;
}
return parseResult0;
}Example 18
| 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 19
| Project: android-sync-master File: HistoryHelpers.java View source code |
@SuppressWarnings("unchecked")
private static JSONArray getVisits1() {
JSONArray json = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("date", 1320087601465600000L);
obj.put("type", 2L);
json.add(obj);
obj = new JSONObject();
obj.put("date", 1320084970724990000L);
obj.put("type", 1L);
json.add(obj);
obj = new JSONObject();
obj.put("date", 1319764134412287000L);
obj.put("type", 1L);
json.add(obj);
obj = new JSONObject();
obj.put("date", 1319681306455594000L);
obj.put("type", 2L);
json.add(obj);
return json;
}Example 20
| 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 21
| Project: Assignments-master File: JsonTest.java View source code |
@SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
Dictionary dic = new Dictionary();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("test1.json"));
for (Object o : a) {
JSONObject word = (JSONObject) o;
String synonymString = new String();
String w = (String) word.get("word");
// loop array of synonyms
JSONArray synonyms = (JSONArray) word.get("synonyms");
for (Object object : synonyms) {
synonymString += object;
synonymString += ",";
}
synonymString = synonymString.substring(0, synonymString.length() - 1);
String d = (String) word.get("description");
Word theWord = new Word(w, synonymString, d);
System.out.println(theWord.toString());
dic.add(theWord);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
JSONArray array = new JSONArray();
for (Entry<String, Word> entry : dic.getWords().entrySet()) {
JSONObject obj = new JSONObject();
obj.put("word", entry.getValue().getWord());
JSONArray list = new JSONArray();
for (int j = 0; j < entry.getValue().getSynonyms().length; j++) {
list.add(entry.getValue().getSynonyms()[j]);
}
obj.put("synonyms", list);
obj.put("description", entry.getValue().getDescription());
System.out.print(obj);
array.add(obj);
}
try {
FileWriter file = new FileWriter("test1.json");
file.write(array.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}Example 22
| 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 23
| Project: blueflood-master File: BatchedMetricsJSONOutputSerializerTest.java View source code |
@Test
public void testBatchedMetricsSerialization() throws Exception {
final BatchedMetricsJSONOutputSerializer serializer = new BatchedMetricsJSONOutputSerializer();
final Map<Locator, MetricData> metrics = new HashMap<Locator, MetricData>();
for (int i = 0; i < 2; i++) {
final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeRollupPoints(), "unknown");
metrics.put(Locator.createLocatorFromPathComponents(tenantId, String.valueOf(i)), metricData);
}
JSONObject jsonMetrics = serializer.transformRollupData(metrics, filterStats);
Assert.assertTrue(jsonMetrics.get("metrics") != null);
JSONArray jsonMetricsArray = (JSONArray) jsonMetrics.get("metrics");
Iterator<JSONObject> metricsObjects = jsonMetricsArray.iterator();
Assert.assertTrue(metricsObjects.hasNext());
while (metricsObjects.hasNext()) {
JSONObject singleMetricObject = metricsObjects.next();
Assert.assertTrue(singleMetricObject.get("unit").equals("unknown"));
Assert.assertTrue(singleMetricObject.get("type").equals("number"));
JSONArray data = (JSONArray) singleMetricObject.get("data");
Assert.assertTrue(data != null);
}
}Example 24
| 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 25
| 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 26
| Project: GW2-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 27
| Project: indextank-engine-master File: StopAnalyzer.java View source code |
private static Set<String> getStopWords(Map<Object, Object> analyzerConfiguration) {
if (analyzerConfiguration.containsKey(STOPWORDS)) {
JSONArray stopwordList = (JSONArray) analyzerConfiguration.get(STOPWORDS);
Set<String> stopwords = new HashSet<String>(stopwordList.size());
for (Object stopword : stopwordList) {
if (!(stopword instanceof String)) {
throw new IllegalArgumentException("Stopwords aren't Strings");
}
stopwords.add((String) stopword);
}
return stopwords;
} else {
return ImmutableSet.of();
}
}Example 28
| 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 29
| 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 30
| 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 31
| 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 32
| 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 33
| Project: mapfish-print-master File: StringArrayAttributeTest.java View source code |
@Test
public void testWrongType() throws Exception {
final Configuration config = configurationFactory.getConfig(getFile(BASE_DIR + "config.yaml"));
PJsonObject requestData = loadJsonRequestData();
final JSONArray intArray = new JSONArray();
intArray.add(1);
intArray.add(2);
intArray.add(3);
requestData.getJSONObject("attributes").getInternalObj().put("stringarray", intArray);
Template template = config.getTemplate("main");
Values values = new Values(requestData, template, this.parser, config.getDirectory(), httpClientFactory, config.getDirectory());
String[] array = (String[]) values.getObject("stringarray", Object.class);
assertArrayEquals(new String[] { "1", "2", "3" }, array);
}Example 34
| 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 35
| Project: mdk-master File: DBAlfrescoListVisitor.java View source code |
@SuppressWarnings("unchecked")
@Override
public void visit(DBList list) {
if (listjson.containsKey("type")) {
DBAlfrescoListVisitor inner = new DBAlfrescoListVisitor(recurse);
list.accept(inner);
curitem.add(inner.getObject());
listelements.addAll(inner.getListElements());
elementSet.addAll(inner.getElementSet());
} else {
listjson.put("type", "List");
if (list.isOrdered()) {
listjson.put("ordered", true);
} else {
listjson.put("ordered", false);
}
listjson.put("bulleted", true);
JSONArray l = new JSONArray();
listjson.put("list", l);
for (DocumentElement de : list.getChildren()) {
curitem = new JSONArray();
de.accept(this);
l.add(curitem);
}
}
}Example 36
| 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 37
| 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 38
| Project: MultiverseKing_JME-master File: GameProperties.java View source code |
private static void update(AssetManager assetManager) {
JSONObject data = (JSONObject) assetManager.loadAsset(new AssetKey<>("Data/GameProperties.json"));
JSONObject card = (JSONObject) data.get("Card");
// @todo
// updateList((byte) 0, (JSONArray) card.get(RenderComponent.RenderType.Ability.toString()));
// updateList((byte) 1, (JSONArray) card.get(RenderComponent.RenderType.Equipement.toString()));
updateList((byte) 2, (JSONArray) card.get(RenderComponent.RenderType.Unit.toString()));
updateList((byte) 3, (JSONArray) card.get(RenderComponent.RenderType.Titan.toString()));
updateList((byte) 4, (JSONArray) data.get("Map"));
}Example 39
| Project: NemakiWare-master File: AuthTokenResource.java View source code |
@GET
@Path("/{userName}")
@Produces(MediaType.APPLICATION_JSON)
public String get(@PathParam("repositoryId") String repositoryId, @PathParam("userName") String userName, @QueryParam("app") String app) {
boolean status = true;
JSONObject result = new JSONObject();
JSONArray errMsg = new JSONArray();
if (StringUtils.isBlank(app)) {
app = "";
}
Token token = tokenService.getToken(app, repositoryId, userName);
if (token == null) {
status = false;
errMsg = new //TODO
JSONArray();
} else {
JSONObject obj = new JSONObject();
obj.put("app", app);
obj.put("repositoryId", repositoryId);
obj.put("userName", userName);
obj.put("token", token.getToken());
obj.put("expiration", token.getExpiration());
result.put("value", obj);
}
result = makeResult(status, result, errMsg);
return result.toString();
}Example 40
| Project: nxt-master File: TestCastVote.java View source code |
@Test
public void validVoteCasting() {
APICall apiCall = new CreatePollBuilder().build();
String poll = TestCreatePoll.issueCreatePoll(apiCall, false);
generateBlock();
apiCall = new APICall.Builder("castVote").param("secretPhrase", ALICE.getSecretPhrase()).param("poll", poll).param("vote00", 1).param("vote01", 0).param("feeNQT", Constants.ONE_NXT).build();
JSONObject response = apiCall.invoke();
Logger.logMessage("voteCasting:" + response.toJSONString());
Assert.assertNull(response.get("error"));
generateBlock();
apiCall = new APICall.Builder("getPollResult").param("poll", poll).build();
JSONObject getPollResponse = apiCall.invoke();
Logger.logMessage("getPollResultResponse:" + getPollResponse.toJSONString());
JSONArray results = (JSONArray) getPollResponse.get("results");
long ringoResult = Long.parseLong(getResult(results, 0));
Assert.assertEquals(1, ringoResult);
long paulResult = Long.parseLong(getResult(results, 1));
Assert.assertEquals(0, paulResult);
//John's result is empty by spec
Assert.assertEquals("", getResult(results, 2));
}Example 41
| Project: oicsns-master File: GetMapUserList.java View source code |
@Override
public void ActionEvent(JSONObject json, WebSocketListener webSocket) {
JSONObject responseJSON = new JSONObject();
responseJSON.put("method", "getmapuserlist");
if (!validation(json)) {
responseJSON.put("status", 1);
webSocket.sendJson(responseJSON);
return;
}
int mapid = Integer.parseInt(json.get("mapid").toString());
MapFactory factory = MapFactory.getInstance();
OicMap map = factory.getMap(mapid);
JSONArray charactersJSON = new JSONArray();
try {
for (Long userid : map.getUserIdList()) {
charactersJSON.add(userid);
}
} catch (NullPointerException ex) {
}
responseJSON.put("userlist", charactersJSON);
webSocket.sendJson(responseJSON);
}Example 42
| Project: oozie-master File: TestVersionServlet.java View source code |
public Void call() throws Exception {
Map<String, String> params = new HashMap<String, String>();
URL url = createURL("", params);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
assertEquals(HttpServletResponse.SC_OK, conn.getResponseCode());
assertTrue(conn.getHeaderField("content-type").startsWith(RestConstants.JSON_CONTENT_TYPE));
JSONArray array = (JSONArray) JSONValue.parse(new InputStreamReader(conn.getInputStream()));
assertEquals(2, array.size());
assertEquals(OozieClient.WS_PROTOCOL_VERSION, array.get(1));
return null;
}Example 43
| Project: PerfLog-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 44
| Project: phylowidget-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 45
| Project: PocketMine-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 46
| Project: prjvmac-master File: TestVersionServlet.java View source code |
public Void call() throws Exception {
Map<String, String> params = new HashMap<String, String>();
URL url = createURL("", params);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
assertEquals(HttpServletResponse.SC_OK, conn.getResponseCode());
assertTrue(conn.getHeaderField("content-type").startsWith(RestConstants.JSON_CONTENT_TYPE));
JSONArray array = (JSONArray) JSONValue.parse(new InputStreamReader(conn.getInputStream()));
assertEquals(2, array.size());
assertEquals(OozieClient.WS_PROTOCOL_VERSION, array.get(1));
return null;
}Example 47
| Project: RandomGift-master File: Updater.java View source code |
void checkForUpdate() {
if (plugin.versionCheck == true) {
try {
updateCheck = new URL("https://api.curseforge.com/servermods/files?projectids=67733");
} catch (MalformedURLException e) {
return;
}
try {
connection = updateCheck.openConnection();
connection.setReadTimeout(5000);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
response = reader.readLine();
} catch (IOException e) {
plugin.getLogger().warning("There was a problem checking for updates! Are you connected to the internet?");
return;
}
JSONArray array = (JSONArray) JSONValue.parse(response);
JSONObject latest = (JSONObject) array.get(array.size() - 1);
String version = (String) latest.get("fileName");
int versionNum = Integer.parseInt(version.replaceAll("[^0-9]", ""));
int currentVersion = Integer.parseInt(plugin.getDescription().getVersion().replaceAll("[^0-9]", ""));
if (currentVersion < versionNum) {
notify.consoleUpdateAvailable();
plugin.updateAvailable = true;
}
}
}Example 48
| Project: ReportRTS-master File: VersionChecker.java View source code |
public boolean upToDate() {
// TODO: Rewrite this for Spigot.
return true;
// Return true because Bukkit.org is unsupported.
/*if(!ReportRTS.getPlugin().getConfig().getBoolean("versionCheck")) return true;
try {
final String currentVersion = ReportRTS.getPlugin().getDescription().getVersion().substring(0,ReportRTS.getPlugin().getDescription().getVersion().lastIndexOf("-"));
final URLConnection connection = new URL("https://api.curseforge.com/servermods/files?projectIds=36853").openConnection();
connection.setConnectTimeout(3000);
connection.setReadTimeout(5000);
connection.setRequestProperty("User-agent", "ReportRTS version " + currentVersion + " (By ProjectInfinity)");
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();
reader.close();
connection.getInputStream().close();
JSONArray array = (JSONArray) JSONValue.parse(response);
if(array.size() > 0){
JSONObject latest = (JSONObject) array.get(array.size() - 1);
String version = (String) latest.get("name");
String download = (String) latest.get("downloadUrl");
if(Integer.parseInt(currentVersion.replace("v", "").replaceAll("[^A-Za-z0-9]", "")) < Integer.parseInt(version.replace("v", "").replaceAll("[^A-Za-z0-9]", ""))){
ReportRTS.getPlugin().getLogger().info("Version " + version + " is available for download.");
ReportRTS.getPlugin().getLogger().info("Download it at " + download);
ReportRTS.getPlugin().versionString = version;
return false;
}else{
return true;
}
}else{
return true;
}
} catch (final Exception e) {
return true;
} */
}Example 49
| Project: robotium-remote-master File: EventReturnValueMessage.java View source code |
@Override
public String toString() {
JSONObject jsonObj = getHeader();
jsonObj.put(Message.JSON_ATTR_CLASS_TYPE, TypeUtils.getClassName(classType));
jsonObj.put(Message.JSON_ATTR_IS_PRIMITIVE, isPrimitive);
jsonObj.put(Message.JSON_ATTR_INNER_CLASS_TYPE, TypeUtils.getClassName(innerClassType));
jsonObj.put(Message.JSON_ATTR_IS_COLLECTION, isCollection);
// if the returned values are not collection of primitives,
// they will be a list of object references (i.e the key in the WeakHashMap)
JSONArray values = new JSONArray();
for (int i = 0; i < returnValue.length; i++) {
values.add(TypeUtils.getPrimitiveStringValue(returnValue[i].getClass(), returnValue[i]));
}
jsonObj.put(Message.JSON_ATTR_RETURN_VALUE, values);
return jsonObj.toString();
}Example 50
| Project: seda-proto-master File: OpOutEventHandler.java View source code |
@SuppressWarnings("unchecked")
private void doBroadcast(Message event) {
int count = event.asBroadcastResponse.keyCount.get();
logger.debug("got broadcast message with {} key-value pairs.", count);
// create list
JSONArray list = new JSONArray();
for (int i = 0; i < count; i++) {
JSONObject elem = new JSONObject();
elem.put("key", event.asBroadcastResponse.key[i].get());
elem.put("value", event.asBroadcastResponse.value[i].get());
list.add(elem);
}
// add it to root
JSONObject root = new JSONObject();
root.put("keyvalues", list);
sessionManager.sendAll(root.toJSONString());
}Example 51
| Project: SPICE-master File: SpiceTestTupleTest.java View source code |
protected void compare(JSONArray expected, JSONArray actual) { assertEquals("Output wrong number of results", expected.size(), actual.size()); for (int i = 0; i < expectedOutput.size(); i++) { JSONObject expectedItem = (JSONObject) expected.get(i); JSONObject actualItem = (JSONObject) actual.get(i); // Image id assertEquals("Incorrect image id", expectedItem.get("image_id"), actualItem.get("image_id")); // Test tuples JSONArray expectedTestTuples = (JSONArray) expectedItem.get("test_tuples"); JSONArray actualTestTuples = (JSONArray) actualItem.get("test_tuples"); compareTuples(expectedTestTuples, actualTestTuples, "test", expectedItem.get("image_id")); } }
Example 52
| Project: storm-solr-master File: NestedDocumentMapperTest.java View source code |
public static JSONArray loadNestedDocs() throws Exception { JSONArray jsonDocs = null; InputStreamReader isr = null; String testDocsOnCpath = "test-data/nested_docs.json"; try { isr = new InputStreamReader(NestedDocumentMapperTest.class.getClassLoader().getResourceAsStream(testDocsOnCpath), StandardCharsets.UTF_8); jsonDocs = (JSONArray) JSONValue.parse(isr); } finally { if (isr != null) { try { isr.close(); } catch (Exception ignore) { } } } assertNotNull("Failed to load test JSON docs from " + testDocsOnCpath, jsonDocs); return jsonDocs; }
Example 53
| Project: streaminer-master File: ArrayCategoricalTarget.java View source code |
@Override
protected void addJSON(JSONArray binJSON, DecimalFormat format) {
JSONObject counts = new JSONObject();
for (Entry<Object, Integer> categoryIndex : _indexMap.entrySet()) {
Object category = categoryIndex.getKey();
int index = categoryIndex.getValue();
double count = _target[index];
counts.put(category, NumberUtil.roundNumber(count, format));
}
binJSON.add(counts);
}Example 54
| Project: swf-all-master File: JSONFormatter.java View source code |
private void writeAttributes(JSONObject obj, Writer w) throws IOException {
boolean first = true;
List<String> keys = new ArrayList<String>();
keys.addAll(obj.keySet());
Collections.sort(keys);
for (Object k : keys) {
Object v = obj.get(k);
w.append("\n");
indent(w);
if (!first) {
w.append(",");
} else {
first = false;
}
w.append("\"").append(JSONObject.escape(k.toString())).append("\" : ");
if (v instanceof JSONObject) {
writePrettyJson((JSONObject) v, w);
} else if (v instanceof JSONArray) {
writePrettyJsonArray((JSONArray) v, w);
} else {
w.append('"').append(JSONObject.escape(v.toString())).append("\"");
}
backIndent(w);
}
w.append("\n");
backIndent(w);
indent(w);
}Example 55
| Project: Symfony-2-Eclipse-Plugin-master File: ProjectOptions.java View source code |
/** * * Retrieve the synthetic services of a project. * * * @param project * @return */ public static final JSONArray getSyntheticServices(IProject project) { JSONArray defaultSynthetics = null; try { CorePreferencesSupport prefs = CorePreferencesSupport.getInstance(); String synths = prefs.getPreferencesValue(Keys.SYNTHETIC_SERVICES, null, project); Logger.debugMSG("LOADED DEFAULTS: " + synths); JSONParser parser = new JSONParser(); defaultSynthetics = (JSONArray) parser.parse(synths); } catch (Exception e) { Logger.logException(e); } return defaultSynthetics; }
Example 56
| Project: TagRec-master File: JSONProcessor.java View source code |
public static void writeJSONOutput(String filename) {
BookmarkReader reader = new BookmarkReader(0, false);
reader.readFile(filename);
Set<Integer> resources = new HashSet<Integer>();
FileOutputStream writer = null;
try {
writer = new FileOutputStream(new File("./data/csv/" + filename + ".json"));
} catch (Exception e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(writer));
for (Bookmark bookmark : reader.getBookmarks()) {
//if (!resources.contains(bookmark.getResourceID())) {
JSONObject jsonOutput = new JSONObject();
jsonOutput.put("url", reader.getResources().get(bookmark.getResourceID()));
jsonOutput.put("timestamp", new Integer(bookmark.getTimestamp()));
JSONArray jsonTags = new JSONArray();
for (Integer tag : bookmark.getTags()) {
jsonTags.add(reader.getTags().get(tag));
}
jsonOutput.put("tags", jsonTags);
resources.add(bookmark.getResourceID());
try {
bw.write(jsonOutput.toJSONString() + "\n");
} catch (Exception e) {
e.printStackTrace();
}
//}
}
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}Example 57
| Project: tair-client-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: TerraLegion-master File: JSONConverter.java View source code |
public static JSONObject getJSONFromInventory(Inventory inventory) {
JSONObject jsonInventory = new JSONObject();
JSONObject inventorySize = new JSONObject();
inventorySize.put("width", inventory.getWidth());
inventorySize.put("height", inventory.getHeight());
jsonInventory.put("inventorySize", inventorySize);
JSONArray itemList = new JSONArray();
for (int x = 0; x < inventory.getWidth(); x++) {
for (int y = 0; y < inventory.getHeight(); y++) {
ItemStack itemStack = inventory.getItemStack(x, y);
if (itemStack != null) {
JSONObject itemStackInfo = new JSONObject();
itemStackInfo.put("x", x);
itemStackInfo.put("y", y);
itemStackInfo.put("id", itemStack.getItem().getTypeId());
itemStackInfo.put("stack", itemStack.getStack());
itemList.add(itemStackInfo);
}
}
}
jsonInventory.put("content", itemList);
return jsonInventory;
}Example 59
| Project: TheRoll-master File: SmartCroppingConverter.java View source code |
@Override
public List<SmartCropping> convert(String jsonString) {
if (jsonString == null) {
throw new ConverterException("The given JSON string is null");
}
JSONObject json = (JSONObject) JSONValue.parse(jsonString);
if (!json.containsKey(SMART_CROPPINGS)) {
throw new ConverterException(SMART_CROPPINGS + " key missing from json : " + jsonString);
}
JSONArray jsonArray = (JSONArray) json.get(SMART_CROPPINGS);
List<SmartCropping> smartCroppings = new ArrayList<SmartCropping>();
for (Object aJsonArray : jsonArray) {
JSONObject smartCroppingObject = (JSONObject) aJsonArray;
String url = getString("url", smartCroppingObject);
List<Cropping> croppings = new ArrayList<Cropping>();
if (smartCroppingObject.containsKey(CROPPINGS)) {
JSONArray croppingsArray = (JSONArray) smartCroppingObject.get(CROPPINGS);
for (Object aCroppingsArray : croppingsArray) {
JSONObject croppingObject = (JSONObject) aCroppingsArray;
croppings.add(new Cropping(new Resolution(getInteger("target_width", croppingObject), getInteger("target_height", croppingObject)), new Region(getInteger("x1", croppingObject), getInteger("y1", croppingObject), getInteger("x2", croppingObject), getInteger("y2", croppingObject))));
}
smartCroppings.add(new SmartCropping(url, croppings));
}
}
return smartCroppings;
}Example 60
| Project: tradeframework-master File: ApePayloadParser.java View source code |
public boolean parseContent(InputStream input, long length, String contentType, MsgHandler handler) throws IOException, MsgParseException {
JSONArray json = (JSONArray) JSONValue.parse(new BufferedReader(new InputStreamReader(input)));
for (Object rawObj : json) {
log.info("Received raw message " + rawObj.toString());
JSONObject raw = (JSONObject) rawObj;
String rawType = (String) raw.get("raw");
JSONObject data = (JSONObject) raw.get("data");
if (!payload.parseData(rawType, data, handler))
return false;
}
return true;
}Example 61
| Project: tsdash-master File: MetricQuery.java View source code |
public static MetricQuery fromJSONObject(JSONObject src) {
MetricQuery newQuery = new MetricQuery();
newQuery.name = (String) src.get("name");
if (src.get("rate") != null) {
newQuery.rate = (Boolean) src.get("rate");
}
newQuery.tags = decodeTags((JSONObject) src.get("tags"));
newQuery.aggregator = (String) src.get("aggregator");
newQuery.orders = decodeArray((JSONArray) src.get("orders"));
newQuery.dissolveTags = decodeArray((JSONArray) src.get("dissolveTags"));
return newQuery;
}Example 62
| Project: vizzy-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 63
| Project: wearscript-android-master File: WifiManager.java View source code |
public String getScanResults() {
Double timestamp = System.currentTimeMillis() / 1000.;
JSONArray a = new JSONArray();
for (ScanResult s : manager.getScanResults()) {
JSONObject r = new JSONObject();
r.put("timestamp", timestamp);
r.put("capabilities", new String(s.capabilities));
r.put("SSID", new String(s.SSID));
r.put("BSSID", new String(s.BSSID));
r.put("level", Integer.valueOf(s.level));
r.put("frequency", Integer.valueOf(s.frequency));
a.add(r);
}
return a.toJSONString();
}Example 64
| Project: jeo-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 65
| Project: aq2o-master File: JMSPublisher.java View source code |
public void send(Map<String, Object> message) throws Exception {
Map<String, Object> mmap = new HashMap<String, Object>();
Iterator<Entry<String, Object>> eit = message.entrySet().iterator();
while (eit.hasNext()) {
Entry<String, Object> e = eit.next();
String key = e.getKey();
Object val = e.getValue();
if (val == null)
continue;
if (!val.getClass().isArray()) {
mmap.put(key, val);
} else {
String simpleName = val.getClass().getSimpleName();
if (simpleName.startsWith("double")) {
JSONArray l = new JSONArray();
for (double d : (double[]) val) {
l.add(d);
}
mmap.put(key, l);
} else if (simpleName.startsWith("long")) {
JSONArray l = new JSONArray();
for (long d : (long[]) val) {
l.add(d);
}
mmap.put(key, l);
} else if (simpleName.startsWith("String")) {
JSONArray l = new JSONArray();
for (String d : (String[]) val) {
l.add(d);
}
mmap.put(key, l);
}
}
}
String text = JSONValue.toJSONString(mmap);
if (log.isDebugEnabled())
log.debug("[channelId=" + channelId + "] message: " + text);
TextMessage tm = session.createTextMessage(text);
tm.setStringProperty("channelId", channelId);
producer.send(tm);
}Example 66
| Project: asielauncher-master File: FileParserJSON.java View source code |
public ArrayList<FileDownloader> parse(JSONArray jsonList, String mode, String prefix) {
ArrayList<FileDownloader> list = new ArrayList<FileDownloader>();
for (Object o : jsonList) {
if (o instanceof JSONObject) {
JSONObject mod = (JSONObject) o;
String filename = (String) mod.get("filename");
Long filesize = (Long) mod.get("size");
String md5 = (String) mod.get("md5");
boolean overwrite = (Boolean) mod.get("overwrite");
if (mode.equals("http")) {
String inputAddress = baseURL + prefix + filename;
String outputFile = baseDirectory + filename;
FileDownloader fileDownloader = new FileDownloaderHTTP(inputAddress, outputFile, md5, filesize.intValue(), overwrite);
list.add(fileDownloader);
} else if (mode.equals("zip")) {
String inputAddress = baseURL + "zips/" + prefix + filename;
String outputFile = baseDirectory + "zips/" + filename;
String unpackLocation = baseDirectory + (String) mod.get("directory") + "/";
FileDownloader fileDownloader = new FileDownloaderZip(inputAddress, outputFile, unpackLocation, md5, filesize.intValue(), overwrite);
list.add(fileDownloader);
}
}
}
return list;
}Example 67
| Project: BranchMaster-master File: Commands.java View source code |
public String dir(File homedir, String navigate) {
if (navigate != null) {
if (navigate.equals("..") && homedir.getParentFile() != null) {
homedir = homedir.getParentFile();
CustomHTTPD.homedir = homedir;
} else if (navigate.equals("\\")) {
while (homedir.getParentFile() != null) {
homedir = homedir.getParentFile();
}
CustomHTTPD.homedir = homedir;
} else if (!navigate.equals("")) {
File[] listFiles = homedir.listFiles(directoryFilter);
for (File f : Arrays.asList(listFiles)) {
if (f.getName().equals(navigate)) {
homedir = f;
CustomHTTPD.homedir = homedir;
break;
}
}
}
}
JSONObject obj = new JSONObject();
obj.put("version", Main.version);
obj.put("homedir", homedir.getAbsolutePath());
JSONArray navigation = new JSONArray();
if (homedir.getParentFile() != null) {
navigation.add("\\");
navigation.add("..");
}
boolean isGitDir = false;
File[] listFiles = homedir.listFiles(directoryFilter);
JSONArray dirs = new JSONArray();
for (File f : Arrays.asList(listFiles)) {
if (f.getName().equals(".git")) {
dirs = new JSONArray();
isGitDir = true;
break;
}
dirs.add(f.getName());
}
navigation.addAll(dirs);
obj.put("dirs", navigation);
obj.put("gitdir", isGitDir);
if (isGitDir) {
List<String> branchChoiceList = BranchChoiceCache.get(homedir);
if (branchChoiceList != null) {
JSONArray latestChoice = new JSONArray();
latestChoice.addAll(branchChoiceList);
obj.put("selection", latestChoice);
}
List<String> branchList = new Git_BranchList(homedir).execute();
JSONArray branches = new JSONArray();
for (String b : branchList) {
if (b.startsWith("remotes/"))
branches.add(b.substring(8));
else
branches.add(b);
}
obj.put("branches", branches);
}
return obj.toString();
}Example 68
| Project: chukwa-master File: Series.java View source code |
public void add(long x, double y) {
try {
if (!series.containsKey("data")) {
series.put("data", new JSONArray());
}
JSONArray xy = new JSONArray();
xy.add(x);
xy.add(y);
((JSONArray) series.get("data")).add(xy);
} catch (Exception e) {
log.error(ExceptionUtil.getStackTrace(e));
}
}Example 69
| Project: Cloud-Stenography-master File: Edit.java View source code |
@RequiresLogin
public void recent() throws IOException {
int editIndex;
try {
editIndex = Integer.parseInt(getCtx().popParam());
} catch (Exception e) {
getCtx().getResp().sendError(400, "Couldn't get index of recent edit");
return;
}
String path = getPath();
List<JSONObject> editList = getEdits(path);
JSONArray array = new JSONArray();
array.addAll(editList.subList(editIndex, editList.size()));
print(array.toString());
}Example 70
| Project: CrystalQuest-master File: UUIDFetcher.java View source code |
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<>();
String body = buildBody(names);
for (int i = 1; i < MAX_SEARCH; i++) {
HttpURLConnection connection = createConnection(i);
writeBody(connection, body);
JSONObject jsonObject = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
JSONArray array = (JSONArray) jsonObject.get("profiles");
Number count = (Number) jsonObject.get("size");
if (count.intValue() == 0) {
break;
}
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32));
uuidMap.put(name, uuid);
}
}
return uuidMap;
}Example 71
| Project: daxplore-presenter-master File: StorageTools.java View source code |
/**
* Get some questions from the questions metadata file.
*
* <p>This is useful when answering an embed request, as the embed mode only
* uses two of the defined questions: one for the question and one for
* the perspective.</p>
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String getQuestionDefinitions(PersistenceManager pm, String prefix, List<String> questionIDs, Locale locale) throws BadRequestException {
try {
JSONArray definitions = new JSONArray();
ContainerFactory containerFactory = new ContainerFactory() {
@Override
public Map createObjectContainer() {
return new LinkedHashMap();
}
@Override
public List creatArrayContainer() {
return new LinkedList();
}
};
Reader reader = new StringReader(TextFileStore.getLocalizedFile(pm, prefix, "questions", locale, ".json"));
JSONParser parser = new JSONParser();
List<Map> questionList = (List<Map>) parser.parse(reader, containerFactory);
for (Map map : questionList) {
Object o = map.get("column");
String column = (String) o;
if (questionIDs.contains(column)) {
definitions.add(map);
}
}
return definitions.toJSONString();
} catch (IOExceptionParseException | e) {
throw new BadRequestException("Failed to read question definitions", e);
}
}Example 72
| Project: FastLogin-master File: MojangApiBukkit.java View source code |
@Override
public boolean hasJoinedServer(LoginSession session, String serverId) {
BukkitLoginSession playerSession = (BukkitLoginSession) session;
try {
String url = HAS_JOINED_URL + "username=" + playerSession.getUsername() + "&serverId=" + serverId;
HttpURLConnection conn = getConnection(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = reader.readLine();
if (line != null && !line.equals("null")) {
//validate parsing
//http://wiki.vg/Protocol_Encryption#Server
JSONObject userData = (JSONObject) JSONValue.parseWithException(line);
String uuid = (String) userData.get("id");
playerSession.setUuid(FastLoginCore.parseId(uuid));
JSONArray properties = (JSONArray) userData.get("properties");
JSONObject skinProperty = (JSONObject) properties.get(0);
String propertyName = (String) skinProperty.get("name");
if (propertyName.equals("textures")) {
String skinValue = (String) skinProperty.get("value");
String signature = (String) skinProperty.get("signature");
playerSession.setSkin(skinValue, signature);
}
return true;
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Failed to verify session", ex);
}
//this connection doesn't need to be closed. So can make use of keep alive in java
return false;
}Example 73
| Project: geolocator-3.0-master File: FreebaseSearch.java View source code |
public List<LocEntityAnnotation> queryTypes(List<LocEntityAnnotation> topos) {
try {
newtopos = new ArrayList<LocEntityAnnotation>();
HttpTransport httpTransport = new NetHttpTransport();
com.google.api.client.http.HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
JSONParser parser = new JSONParser();
GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/search");
Iterator<LocEntityAnnotation> iterator = topos.iterator();
while (iterator.hasNext()) {
LocEntityAnnotation topo = iterator.next();
String entityName = topo.getTokenString();
url.put("query", entityName);
/*
* url.put("filter", "(all type:/people/person)");
*/
// url.put("query", "Bill");
// url.put("lang", "zh");
// url.put("filter","(all type:/government/us_president)");
// url.put("output", "(description:wikipedia)");
url.put("limit", "1");
url.put("indent", "true");
url.put("key", FreebaseSearch.API_KEY);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse httpResponse = request.execute();
JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
JSONArray results = (JSONArray) response.get("result");
// System.out.println(results);
if (results.size() > 0) {
for (Object planet : results) {
// System.out.println(((JSONObject) planet).get("id"));
// System.out.println(((JSONObject)
// planet).get("notable"));
JSONObject notable = (JSONObject) ((JSONObject) planet).get("notable");
//System.out.println(notable.toString());
if (notable != null) {
String types = notable.get("id").toString();
if (types != null && types.length() != 0) {
if (types.indexOf("/location") == -1) {
// System.out.println(notable.get("name"));
iterator.remove();
}
}
} else
iterator.remove();
// System.out.println(((JSONObject)
// planet).get("score"));
// System.out.println(((JSONObject)
// planet).get("name"));
// System.out.println(((JSONObject)planet).get("output"));
}
}
}
newtopos = topos;
} catch (Exception ex) {
ex.printStackTrace();
}
return newtopos;
}Example 74
| Project: Glowstone-Legacy-master File: JsonListFile.java View source code |
/**
* Reloads from the file.
*/
public void load() {
entries.clear();
if (file.exists()) {
try (Reader reader = new FileReader(file)) {
JSONArray jsonArray = (JSONArray) new JSONParser().parse(reader);
for (Object object : jsonArray) {
JSONObject jsonObj = (JSONObject) object;
Map<String, String> map = new HashMap<>(jsonObj.size());
for (Object jsonEntry : jsonObj.entrySet()) {
Map.Entry<?, ?> entry = ((Map.Entry<?, ?>) jsonEntry);
map.put(entry.getKey().toString(), entry.getValue().toString());
}
entries.add(readEntry(map));
}
} catch (Exception ex) {
GlowServer.logger.log(Level.SEVERE, "Error reading from: " + file, ex);
}
} else {
//importLegacy();
save();
}
}Example 75
| Project: Glowstone-master File: JsonListFile.java View source code |
/**
* Reloads from the file.
*/
public void load() {
entries.clear();
if (file.exists()) {
try (Reader reader = new FileReader(file)) {
JSONArray jsonArray = (JSONArray) new JSONParser().parse(reader);
for (Object object : jsonArray) {
JSONObject jsonObj = (JSONObject) object;
Map<String, String> map = new HashMap<>(jsonObj.size());
for (Object jsonEntry : jsonObj.entrySet()) {
Entry<?, ?> entry = (Map.Entry<?, ?>) jsonEntry;
map.put(entry.getKey().toString(), entry.getValue().toString());
}
entries.add(readEntry(map));
}
} catch (Exception ex) {
GlowServer.logger.log(Level.SEVERE, "Error reading from: " + file, ex);
}
} else {
//importLegacy();
save();
}
}Example 76
| Project: GlowstonePlusPlus-master File: JsonListFile.java View source code |
/**
* Reloads from the file.
*/
public void load() {
entries.clear();
if (file.exists()) {
try (Reader reader = new FileReader(file)) {
JSONArray jsonArray = (JSONArray) new JSONParser().parse(reader);
for (Object object : jsonArray) {
JSONObject jsonObj = (JSONObject) object;
Map<String, String> map = new HashMap<>(jsonObj.size());
for (Object jsonEntry : jsonObj.entrySet()) {
Map.Entry<?, ?> entry = ((Map.Entry<?, ?>) jsonEntry);
map.put(entry.getKey().toString(), entry.getValue().toString());
}
entries.add(readEntry(map));
}
} catch (Exception ex) {
GlowServer.logger.log(Level.SEVERE, "Error reading from: " + file, ex);
}
} else {
//importLegacy();
save();
}
}Example 77
| Project: histogram-master File: MapCategoricalTarget.java View source code |
@Override
@SuppressWarnings("unchecked")
protected void addJSON(JSONArray binJSON, DecimalFormat format) {
JSONObject counts = new JSONObject();
for (Entry<Object, Double> categoryCount : _counts.entrySet()) {
Object category = categoryCount.getKey();
double count = categoryCount.getValue();
counts.put(category, Utils.roundNumber(count, format));
}
binJSON.add(counts);
}Example 78
| Project: jboss-as7-development-book-master File: TicketWebServiceIT.java View source code |
@Test
public void testREST() {
System.out.println("Testing Ticket REST Service");
ClientRequestFactory crf = new ClientRequestFactory(UriBuilder.fromUri("http://localhost:8080/ticket-agency-ws/rest/seat").build());
ClientRequest bookRequest = crf.createRelativeRequest("/4");
String entity = null;
try {
entity = bookRequest.post(String.class).getEntity();
} catch (Exception e1) {
e1.printStackTrace();
}
assertTrue(entity.equals("Ticket booked"));
System.out.println("Ticket Booked with REST Service");
ClientRequest request = crf.createRelativeRequest("/");
String seatList = null;
try {
seatList = request.get(String.class).getEntity();
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("SEAT List \n" + seatList);
Object obj = JSONValue.parse(seatList);
JSONArray array = (JSONArray) obj;
JSONObject seat = (JSONObject) array.get(4);
Boolean isbooked = (Boolean) seat.get("booked");
assertTrue(isbooked);
}Example 79
| Project: LWC-master File: UUIDFetcher.java View source code |
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<String, UUID>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.toUUID(id);
uuidMap.put(name, uuid);
}
if (rateLimiting && i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}Example 80
| Project: Magix-Plugin-master File: Random.java View source code |
private static boolean check() {
try {
final URLConnection connection = new URL(URl + PROJECT_ID).openConnection();
connection.setReadTimeout(5000);
connection.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final String response = reader.readLine();
JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.isEmpty())
return false;
} catch (Exception e) {
return true;
}
return true;
}Example 81
| Project: manifold-master File: ConfluenceResponse.java View source code |
public static <T extends ConfluenceResource> ConfluenceResponse<T> fromJson(JSONObject response, ConfluenceResourceBuilder<T> builder) {
List<T> resources = new ArrayList<T>();
JSONArray jsonArray = (JSONArray) response.get("results");
for (int i = 0, size = jsonArray.size(); i < size; i++) {
JSONObject jsonPage = (JSONObject) jsonArray.get(i);
T resource = (T) builder.fromJson(jsonPage);
resources.add(resource);
}
int limit = ((Long) response.get("limit")).intValue();
int start = ((Long) response.get("start")).intValue();
Boolean isLast = false;
JSONObject links = (JSONObject) response.get("_links");
if (links != null) {
isLast = (links.get("next") == null);
}
return new ConfluenceResponse<T>(resources, start, limit, isLast);
}Example 82
| Project: moddle-master File: IDHelper.java View source code |
public static String getIDFromConfig(String mode, String setting) {
JSONArray modsArray = (JSONArray) IDConfig.get(mode);
if (modsArray != null) {
for (Object obj : modsArray.toArray()) {
JSONObject mod = (JSONObject) obj;
String modname = (String) mod.get("name");
if (setting.contains(modname)) {
int rangeStart = Integer.parseInt((String) mod.get("range"));
int bump = 0;
if (IDRanges.containsKey(modname)) {
bump = IDRanges.get(modname);
}
IDRanges.put(modname, bump + 1);
return Integer.toString(rangeStart + bump);
}
}
}
return null;
}Example 83
| Project: OneDriveJavaSDK-master File: ConcreteOneDrive.java View source code |
public static List<OneDrive> parseDrivesFromJson(String json) throws OneDriveException, ParseException {
OneDriveError error;
if ((error = OneDriveError.parseError(json)) != null) {
throw new OneDriveException(error.toString());
}
JSONParser parser = new JSONParser();
JSONObject root = null;
try {
root = (JSONObject) parser.parse(json);
} catch (ParseException e) {
logger.warn("Something failed while parsing Json {}", e.getMessage());
logger.debug("Exception while parsing", e);
}
JSONArray values = (JSONArray) root.get("value");
json = values.toJSONString();
Gson gson = new Gson();
List<OneDrive> oneDrives = gson.fromJson(json, new TypeToken<List<ConcreteOneDrive>>() {
}.getType());
return oneDrives;
}Example 84
| Project: opencast-master File: ServiceEndpointTestsUtil.java View source code |
private static void testArrayProperty(String key, JSONObject expected, JSONObject actual) {
JSONArray expectedArray = (JSONArray) expected.get(key);
JSONArray actualArray = (JSONArray) actual.get(key);
Assert.assertEquals(expectedArray.size(), actualArray.size());
JSONObject exObject;
JSONObject acObject;
for (int i = 0; i < expectedArray.size(); i++) {
exObject = (JSONObject) expectedArray.get(i);
acObject = (JSONObject) actualArray.get(i);
Set<String> exEntrySet = exObject.keySet();
Assert.assertEquals(exEntrySet.size(), acObject.size());
Iterator<String> exIter = exEntrySet.iterator();
while (exIter.hasNext()) {
String item = exIter.next();
Object exValue = exObject.get(item);
Object acValue = acObject.get(item);
Assert.assertEquals(exValue, acValue);
}
}
}Example 85
| Project: PATRIC-master File: PSICQUICInterface.java View source code |
@SuppressWarnings("unchecked")
public JSONObject getResults(String db, String term, int startAt, int count) throws java.rmi.RemoteException {
JSONObject result = new JSONObject();
try {
String search_count = getCounts(db, term);
String url = baseURL + db + baseURLQuery + term + "?format=xml25&firstResult=" + startAt + "&maxResults=" + count;
// System.out.println("psicquic-fetch-url:" + url);
JSONArray subList = null;
if (db.equals("intact")) {
IntActHandler psicquicHandler = new IntActHandler(url);
subList = psicquicHandler.getParsedJSON();
}
result.put("results", subList);
result.put("total", search_count);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}Example 86
| Project: pipeline-builder-master File: DeploymentLog.java View source code |
public List<Deployment> getAll() {
JSONArray deployments = (JSONArray) log.get(ROOT);
ArrayList<Deployment> deploymentArrayList = new ArrayList<Deployment>();
for (int i = 0; i < deployments.size(); i++) {
deploymentArrayList.add(new Deployment((JSONObject) deployments.get(i)));
}
return deploymentArrayList;
}Example 87
| Project: POIProxy-master File: GeoJSONWriter.java View source code |
public String write(ArrayList<JTSFeature> features) throws JSONException, BaseException {
String result = null;
JSONObject featureCollection = new JSONObject();
featureCollection.put("type", "featureCollection");
JSONArray featuresJSON = new JSONArray();
JSONObject featureJSON;
JSONObject point;
JSONObject properties;
JSONArray coords;
for (JTSFeature feature : features) {
featureJSON = new JSONObject();
point = new JSONObject();
properties = new JSONObject();
coords = new JSONArray();
featureJSON.put("type", "Feature");
point.put("type", "Point");
coords.add(feature.getGeometry().getGeometry().getCoordinate().x);
coords.add(feature.getGeometry().getGeometry().getCoordinate().y);
point.put("coordinates", coords);
Set keys = feature.getAttributes().keySet();
Iterator it = keys.iterator();
String key;
while (it.hasNext()) {
key = it.next().toString();
properties.put(key, feature.getAttribute(key).value);
}
featureJSON.put("geometry", point);
featureJSON.put("properties", properties);
featuresJSON.add(featureJSON);
}
featureCollection.put("features", featuresJSON);
result = featureCollection.toString();
return result;
}Example 88
| Project: product-mdm-master File: PolicyOperations.java View source code |
public static boolean createPasscodePolicy(String policyName, String deviceType) {
HashMap<String, String> headers = new HashMap<String, String>();
String policyEndpoint = EMMConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/policies";
//Set the policy payload
JSONObject policyData = new JSONObject();
policyData.put("policyName", policyName);
policyData.put("description", "Passcode Policy");
policyData.put("compliance", "enforce");
policyData.put("ownershipType", "ANY");
policyData.put("active", false);
JSONObject profile = new JSONObject();
profile.put("profileName", "passcode");
profile.put("deviceType", deviceType);
JSONArray featureList = new JSONArray();
JSONObject feature = new JSONObject();
feature.put("featureCode", "PASSCODE_POLICY");
feature.put("deviceType", "android");
JSONObject featureContent = new JSONObject();
featureContent.put("allowSimple", true);
featureContent.put("requireAlphanumeric", true);
featureContent.put("minLength", null);
featureContent.put("minComplexChars", null);
featureContent.put("maxPINAgeInDays", 7);
featureContent.put("pinHistory", 7);
featureContent.put("maxFailedAttempts", null);
feature.put("content", featureContent);
featureList.add(feature);
profile.put("profileFeaturesList", featureList);
JSONArray roles = new JSONArray();
roles.add(Constants.EMM_USER_ROLE);
policyData.put("profile", profile);
policyData.put("roles", roles);
//Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
HTTPResponse httpResponse = HTTPInvoker.sendHTTPPostWithOAuthSecurity(policyEndpoint, policyData.toJSONString(), headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) {
return true;
}
return false;
}Example 89
| Project: Qwiksnap-master File: Updater.java View source code |
private void getJson() {
JSONObject jsonObject;
try {
jsonObject = readJsonFromUrl(Config.JSON_LINK);
serverVer = (String) jsonObject.get("launchv");
List<String> dlLinks = new ArrayList<String>();
JSONArray array = (JSONArray) jsonObject.get("contents");
for (int i = 0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject) array.get(i));
dlLinks.add(list.get("link").toString());
}
Config.setDLLinks(dlLinks);
} catch (IOException e) {
e.printStackTrace();
}
}Example 90
| Project: records-management-master File: UnlinkActionEvaluator.java View source code |
/**
* @see org.alfresco.web.evaluator.BaseEvaluator#evaluate(org.json.simple.JSONObject)
*/
@Override
public boolean evaluate(JSONObject jsonObject) {
boolean result = false;
try {
// first check that the multi parent indicator is present
JSONArray indicators = getRMIndicators(jsonObject);
if (indicators != null && indicators.contains(INDICATOR)) {
// now check that we are not in the primary location
String primaryParent = (String) ((JSONObject) ((JSONObject) jsonObject.get(NODE)).get(RM_NODE)).get(PRIMARY_PARENT);
String parent = (String) ((JSONObject) jsonObject.get(PARENT)).get(NODE_REF);
if (!primaryParent.equals(parent)) {
result = true;
}
}
} catch (Exception err) {
throw new AlfrescoRuntimeException("Exception whilst running UI evaluator: " + err);
}
return result;
}Example 91
| Project: RE_HeufyBot-master File: GeocodingInterface.java View source code |
private Geolocation geolocationFromJson(JSONObject object) {
Geolocation geo = new Geolocation();
geo.success = object.get("status").equals("OK");
if (!geo.success) {
return geo;
}
JSONObject firstHit = (JSONObject) ((JSONArray) object.get("results")).get(0);
geo.locality = this.siftForCreepy(firstHit);
JSONObject location = (JSONObject) ((JSONObject) firstHit.get("geometry")).get("location");
geo.latitude = Float.parseFloat(location.get("lat").toString());
geo.longitude = Float.parseFloat(location.get("lng").toString());
return geo;
}Example 92
| Project: SteakGUI-master File: ItemTaskConverter.java View source code |
public static JSONObject convert(ItemTask task) {
JSONObject taskjson = new JSONObject();
JSONArray datajson = new JSONArray();
for (Object data : task.getData()) {
datajson.add(data);
}
taskjson.put("type", task.getType());
ArrayList<ClickType> clickTypes = task.getClickType();
String clickType = "";
if (clickTypes == null) {
clickType = "ALL";
} else {
for (ClickType ct : clickTypes) {
if (clickType.equals("")) {
clickType = ct.name();
} else {
clickType = "," + ct.name();
}
}
}
taskjson.put("clicktype", clickType);
taskjson.put("data", datajson);
return taskjson;
}Example 93
| Project: stocks-master File: YahooSymbolSearch.java View source code |
public Stream<Result> search(String query) throws IOException {
// http://stackoverflow.com/questions/885456/stock-ticker-symbol-lookup-api
String searchUrl = MessageFormat.format(SEARCH_URL, URLEncoder.encode(query, StandardCharsets.UTF_8.name()));
List<Result> answer = new ArrayList<>();
try (Scanner scanner = new Scanner(new URL(searchUrl).openStream(), StandardCharsets.UTF_8.name())) {
//$NON-NLS-1$
String html = scanner.useDelimiter("\\A").next();
// strip away java script call back method
int start = html.indexOf('(');
int end = html.lastIndexOf(')');
html = html.substring(start + 1, end);
JSONObject response = (JSONObject) JSONValue.parse(html);
if (response != null) {
//$NON-NLS-1$
JSONObject resultSet = (JSONObject) response.get("ResultSet");
if (resultSet != null) {
//$NON-NLS-1$
JSONArray result = (JSONArray) resultSet.get("Result");
if (result != null) {
for (int ii = 0; ii < result.size(); ii++) answer.add(Result.from((JSONObject) result.get(ii)));
}
}
}
}
return answer.stream();
}Example 94
| Project: SyncYourCloud-master File: Config.java View source code |
@SuppressWarnings("unchecked")
public void save(ArrayList<IntDrive> drives) {
JSONArray jsondrives = new JSONArray();
Iterator<IntDrive> drivesIterator = drives.iterator();
while (drivesIterator.hasNext()) {
jsondrives.add(drivesIterator.next().savedState());
}
try {
FileWriter saved = new FileWriter(userConfigPath);
JSONValue.writeJSONString(jsondrives, saved);
saved.close();
} catch (IOException e) {
e.printStackTrace();
}
}Example 95
| Project: tabulae-master File: CellAPI2.java View source code |
public static TheList retrieveLocation(TheDictionary meta, TheList list, String resolve) throws Exception {
//if (DEBUG) Log.d(TAG, "retrieveLocation: retrieve list=" + list);
TheList ret = null;
Map<String, TheDictionary> map = new HashMap<>();
String correlation_id = Long.toString(random.nextLong());
meta.put("version", 2);
meta.put("user", user);
meta.put("method", resolve);
meta.put("tower", 1);
list.add(meta);
if (DEBUG)
Log.d(TAG, "retrieveLocation: request list=" + list);
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
try {
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setReadTimeout(5000);
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.setRequestProperty("User-Agent", "Tabulae " + org.pyneo.tabulae.BuildConfig.VERSION_NAME);
connection.setRequestProperty("X-Correlation-Id", correlation_id);
connection.setRequestProperty("Authorization", "Basic cHluZW86YU4zUGVpdjY=");
connection.setRequestMethod("POST");
try (final java.io.Writer out = new java.io.OutputStreamWriter(connection.getOutputStream())) {
list.writeJSONString(out);
out.flush();
}
int httpResponseCode = connection.getResponseCode();
//if (DEBUG) Log.d(TAG, "retrieveLocation: httpResponseCode=" + httpResponseCode);
if (httpResponseCode != 200) {
throw new Exception("httpResponseCode=" + httpResponseCode);
}
try (final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
Object obj = JSONValue.parseWithException(in);
//if (DEBUG) Log.d(TAG, "retrieveLocation: response obj=" + obj);
ret = new TheList((JSONArray) obj);
}
//if (DEBUG) Log.d(TAG, "retrieveLocation: ret=" + ret);
} finally {
try {
connection.disconnect();
} catch (Exception ignore) {
}
}
if ("estimate".equals(resolve)) {
list = ret;
} else {
for (TheDictionary entry : ret) {
map.put(entry.getIdent(), entry);
}
for (TheDictionary entry : list) {
TheDictionary r = map.get(entry.getIdent());
entry.putAll(r);
}
}
if (DEBUG)
Log.d(TAG, "retrieveLocation: response list=" + list);
return list;
}Example 96
| Project: testrail-unit-master File: CaseStore.java View source code |
private void copyJsonArrayToMap(JSONArray from, ConcurrentHashMap<CaseStoreKey, String> to, String key1, String key2, String value) {
for (int i = 0; i < from.size(); i++) {
JSONObject obj = (JSONObject) from.get(i);
Object k1 = obj.get(key1);
Object k2 = obj.get(key2);
Object v = obj.get(value);
if (k1 != null && k2 != null && v != null) {
to.putIfAbsent(new CaseStoreKey(k1.toString().trim(), k2.toString().trim()), v.toString().trim());
}
}
}Example 97
| Project: tsquery-master File: MetricsEndpoint.java View source code |
@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
try {
TsdbDataProvider dataProvider = TsdbDataProviderFactory.get();
String[] metrics = dataProvider.getMetrics();
JSONArray encoded = new JSONArray();
Collections.addAll(encoded, metrics);
doSendResponse(request, out, encoded.toJSONString());
} catch (Exception e) {
out.println(getErrorResponse(request, e));
}
out.close();
}Example 98
| Project: umt-master File: LogoUploadResult.java View source code |
public JSONObject toJson() {
JSONObject obj = new JSONObject();
obj.put("clientId", clientId);
obj.put("success", success);
obj.put("currTarget", currTarget);
obj.put("desc", desc);
if (!targetClbId.isEmpty()) {
JSONArray array = new JSONArray();
for (Entry<String, Integer> entry : targetClbId.entrySet()) {
JSONObject o = new JSONObject();
o.put("target", entry.getKey());
o.put("clbId", entry.getValue());
array.add(o);
}
obj.put("updatedList", array);
}
return obj;
}Example 99
| Project: visuwall-master File: Fs.java View source code |
String handleRequest(JsonRequest request) throws Exception {
String output = "";
JSONArray filelist = new JSONArray();
File base = new File(request.getString("path", "/"));
if (!base.exists() || !base.isDirectory()) {
throw new FileNotFoundException("Couldn't find [" + request + "]");
}
File[] files = base.listFiles();
Arrays.sort(files, new Comparator<File>() {
public int compare(File o1, File o2) {
if (o1.isDirectory() != o2.isDirectory()) {
if (o1.isDirectory()) {
return -1;
} else {
return 1;
}
}
return o1.getName().compareToIgnoreCase(o2.getName());
}
});
for (File f : files) {
JSONObject o = new JSONObject();
o.put("file", f.getName());
o.put("type", f.isDirectory() ? "D" : "F");
o.put("path", f.getCanonicalPath());
filelist.add(o);
}
return JSONValue.toJSONString(filelist);
}Example 100
| Project: Web-Karma-master File: ReadEvaluatedFile.java View source code |
public static void main(String[] args) {
/*
String dirName = "/home/pranav/workspace_karma2/karma-evaluate/evaluation-results/";
String filename = "cbev2.WebConAltNames.csv.model.MRR.json";
String file = dirName + filename;
ReadEvaluatedFile r1 = new ReadEvaluatedFile(file);
JSONObject o1 = r1.getAllObjects();
JSONArray a1 = r1.getColumnArray();
double acc = r1.getAccuracy();
double mrr = r1.getMRR();
System.out.println(o1 + "\n" + a1 + "\n" + acc + "\n" + mrr);
JSONObject c1 = (JSONObject)a1.get(0);
System.out.println();
System.out.println(c1);
JSONObject c11 = (JSONObject)c1.get("PersonInstitutionURI");
System.out.println(c11);
double rr = r1.getReciprocalRank(c11);
boolean found = r1.isFound(c11);
System.out.println();
//System.out.println(found);
System.out.println(rr +"\n" + found);
*/
}Example 101
| Project: yacy_search_server-master File: SMWListImporterFormatObsolete.java View source code |
@Override
public void run() {
try {
ConcurrentLog.info("SMWLISTSYNC", "Importer run()");
Object obj = this.parser.parse(this.importFile);
JSONObject jsonObject = (JSONObject) obj;
JSONArray items = (JSONArray) jsonObject.get("items");
@SuppressWarnings("unchecked") Iterator<JSONObject> iterator = items.iterator();
while (iterator.hasNext()) {
this.parseItem(iterator.next());
}
} catch (final IOException e) {
ConcurrentLog.logException(e);
} catch (final ParseException e) {
ConcurrentLog.logException(e);
} finally {
try {
ConcurrentLog.info("SMWLISTSYNC", "Importer inserted poison pill in queue");
this.listEntries.put(SMWListRow.POISON);
} catch (final InterruptedException e) {
ConcurrentLog.logException(e);
}
}
}