public static void main(String[] args) { // convert Java to json JSONObject root = new JSONObject(); root.put("message", "Hi"); JSONObject place = new JSONObject(); place.put("name", "World!"); root.put("place", place); String json = root.toJSONString(); System.out.println(json); System.out.println(); // convert json to Java JSONObject obj = (JSONObject) JSONValue.parse(json); String message = (String) obj.get("message"); place = (JSONObject) obj.get("place"); String name = (String) place.get("name"); System.out.println(message + " " + name); } }
public static Update fromString(String json) { try { // Read json string JSONObject obj = (JSONObject) new JSONParser().parse(json); int buildNumber = ((Long) obj.get("buildNumber")).intValue(); URL download = new URL((String) obj.get("download")); // Return cached update from json return new Update(buildNumber, download, true); } catch (IOException | ParseException ex) { Log.e(TAG, "Invalid JSON object: " + json); } // Shouldn't be returned, but it may happen return new Update(0, null, true); } }
public Number connect(Map conf, TopologyContext context) throws IOException, NoOutputException { JSONObject setupInfo = new JSONObject(); setupInfo.put("pidDir", context.getPIDDir()); setupInfo.put("conf", conf); setupInfo.put("context", context); writeMessage(setupInfo); return (Number) ((JSONObject) readMessage()).get("pid"); }
@Test public void testBasicHeader() { for (JSONObject obj : parse( "CEF:0|Security|threatmanager|1.0|100|worm successfully stopped|10|src=10.0.0.1 dst=2.1.2.2 spt=1232")) { Assert.assertEquals("Security", obj.get("DeviceVendor")); Assert.assertEquals("threatmanager", obj.get("DeviceProduct")); Assert.assertEquals("1.0", obj.get("DeviceVersion")); Assert.assertEquals("100", obj.get("DeviceEvent")); Assert.assertEquals("worm successfully stopped", obj.get("Name")); Assert.assertEquals(10, obj.get("Severity")); } }
@Test public void testPremineFromJSON() throws ParseException { JSONParser parser = new JSONParser(); JSONObject genesisMap = (JSONObject) parser.parse(TEST_GENESIS); Set keys = genesisMap.keySet(); Trie state = new SecureTrie((byte[]) null); for (Object key : keys) { JSONObject val = (JSONObject) genesisMap.get(key); String denom = (String) val.keySet().toArray()[0]; String value = (String) val.values().toArray()[0]; BigInteger wei = Denomination.valueOf(denom.toUpperCase()).value().multiply(new BigInteger(value)); AccountState acctState = new AccountState(BigInteger.ZERO, wei); state.put(Hex.decode(key.toString()), acctState.getEncoded()); } logger.info("root: " + Hex.toHexString(state.getRootHash())); assertEquals(GENESIS_STATE_ROOT, Hex.toHexString(state.getRootHash())); }
private void runMissingYear(Calendar expected, Calendar input) { SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm:ss.SSS"); for (JSONObject obj : parse("CEF:0|Security|threatmanager|1.0|100|worm successfully stopped|10|src=10.0.0.1 rt=" + sdf.format(input.getTime()) + " dst=2.1.2.2 spt=1232")) { Assert.assertEquals(expected.getTimeInMillis(), obj.get("timestamp")); Assert.assertEquals(expected.getTime(), new Date((long) obj.get("timestamp"))); } }
@Test public void shouldWriteSuccessfullyWhenMessageTimestampIsString() { List<Tuple> tuples = createTuples(1); List<JSONObject> messages = createMessages(1); // the timestamp is a String, rather than a Long messages.get(0).put(Constants.Fields.TIMESTAMP.getName(), new Long(System.currentTimeMillis()).toString()); // create the document JSONObject message = messages.get(0); String timestamp = (String) message.get(Constants.Fields.TIMESTAMP.getName()); String guid = (String) message.get(Constants.GUID); String sensorType = (String) message.get(Constants.SENSOR_TYPE); TupleBasedDocument document = new TupleBasedDocument(message, guid, sensorType, Long.parseLong(timestamp), tuples.get(0)); // create a document writer which will successfully write that document BulkDocumentWriterResults<TupleBasedDocument> results = new BulkDocumentWriterResults<>(); results.addSuccess(document); BulkDocumentWriter<TupleBasedDocument> docWriter = mock(BulkDocumentWriter.class); when(docWriter.write()).thenReturn(results); // attempt to write ElasticsearchWriter esWriter = new ElasticsearchWriter(); esWriter.setDocumentWriter(docWriter); esWriter.init(stormConf, topologyContext, writerConfiguration); BulkWriterResponse response = esWriter.write("bro", writerConfiguration, tuples, messages); // response should only contain successes assertFalse(response.hasErrors()); assertTrue(response.getSuccesses().contains(tuples.get(0))); }
@Override public JSONObject joinMessages(Map<String, Tuple> streamMessageMap, MessageGetStrategy messageGetStrategy) { JSONObject message = new JSONObject(); for (String key : streamMessageMap.keySet()) { Tuple tuple = streamMessageMap.get(key); JSONObject obj = (JSONObject) messageGetStrategy.get(tuple); message.putAll(obj); } List<Object> emptyKeys = new ArrayList<>(); for(Object key : message.keySet()) { Object value = message.get(key); if(value == null || value.toString().length() == 0) { emptyKeys.add(key); } } for(Object o : emptyKeys) { message.remove(o); } message.put(getClass().getSimpleName().toLowerCase() + ".joiner.ts", "" + System.currentTimeMillis()); return message; }
@Test public void testIp6Addr() { String rawMessage = "<174>Jan 05 2016 14:52:35 10.22.8.212 %ASA-6-302015: Built inbound UDP connection 76245506 for outside:2001:db8:85a3::8a2e:370:7334/49886 (10.22.8.110/49886) to inside:2001:0db8:85a3:0000:0000:8a2e:0370:7334/8612 (192.111.72.8/8612) (user.name)"; JSONObject asaJson = asaParser.parse(rawMessage.getBytes()).get(0); assertEquals(rawMessage, asaJson.get("original_string")); assertEquals("2001:db8:85a3::8a2e:370:7334", asaJson.get("ip_src_addr")); assertEquals("2001:0db8:85a3:0000:0000:8a2e:0370:7334", asaJson.get("ip_dst_addr")); assertEquals(49886, asaJson.get("ip_src_port")); assertEquals(8612, asaJson.get("ip_dst_port")); assertEquals(1452005555000L, asaJson.get("timestamp")); }
@Test public void testFromDump_1() throws URISyntaxException, IOException, ParseException { JSONArray dbDumpJSONArray = (JSONArray) parser.parse(testSrc); byte[] key = Hex.decode(obj.get("key").toString()); byte[] val = Hex.decode(obj.get("val").toString()); AccountState accountState1 = new AccountState(val1); assertEquals(BigInteger.valueOf(2).pow(200), accountState1.getBalance()); assertEquals("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", Hex.toHexString(accountState1.getCodeHash())); assertEquals(BigInteger.ZERO, accountState1.getNonce()); assertEquals(null, accountState1.getStateRoot());
private void testMapEnrichment(String config, String field) throws Exception { JSONObject message = getMessage(); EnrichmentConfig enrichmentConfig = JSONUtils.INSTANCE.load(config, EnrichmentConfig.class); Assert.assertNotNull(enrichmentConfig.getEnrichmentConfigs().get("stellar")); ConfigHandler handler = enrichmentConfig.getEnrichmentConfigs().get("stellar"); JSONObject enriched = enrich(message, field, handler); Assert.assertEquals(2, enriched.size()); Assert.assertEquals("stellar_test", enriched.get("stmt2.foo")); Assert.assertEquals("stellar_test".toUpperCase(), enriched.get("stmt1")); }
private void formatResponse(String result) { JSONParser parser = new JSONParser(); Object status; try { status = parser.parse(result); } catch (ParseException e) { System.err.println("Invalid response received from AM"); if (opts.verbose) { System.out.println(result); System.out.println(e.getMessage()); } return; } JSONObject root = (JSONObject) status; showMetric("AM State", root, "state"); showMetric("Target Drillbit Count", root.get("summary"), "targetBitCount"); showMetric("Live Drillbit Count", root.get("summary"), "liveBitCount"); showMetric("Unmanaged Drillbit Count", root.get("summary"), "unmanagedCount"); showMetric("Blacklisted Node Count", root.get("summary"), "blackListCount"); showMetric("Free Node Count", root.get("summary"), "freeNodeCount"); }
Object previousValue = json.get( header.getName() ); if ( previousValue == null ) { json.put( header.getName(), header.getValue() ); } else if ( previousValue instanceof List ) { List<String> list = (List<String>) previousValue; list.add( (String) previousValue ); list.add( header.getValue() ); json.put( header.getName(), list );
protected String call(HttpURLConnection conn) throws IOException, OozieClientException { if ((conn.getResponseCode() == HttpURLConnection.HTTP_OK)) { Reader reader = new InputStreamReader(conn.getInputStream(), Charsets.UTF_8); JSONObject json = (JSONObject) JSONValue.parse(reader); return (String) json.get(JsonTags.JMS_TOPIC_NAME); } else { handleError(conn); } return null; } }
@Test public void testEscaping() { for (JSONObject obj : parse( "Sep 19 08:26:10 host CEF:0|security|threatmanager|1.0|100|detected a \\ in packet|10|src=10.0.0.1 act=blocked a \\ dst=1.1.1.1")) { Assert.assertEquals("10.0.0.1", obj.get("ip_src_addr")); Assert.assertEquals("blocked a \\", obj.get("deviceAction")); Assert.assertEquals("1.1.1.1", obj.get("ip_dst_addr")); } }
@Test public void testRebalanceTopologyResourcesAndConfigs() throws Exception { jsonObject.put(Config.TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB, 768.0); JSONObject readConf = (JSONObject) parser.parse(confRaw); if (768.0 == (double) readConf.get(Config.TOPOLOGY_WORKER_MAX_HEAP_SIZE_MB)) { topologyUpdated = true; break; String componentConfRaw = readStormTopology.get_spouts().get("spout-1").get_common().get_json_conf(); JSONObject readTopologyConf = (JSONObject) parser.parse(componentConfRaw); Map<String, Double> componentResources = (Map<String, Double>) readTopologyConf.get(Config.TOPOLOGY_COMPONENT_RESOURCES_MAP); assertTrue("Topology has been updated", topologyUpdated); assertEquals("Updated CPU correct", 25.0, componentResources.get(Constants.COMMON_CPU_RESOURCE_NAME), 0.001); assertEquals("Updated Memory correct", 120.0, componentResources.get(Constants.COMMON_ONHEAP_MEMORY_RESOURCE_NAME), 0.001); assertEquals("Updated Generic resource correct", 5.0, componentResources.get("gpu.count"), 0.001);
private void checkMergedData(RawMessage m) { JSONObject message = new JSONObject(envelopedMessage); RawMessageStrategies.ENVELOPE.mergeMetadata(message, m.getMetadata(), true, new HashMap<String, Object>() {}); if(m.getMetadata().containsKey(MetadataUtil.METADATA_PREFIX + "." +Constants.Fields.ORIGINAL.getName())) { Assert.assertEquals(m.getMetadata().get(MetadataUtil.METADATA_PREFIX + "." + Constants.Fields.ORIGINAL.getName()), message.get(Constants.Fields.ORIGINAL.getName())); } Assert.assertEquals("message_val1", message.get("message_field1")); }