List of usage examples for org.json.simple JSONObject isEmpty
boolean isEmpty();
From source file:com.opensoc.enrichment.common.GenericEnrichmentBolt.java
@SuppressWarnings("unchecked") public void execute(Tuple tuple) { LOG.trace("[OpenSOC] Starting enrichment"); JSONObject in_json = null; String key = null;/*from w ww.j ava 2 s.c om*/ try { key = tuple.getStringByField("key"); in_json = (JSONObject) tuple.getValueByField("message"); if (in_json == null || in_json.isEmpty()) throw new Exception("Could not parse binary stream to JSON"); if (key == null) throw new Exception("Key is not valid"); LOG.trace("[OpenSOC] Received tuple: " + in_json); JSONObject message = (JSONObject) in_json.get("message"); if (message == null || message.isEmpty()) throw new Exception("Could not extract message from JSON: " + in_json); LOG.trace("[OpenSOC] Extracted message: " + message); for (String jsonkey : _jsonKeys) { LOG.trace("[OpenSOC] Processing:" + jsonkey + " within:" + message); String jsonvalue = (String) message.get(jsonkey); LOG.trace("[OpenSOC] Processing: " + jsonkey + " -> " + jsonvalue); if (null == jsonvalue) { LOG.trace("[OpenSOC] Key " + jsonkey + "not present in message " + message); continue; } // If the field is empty, no need to enrich if (jsonvalue.length() == 0) { continue; } JSONObject enrichment = cache.getUnchecked(jsonvalue); LOG.trace("[OpenSOC] Enriched: " + jsonkey + " -> " + enrichment); if (enrichment == null) throw new Exception("[OpenSOC] Could not enrich string: " + jsonvalue); if (!in_json.containsKey("enrichment")) { in_json.put("enrichment", new JSONObject()); LOG.trace("[OpenSOC] Starting a string of enrichments"); } JSONObject enr1 = (JSONObject) in_json.get("enrichment"); if (enr1 == null) throw new Exception("Internal enrichment is empty"); if (!enr1.containsKey(_enrichment_tag)) { enr1.put(_enrichment_tag, new JSONObject()); LOG.trace("[OpenSOC] Starting a new enrichment"); } LOG.trace("[OpenSOC] ENR1 is: " + enr1); JSONObject enr2 = (JSONObject) enr1.get(_enrichment_tag); enr2.put(jsonkey, enrichment); LOG.trace("[OpenSOC] ENR2 is: " + enr2); enr1.put(_enrichment_tag, enr2); in_json.put("enrichment", enr1); } LOG.debug("[OpenSOC] Generated combined enrichment: " + in_json); _collector.emit("message", new Values(key, in_json)); _collector.ack(tuple); if (_reporter != null) { emitCounter.inc(); ackCounter.inc(); } } catch (Exception e) { LOG.error("[OpenSOC] Unable to enrich message: " + in_json); _collector.fail(tuple); if (_reporter != null) { failCounter.inc(); } JSONObject error = ErrorGenerator.generateErrorMessage("Enrichment problem: " + in_json, e); _collector.emit("error", new Values(error)); } }
From source file:i5.las2peer.services.todolist.Todolist.java
/** * /*from ww w . j a v a 2 s.co m*/ * getData * * * @return HttpResponse * */ @GET @Path("/data") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "responseGetData") }) @ApiOperation(value = "getData", notes = "") public HttpResponse getData() { JSONObject dataJson = new JSONObject(); Connection conn = null; try { conn = dbm.getConnection(); PreparedStatement stmt = conn .prepareStatement("SELECT * FROM gamificationCAE.todolist ORDER BY id ASC"); ResultSet rs = stmt.executeQuery(); while (rs.next()) { dataJson.put(rs.getInt("id"), rs.getString("name")); } if (!dataJson.isEmpty()) { return new HttpResponse(dataJson.toJSONString(), HttpURLConnection.HTTP_OK); } return new HttpResponse("No data Found", HttpURLConnection.HTTP_OK); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return new HttpResponse("Database connection error", HttpURLConnection.HTTP_INTERNAL_ERROR); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java
@Deprecated private String getPOSTBody(JSONObject obj) { String body = "{}"; StoredPaths pan = new StoredPaths(); JSONObject returned = new JSONObject(); ArrayList<String> names = new ArrayList<>(); ArrayList<String> values = new ArrayList<>(); String originalString = ""; double similarity = 0.0, current = 0.0; if (!obj.isEmpty()) { Set keys = obj.keySet();// w w w.java 2 s.c o m Iterator iter = keys.iterator(); for (; iter.hasNext();) { String temporary = String.valueOf(iter.next()); if (temporary.startsWith("has")) names.add(temporary); } names.stream().forEach((name) -> { values.add(String.valueOf(obj.get(name))); }); } originalString = values.stream().map((value) -> value).reduce(originalString, String::concat); //Begin the initialisation process. OntModelSpec s = new OntModelSpec(PelletReasonerFactory.THE_SPEC); //s.setReasoner(PelletReasonerFactory.theInstance().create()); OntDocumentManager dm = OntDocumentManager.getInstance(); dm.setFileManager(FileManager.get()); s.setDocumentManager(dm); OntModel m = ModelFactory.createOntologyModel(s, null); //OntModel m = ModelFactory.createOntologyModel( PelletReasonerFactory.THE_SPEC ); InputStream in = FileManager.get().open(StoredPaths.casebasepath); if (in == null) { throw new IllegalArgumentException("File: " + StoredPaths.casebasepath + " not found"); } // read the file m.read(in, null); //begin building query string. String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixCasePath; queryString += "\nSELECT DISTINCT "; for (int i = 0; i < names.size(); i++) { queryString += "?param" + i + " "; } queryString += "?message ?handle ?URI ?body WHERE {"; for (int i = 0; i < names.size(); i++) { queryString += "?event base:" + names.get(i) + " ?param" + i + " . "; } queryString += "?event base:isSolvedBy ?solution . ?solution base:exposesMessage ?message . ?solution base:eventHandledBy ?handle . ?solution base:URI ?URI . ?solution base:hasPOSTBody ?body}"; try { String testString = ""; Query query = QueryFactory.create(queryString); //System.out.println(String.valueOf(query)); QueryExecution qe = QueryExecutionFactory.create(query, m); ResultSet results = qe.execSelect(); for (; results.hasNext();) { QuerySolution soln = results.nextSolution(); // Access variables: soln.get("x"); Literal lit; for (int i = 0; i < names.size(); i++) { lit = soln.getLiteral("param" + i);// Get a result variable by name. String temporary = String.valueOf(lit).substring(0, String.valueOf(lit).indexOf("^^")); testString += temporary; } String longer = testString, shorter = originalString; if (testString.length() < originalString.length()) { // longer should always have greater length longer = originalString; shorter = testString; } int longerLength = longer.length(); current = (longerLength - StringUtils.getLevenshteinDistance(longer, shorter)) / (double) longerLength; if (similarity < current) { similarity = current; returned.clear(); returned.put("message", soln.getLiteral("message").getString()); returned.put("URI", soln.getLiteral("URI").getString()); returned.put("handle", soln.getLiteral("handle").getString()); body = soln.getLiteral("body").getString(); } } } catch (Exception e) { System.out.println("Search is interrupted by an error."); } m.close(); return body; }
From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java
@Deprecated public JSONObject searchEventSolution(JSONObject obj) { StoredPaths pan = new StoredPaths(); JSONObject returned = new JSONObject(); long since = 0; long ts = 0;/* w w w. j a v a 2 s . com*/ ArrayList<String> names = new ArrayList<>(); ArrayList<String> values = new ArrayList<>(); String originalString = ""; double similarity = 0.0, current = 0.0; if (!obj.isEmpty()) { Set keys = obj.keySet(); Iterator iter = keys.iterator(); for (; iter.hasNext();) { String temporary = String.valueOf(iter.next()); if (temporary.startsWith("has")) names.add(temporary); } names.stream().forEach((name) -> { values.add(String.valueOf(obj.get(name))); }); } originalString = values.stream().map((value) -> value).reduce(originalString, String::concat); //Begin the initialisation process. OntModelSpec s = new OntModelSpec(PelletReasonerFactory.THE_SPEC); OntDocumentManager dm = OntDocumentManager.getInstance(); dm.setFileManager(FileManager.get()); s.setDocumentManager(dm); OntModel m = ModelFactory.createOntologyModel(s, null); InputStream in = FileManager.get().open(StoredPaths.casebasepath); if (in == null) { throw new IllegalArgumentException("File: " + StoredPaths.casebasepath + " not found"); } // read the file m.read(in, null); //begin building query string. String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixCasePath; queryString += "\nSELECT DISTINCT "; for (int i = 0; i < names.size(); i++) { queryString += "?param" + i + " "; } queryString += "?message ?handle ?URI WHERE {"; for (int i = 0; i < names.size(); i++) { queryString += "?event base:" + names.get(i) + " ?param" + i + " . "; } queryString += "?event base:isSolvedBy ?solution . ?solution base:exposesMessage ?message . ?solution base:eventHandledBy ?handle . ?solution base:URI ?URI}"; try { String testString = ""; Query query = QueryFactory.create(queryString); QueryExecution qe = QueryExecutionFactory.create(query, m); ResultSet results = qe.execSelect(); for (; results.hasNext();) { QuerySolution soln = results.nextSolution(); // Access variables: soln.get("x"); Literal lit; for (int i = 0; i < names.size(); i++) { lit = soln.getLiteral("param" + i);// Get a result variable by name. String temporary = String.valueOf(lit).substring(0, String.valueOf(lit).indexOf("^^")); testString += temporary; } String longer = testString, shorter = originalString; if (testString.length() < originalString.length()) { // longer should always have greater length longer = originalString; shorter = testString; } int longerLength = longer.length(); System.out.println("Similarity between:" + originalString + " and " + testString + " is:"); current = (longerLength - StringUtils.getLevenshteinDistance(longer, shorter)) / (double) longerLength; System.out.println(current + " out of 1.0."); if (similarity < current) { similarity = current; returned.clear(); returned.put("message", soln.getLiteral("message").getString()); returned.put("URI", soln.getLiteral("URI").getString()); returned.put("handle", soln.getLiteral("handle").getString()); } } } catch (Exception e) { System.out.println("Search is interrupted by an error."); } m.close(); return returned; }
From source file:com.p000ison.dev.simpleclans2.converter.Converter.java
public void convertClans() throws SQLException { ResultSet result = from.query("SELECT * FROM `sc_clans`;"); while (result.next()) { JSONObject flags = new JSONObject(); String name = result.getString("name"); String tag = result.getString("tag"); boolean verified = result.getBoolean("verified"); boolean friendly_fire = result.getBoolean("friendly_fire"); long founded = result.getLong("founded"); long last_used = result.getLong("last_used"); String flagsString = result.getString("flags"); String cape = result.getString("cape_url"); ConvertedClan clan = new ConvertedClan(tag); clan.setPackedAllies(result.getString("packed_allies")); clan.serPackedRivals(result.getString("packed_rivals")); if (friendly_fire) { flags.put("ff", friendly_fire); }//from w w w . j a v a 2 s . com if (cape != null && !cape.isEmpty()) { flags.put("cape-url", cape); } JSONParser parser = new JSONParser(); try { JSONObject object = (JSONObject) parser.parse(flagsString); String world = object.get("homeWorld").toString(); if (!world.isEmpty()) { int x = ((Long) object.get("homeX")).intValue(); int y = ((Long) object.get("homeY")).intValue(); int z = ((Long) object.get("homeZ")).intValue(); flags.put("home", x + ":" + y + ":" + z + ":" + world + ":0:0"); } clan.setRawWarring((JSONArray) object.get("warring")); } catch (ParseException e) { Logging.debug(e, true); continue; } insertClan(name, tag, verified, founded, last_used, flags.isEmpty() ? null : flags.toJSONString(), result.getDouble("balance")); String selectLastQuery = "SELECT `id` FROM `sc2_clans` ORDER BY ID DESC LIMIT 1;"; ResultSet selectLast = to.query(selectLastQuery); selectLast.next(); clan.setId(selectLast.getLong("id")); selectLast.close(); insertBB(Arrays.asList(result.getString("packed_bb").split("\\s*(\\||$)")), clan.getId()); clans.add(clan); } for (ConvertedClan clan : clans) { JSONArray allies = new JSONArray(); JSONArray rivals = new JSONArray(); JSONArray warring = new JSONArray(); for (String allyTag : clan.getRawAllies()) { long allyID = getIDByTag(allyTag); if (allyID != -1) { allies.add(allyID); } } for (String rivalTag : clan.getRawAllies()) { long rivalID = getIDByTag(rivalTag); if (rivalID != -1) { rivals.add(rivalID); } } for (String warringTag : clan.getRawWarring()) { long warringID = getIDByTag(warringTag); if (warringID != -1) { warring.add(warringID); } } if (!allies.isEmpty()) { updateClan.setString(1, allies.toJSONString()); } else { updateClan.setNull(1, Types.VARCHAR); } if (!rivals.isEmpty()) { updateClan.setString(2, rivals.toJSONString()); } else { updateClan.setNull(2, Types.VARCHAR); } if (!warring.isEmpty()) { updateClan.setString(3, warring.toJSONString()); } else { updateClan.setNull(3, Types.VARCHAR); } updateClan.setLong(4, clan.getId()); updateClan.executeUpdate(); } }
From source file:copter.WebSocketServerFactory.java
@Override public void onMessage(WebSocket conn, String message) { JSONObject res = new JSONObject(); String command = null;// w w w . j av a2 s. c o m JSONObject jsonObj = null; try { JSONParser parser = new JSONParser(); Object obj = parser.parse(message); jsonObj = (JSONObject) obj; command = (String) jsonObj.get("command"); if (command == null || command.isEmpty()) { return; } if (!command.equals(Constants.PING_COMMAND)) { logger.log("websocket message received: " + message); } switch (command) { case Constants.REBOOT_COMMAND: res.put("message", LinuxCommandsUtil.getInstance().rebootSystem()); break; case Constants.CAMERA_COMMAND: res.put("message", CameraControl.getInstance().doAction(jsonObj)); break; case Constants.GPS_COMMAND: res.put("message", GpsdConnector.getInstance().doAction(jsonObj, conn)); break; case Constants.HCSR04_COMMAND: res.put("message", HCSR04.getInstance().doAction(jsonObj, conn)); break; case Constants.MPU_COMMAND: res.put("message", MPU9150.getInstance().doAction(jsonObj, conn)); break; case Constants.ENGINE_COMMAND: Engine.getInstance().doAction(jsonObj, conn); break; case Constants.GPIO_COMMAND: res.put("message", GpioControl.getInstance().doAction(jsonObj)); break; case Constants.PING_COMMAND: res.put("status", "ok"); String ping_id = (String) jsonObj.get("ping_id"); res.put("ping_id", ping_id); break; default: res.put("message", "Unknown command '" + command + "'."); break; } } catch (Exception ex) { String err = "Json parse error: " + ex.getMessage(); logger.log(err); res.put("message", err); } if (!res.isEmpty()) { conn.send(res.toJSONString()); if (!command.equals(Constants.PING_COMMAND)) { logger.log("websocket response: " + res.toJSONString()); } } }
From source file:csiro.pidsvc.mappingstore.ManagerJson.java
@SuppressWarnings("unchecked") protected JSONObject getPidConfigImpl(String query, Object value) throws SQLException { // InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("../pid.json"); // byte[] bytes = new byte[inputStream.available()]; // inputStream.read(bytes); // String s = new String(bytes); // return s; PreparedStatement pst = null; ResultSet rsMapping = null, rsAction = null, rsHistory = null; JSONObject ret = null; JSONArray jsonArr = null;//from w w w . j a va 2s.c o m int mappingId; String mappingPath, parentPath; boolean isParentActive; try { pst = _connection.prepareStatement(query); if (value != null) { if (value instanceof Integer) pst.setInt(1, (Integer) value); else pst.setString(1, (String) value); } if (pst.execute()) { ret = new JSONObject(); for (rsMapping = pst.getResultSet(); rsMapping.next();) { String actionType = rsMapping.getString("action_type"); if (rsMapping.wasNull()) actionType = null; mappingId = rsMapping.getInt("mapping_id"); mappingPath = rsMapping.getString("mapping_path"); parentPath = rsMapping.getString("parent"); isParentActive = rsMapping.getBoolean("parent_is_active"); ret.put("mapping_id", mappingId); ret.put("mapping_path", mappingPath); ret.put("original_path", rsMapping.getString("original_path")); ret.put("type", mappingPath == null ? "Regex" : rsMapping.getString("type")); ret.put("title", mappingPath == null ? "Catch-all" : rsMapping.getString("title")); ret.put("description", rsMapping.getString("description")); ret.put("creator", rsMapping.getString("creator")); ret.put("commit_note", rsMapping.getString("commit_note")); ret.put("ended", rsMapping.getBoolean("ended")); ret.put("qr_hits", this.getTotalQrCodeHits(mappingPath)); // Parent mapping. JSONObject jsonParent = new JSONObject(); jsonParent.put("mapping_path", parentPath); jsonParent.put("title", rsMapping.getString("parent_title")); jsonParent.put("active", isParentActive); if (isParentActive) jsonParent.put("cyclic", !this.checkNonCyclicInheritance(mappingId)); jsonParent.put("graph", getMappingDependencies(mappingId, parentPath)); ret.put("parent", jsonParent); // Default action. if (actionType == null) ret.put("action", null); else { ret.put("action", JSONObjectHelper.create("type", actionType, "name", rsMapping.getString("action_name"), "value", rsMapping.getString("action_value"), "description", rsMapping.getString("default_action_description"))); } // Serialise change history. pst = _connection.prepareStatement("SELECT mapping_id, creator, commit_note, " + " to_char(date_start, 'DD/MM/YYYY HH24:MI') AS date_start, " + " to_char(date_end, 'DD/MM/YYYY HH24:MI') AS date_end " + "FROM mapping " + "WHERE mapping_path " + (mappingPath == null ? "IS NULL " : "= ? ") + "ORDER BY mapping.date_start DESC"); if (mappingPath != null) pst.setString(1, mappingPath); // History. jsonArr = new JSONArray(); if (pst.execute()) { for (rsHistory = pst.getResultSet(); rsHistory.next();) { jsonArr.add(JSONObjectHelper.create("mapping_id", rsHistory.getInt("mapping_id"), "creator", rsHistory.getString("creator"), "commit_note", rsHistory.getString("commit_note"), "date_start", rsHistory.getString("date_start"), "date_end", rsHistory.getString("date_end"))); } } ret.put("history", jsonArr); // Conditions. ret.put("conditions", getConditionsByMappingId(rsMapping.getInt("mapping_id"))); } if (value == null && (ret == null || ret.isEmpty())) { // Catch-all mapping is not defined yet. Return default. ret = JSONObjectHelper.create( "mapping_id", 0, "mapping_path", null, "original_path", null, "type", "Regex", "title", "Catch-all", "description", null, "creator", null, "commit_note", null, "ended", false, "qr_hits", 0, "parent", null, "action", JSONObjectHelper.create("type", "404", "name", null, "value", null, "description", null), "history", null, "conditions", new JSONArray()); } } } finally { if (rsMapping != null) rsMapping.close(); if (rsAction != null) rsAction.close(); if (rsHistory != null) rsHistory.close(); if (pst != null) pst.close(); } return ret; }
From source file:de.themoep.ShowItem.ShowItem.java
private String convertItem(ItemStack item, Level debugLevel) { ChatColor itemcolor = ChatColor.WHITE; JSONObject itemJson = new JSONObject(); String icon = ""; if (useIconRp) icon = iconrpmap.getIcon(item, true); //String name = idmap.getHumanName(item.getType()); String name = ""; List<String> translateWith = new ArrayList<String>(); itemJson.put("id", "minecraft:" + idmap.getMCid(item.getType())); itemJson.put("Damage", item.getDurability()); JSONObject tagJson = new JSONObject(); boolean hideEnchants = false; boolean hideAttributes = false; boolean hideUnbreakable = false; boolean hideDestroys = false; boolean hidePlacedOn = false; boolean hideVarious = false; if (item.hasItemMeta()) { ItemMeta meta = item.getItemMeta(); JSONObject displayJson = new JSONObject(); if (meta.getLore() != null && meta.getLore().size() > 0) { List<String> loreList = new ArrayList<String>(); for (String l : meta.getLore()) { loreList.add(l);// ww w. j av a 2s .c o m } displayJson.put("Lore", loreList); } try { if (meta.getItemFlags().size() > 0) { int flagBits = 0; for (ItemFlag flag : meta.getItemFlags()) switch (flag) { case HIDE_ENCHANTS: hideEnchants = true; flagBits += 1; break; case HIDE_ATTRIBUTES: hideAttributes = true; flagBits += 2; break; case HIDE_UNBREAKABLE: hideUnbreakable = true; flagBits += 4; break; case HIDE_DESTROYS: hideDestroys = true; flagBits += 8; break; case HIDE_PLACED_ON: hidePlacedOn = true; flagBits += 16; break; case HIDE_POTION_EFFECTS: hideVarious = true; flagBits += 32; break; } displayJson.put("HideFlags", flagBits); } } catch (NoSuchMethodError e) { // Catch for 1.7.3-1.7.10 servers, there are no item flags previous to 1.8! } if (meta instanceof LeatherArmorMeta) { displayJson.put("color", ((LeatherArmorMeta) meta).getColor().asRGB()); } if (item.getType().isRecord()) { itemcolor = ChatColor.AQUA; } if (spigot && meta.spigot().isUnbreakable() && !hideUnbreakable) { tagJson.put("Unbreakable", 1); } if (meta.getEnchants() != null && meta.getEnchants().size() > 0) { if (!hideEnchants) { List<JSONObject> enchList = new ArrayList<JSONObject>(); for (Map.Entry<Enchantment, Integer> entry : meta.getEnchants().entrySet()) { JSONObject enchJson = new JSONObject(); enchJson.put("id", entry.getKey().hashCode()); enchJson.put("lvl", entry.getValue()); enchList.add(enchJson); } tagJson.put("ench", enchList); } itemcolor = ChatColor.AQUA; } if (meta instanceof EnchantmentStorageMeta) { EnchantmentStorageMeta esm = (EnchantmentStorageMeta) meta; if (esm.getStoredEnchants() != null) { if (!hideVarious) { List<JSONObject> enchList = new ArrayList<JSONObject>(); for (Map.Entry<Enchantment, Integer> entry : esm.getStoredEnchants().entrySet()) { JSONObject enchJson = new JSONObject(); enchJson.put("id", entry.getKey().hashCode()); enchJson.put("lvl", entry.getValue()); enchList.add(enchJson); } tagJson.put("StoredEnchantments", enchList); } itemcolor = ChatColor.YELLOW; } } if (meta instanceof PotionMeta) { if (!hideVarious) { PotionMeta pm = (PotionMeta) meta; List<JSONObject> potionList = new ArrayList<JSONObject>(); for (PotionEffect potion : pm.getCustomEffects()) { JSONObject potionJson = new JSONObject(); potionJson.put("Id", potion.getType().hashCode()); potionJson.put("Amplifier", potion.getAmplifier()); potionJson.put("Duration", potion.getDuration()); if (potion.isAmbient()) { potionJson.put("Ambient", (byte) 1); } potionList.add(potionJson); } tagJson.put("CustomPotionEffects", potionList); } itemcolor = ChatColor.YELLOW; } if (meta instanceof BookMeta) { if (!hideVarious) { BookMeta bm = (BookMeta) meta; name = "Book"; if (bm.getTitle() != null) { tagJson.put("title", bm.getTitle()); name += ": " + bm.getTitle(); } if (bm.getAuthor() != null) { tagJson.put("author", bm.getAuthor()); if (bm.getTitle() == null) { name += " by " + bm.getAuthor(); } } } } if (meta instanceof SkullMeta) { SkullMeta sm = (SkullMeta) meta; if (sm.hasOwner()) { String owner = sm.getOwner(); if (owner != null) { translateWith.add(0, owner); /*taglist.add("SkullOwner:{Name:\\\\\"" + owner + "\\\\\",},");*/ JSONObject ownerJson = new JSONObject(); ownerJson.put("Name", owner); tagJson.put("SkullOwner", ownerJson); } /*name = owner + "'"; if(!(owner.substring(owner.length() -1).equalsIgnoreCase("s") || owner.substring(owner.length() -1).equalsIgnoreCase("x") || owner.substring(owner.length() -1).equalsIgnoreCase("z"))) name += "s"; name += " Head"; meta.setDisplayName(name);*/ } } if (meta instanceof FireworkMeta) { if (!hideVarious) { FireworkMeta fm = (FireworkMeta) meta; JSONObject fireworkJson = new JSONObject(); fireworkJson.put("Flight", fm.getPower()); List<JSONObject> explList = new ArrayList<JSONObject>(); for (FireworkEffect fe : fm.getEffects()) { JSONObject explJson = new JSONObject(); if (fe.hasFlicker()) { explJson.put("Flicker", (byte) 1); } if (fe.hasTrail()) { explJson.put("Trail", (byte) 1); } byte type = 42; switch (fe.getType()) { case BALL: type = 0; break; case BALL_LARGE: type = 1; break; case STAR: type = 2; break; case CREEPER: type = 3; break; case BURST: type = 4; break; } explJson.put("Type", type); JSONArray colorArray = new JSONArray(); for (Color c : fe.getColors()) { colorArray.add(c.asRGB()); } explJson.put("Colors", colorArray); JSONArray fadeArray = new JSONArray(); for (Color c : fe.getFadeColors()) { fadeArray.add(c.asRGB()); } explJson.put("FadeColors", fadeArray); explList.add(explJson); } fireworkJson.put("Explosions", explList); tagJson.put("Fireworks", fireworkJson); } } if (meta instanceof FireworkEffectMeta) { if (!hideVarious) { FireworkEffect fe = ((FireworkEffectMeta) meta).getEffect(); JSONObject explJson = new JSONObject(); if (fe.hasFlicker()) { explJson.put("Flicker", (byte) 1); } if (fe.hasTrail()) { explJson.put("Trail", (byte) 1); } byte type = 42; switch (fe.getType()) { case BALL: type = 0; break; case BALL_LARGE: type = 1; break; case STAR: type = 2; break; case CREEPER: type = 3; break; case BURST: type = 4; break; } explJson.put("Type", type); JSONArray colorArray = new JSONArray(); for (Color c : fe.getColors()) { colorArray.add(c.asRGB()); } explJson.put("Colors", colorArray); JSONArray fadeArray = new JSONArray(); for (Color c : fe.getFadeColors()) { fadeArray.add(c.asRGB()); } explJson.put("FadeColors", fadeArray); tagJson.put("Explosion", explJson); } } if (meta instanceof MapMeta && ((MapMeta) meta).isScaling() && !hideVarious) { tagJson.put("map_is_scaling", (byte) 1); } if (meta instanceof BannerMeta) { BannerMeta bm = (BannerMeta) meta; JSONObject blockEntityJson = new JSONObject(); DyeColor baseColor = bm.getBaseColor(); int base; if (baseColor != null) { base = baseColor.getDyeData(); } else { base = (int) item.getDurability(); } blockEntityJson.put("Base", base); List<JSONObject> patternList = new ArrayList<JSONObject>(); for (Pattern p : bm.getPatterns()) { JSONObject patternJson = new JSONObject(); patternJson.put("Pattern", p.getPattern().getIdentifier()); patternJson.put("Color", p.getColor().getDyeData()); patternList.add(patternJson); } blockEntityJson.put("Patterns", patternList); tagJson.put("BlockEntityTag", blockEntityJson); } if (meta.getDisplayName() != null) { name = ChatColor.ITALIC + meta.getDisplayName(); if (useIconRp) { displayJson.put("Name", icon + itemcolor + " " + name); } else { displayJson.put("Name", itemcolor + name); } } if (!displayJson.isEmpty()) { tagJson.put("display", displayJson); } } NbtCompound itemNbt = NbtFactory.fromItemTag(item); getLogger().log(debugLevel, "Item-Nbt: " + itemNbt.toString()); if (!itemNbt.isEmpty()) { if (!hideUnbreakable) { Byte unbreakable = itemNbt.getByte("Unbreakable", (byte) 0); if (unbreakable != 0) { tagJson.put("Unbreakable", unbreakable); } } if (!hideDestroys) { NbtList destroyNbtList = itemNbt.getList("CanDestroy", false); if (destroyNbtList != null) { List<String> destroyList = new ArrayList<String>(); for (Object destroyObj : destroyNbtList) { if (destroyObj instanceof String) { destroyList.add((String) destroyObj); } } if (destroyList.size() > 0) { tagJson.put("CanDestroy", destroyList); } } } if (!hidePlacedOn) { NbtList placeNbtList = itemNbt.getList("CanPlaceOn", false); if (placeNbtList != null) { List<String> placeList = new ArrayList<String>(); for (Object destroyObj : placeNbtList) { if (destroyObj instanceof String) { placeList.add((String) destroyObj); } } if (placeList.size() > 0) { tagJson.put("CanPlaceOn", placeList); } } } if (!hideAttributes) { NbtList attrNbtList = itemNbt.getList("AttributeModifiers", false); if (attrNbtList != null) { List<JSONObject> attrList = new ArrayList<JSONObject>(); for (Object attrObj : attrNbtList) { if (attrObj instanceof NbtCompound) { JSONObject attrJson = new JSONObject(); NbtCompound attrNbt = (NbtCompound) attrObj; attrJson.put("AttributeName", attrNbt.getString("AttributeName", "ERROR")); attrJson.put("Name", attrNbt.getString("Name", "ERROR")); String tags[] = { "Amount", "Operation", "UUIDLeast", "UUIDMost" }; for (String tag : tags) { Object value = attrNbt.get(tag); if (value == null || !(value instanceof Number)) { attrJson.put(tag, -1); } else { attrJson.put(tag, value); } } attrList.add(attrJson); } } if (attrList.size() > 0) { tagJson.put("AttributeModifiers", attrList); } } } } if (!tagJson.isEmpty()) { itemJson.put("tag", tagJson); } JSONObject hoverJson = new JSONObject(); hoverJson.put("action", "show_item"); String mojangItemJson = toMojangJsonString(itemJson.toJSONString()); getLogger().log(debugLevel, "toMojangJsonString: " + mojangItemJson); hoverJson.put("value", mojangItemJson); JSONObject nameJson = new JSONObject(); if (!name.isEmpty()) { String resultname = itemcolor + name + ChatColor.RESET; nameJson.put("text", resultname); } else { nameJson.put("translate", transmap.getKey(item)); if (!translateWith.isEmpty()) { nameJson.put("with", translateWith); } } nameJson.put("hoverEvent", hoverJson); nameJson.put("color", itemcolor.name().toLowerCase()); String lbracket = itemcolor + "["; if (useIconRp) { lbracket += icon; } JSONObject lbracketJson = new JSONObject(); lbracketJson.put("text", lbracket); lbracketJson.put("hoverEvent", hoverJson); JSONObject rbracketJson = new JSONObject(); rbracketJson.put("text", itemcolor + "]"); rbracketJson.put("hoverEvent", hoverJson); getLogger().log(debugLevel, "Json string: " + nameJson.toJSONString()); return lbracketJson.toJSONString() + "," + nameJson.toJSONString() + "," + rbracketJson.toJSONString(); }
From source file:org.apache.metron.alerts.TelemetryAlertsBolt.java
@SuppressWarnings("unchecked") public void execute(Tuple tuple) { LOG.trace("[Metron] Starting to process message for alerts"); JSONObject original_message = null; String key = null;//from w w w . j ava 2s . c o m try { key = tuple.getStringByField("key"); original_message = (JSONObject) tuple.getValueByField("message"); if (original_message == null || original_message.isEmpty()) throw new Exception("Could not parse message from byte stream"); if (key == null) throw new Exception("Key is not valid"); LOG.trace("[Metron] Received tuple: " + original_message); JSONObject alerts_tag = new JSONObject(); Map<String, JSONObject> alerts_list = _adapter.alert(original_message); JSONArray uuid_list = new JSONArray(); if (alerts_list == null || alerts_list.isEmpty()) { System.out.println("[Metron] No alerts detected in: " + original_message); _collector.ack(tuple); _collector.emit("message", new Values(key, original_message)); } else { for (String alert : alerts_list.keySet()) { uuid_list.add(alert); LOG.trace("[Metron] Checking alerts cache: " + alert); if (cache.getIfPresent(alert) == null) { System.out.println("[Metron]: Alert not found in cache: " + alert); JSONObject global_alert = new JSONObject(); global_alert.putAll(_identifier); global_alert.putAll(alerts_list.get(alert)); global_alert.put("timestamp", System.currentTimeMillis()); _collector.emit("alert", new Values(global_alert)); cache.put(alert, ""); } else LOG.trace("Alert located in cache: " + alert); LOG.debug("[Metron] Alerts are: " + alerts_list); if (original_message.containsKey("alerts")) { JSONArray already_triggered = (JSONArray) original_message.get("alerts"); uuid_list.addAll(already_triggered); LOG.trace("[Metron] Messages already had alerts...tagging more"); } original_message.put("alerts", uuid_list); LOG.debug("[Metron] Detected alerts: " + alerts_tag); _collector.ack(tuple); _collector.emit("message", new Values(key, original_message)); } /* * if (metricConfiguration != null) { emitCounter.inc(); * ackCounter.inc(); } */ } } catch (Exception e) { e.printStackTrace(); LOG.error("Failed to tag message :" + original_message); e.printStackTrace(); _collector.fail(tuple); /* * if (metricConfiguration != null) { failCounter.inc(); } */ JSONObject error = ErrorUtils.generateErrorMessage("Alerts problem: " + original_message, e); _collector.emit("error", new Values(error)); } }
From source file:org.apache.metron.enrichment.bolt.GenericEnrichmentBolt.java
@SuppressWarnings("unchecked") @Override//from ww w .j av a2 s . com public void execute(Tuple tuple) { String key = tuple.getStringByField("key"); JSONObject rawMessage = (JSONObject) tuple.getValueByField("message"); String subGroup = ""; JSONObject enrichedMessage = new JSONObject(); enrichedMessage.put("adapter." + adapter.getClass().getSimpleName().toLowerCase() + ".begin.ts", "" + System.currentTimeMillis()); try { if (rawMessage == null || rawMessage.isEmpty()) throw new Exception("Could not parse binary stream to JSON"); if (key == null) throw new Exception("Key is not valid"); String sourceType = null; if (rawMessage.containsKey(Constants.SENSOR_TYPE)) { sourceType = rawMessage.get(Constants.SENSOR_TYPE).toString(); } else { throw new RuntimeException( "Source type is missing from enrichment fragment: " + rawMessage.toJSONString()); } boolean error = false; String prefix = null; for (Object o : rawMessage.keySet()) { String field = (String) o; Object value = rawMessage.get(field); if (field.equals(Constants.SENSOR_TYPE)) { enrichedMessage.put(Constants.SENSOR_TYPE, value); } else { JSONObject enrichedField = new JSONObject(); if (value != null) { SensorEnrichmentConfig config = getConfigurations().getSensorEnrichmentConfig(sourceType); if (config == null) { LOG.error("Unable to find SensorEnrichmentConfig for sourceType: " + sourceType); error = true; continue; } config.getConfiguration().putIfAbsent(STELLAR_CONTEXT_CONF, stellarContext); CacheKey cacheKey = new CacheKey(field, value, config); try { adapter.logAccess(cacheKey); prefix = adapter.getOutputPrefix(cacheKey); subGroup = adapter.getStreamSubGroup(enrichmentType, field); enrichedField = cache.getUnchecked(cacheKey); if (enrichedField == null) throw new Exception("[Metron] Could not enrich string: " + value); } catch (Exception e) { LOG.error(e.getMessage(), e); error = true; MetronError metronError = new MetronError() .withErrorType(Constants.ErrorType.ENRICHMENT_ERROR).withThrowable(e) .withErrorFields(new HashSet() { { add(field); } }).addRawMessage(rawMessage); ErrorUtils.handleError(collector, metronError); continue; } } if (!enrichedField.isEmpty()) { for (Object enrichedKey : enrichedField.keySet()) { if (!StringUtils.isEmpty(prefix)) { enrichedMessage.put(field + "." + enrichedKey, enrichedField.get(enrichedKey)); } else { enrichedMessage.put(enrichedKey, enrichedField.get(enrichedKey)); } } } } } enrichedMessage.put("adapter." + adapter.getClass().getSimpleName().toLowerCase() + ".end.ts", "" + System.currentTimeMillis()); if (error) { throw new Exception("Unable to enrich " + rawMessage + " check logs for specifics."); } if (!enrichedMessage.isEmpty()) { collector.emit(enrichmentType, new Values(key, enrichedMessage, subGroup)); } } catch (Exception e) { handleError(key, rawMessage, subGroup, enrichedMessage, e); } }