List of usage examples for org.json.simple JSONArray add
public boolean add(E e)
From source file:luceneprueba.Reader.java
public void searchOnIndex(String wordQuery, String date) { // Parse a simple query that searches for "text": QueryParser parser = new QueryParser("review", analyzer); Query query;//w ww. j ava 2 s. com try { query = parser.parse("date: \"+" + date + "\" AND " + cleanInput(wordQuery)); ScoreDoc[] hits = indexSearcher.search(query, 60).scoreDocs; if (hits.length == 0) { //System.out.println("[Search] No se han encontrado coincidencias."); } else { //System.out.println("[Search] Se han encontrado: " + hits.length + " coincidencias."); JSONArray reviews = new JSONArray(); for (ScoreDoc hit : hits) { Document hitDoc = indexSearcher.doc(hit.doc); //System.out.println(i+".- Score: " + hit.score + ", Doc: " + hitDoc.get("movieId") + ", path: " + hitDoc.get("path") + ", Tile review: " + hitDoc.get("title")); JSONObject json = new JSONObject(); json.put("date", hitDoc.get("date")); json.put("genre", hitDoc.get("genre")); json.put("review", hitDoc.get("review")); json.put("score", hitDoc.get("score")); reviews.add(json); } try (FileWriter file = new FileWriter( "files/output/top-k/reviews_" + date.replace(" ", "") + ".json")) { file.write(reviews.toJSONString()); file.flush(); //indexReader.close(); } } } catch (ParseException | IOException ex) { Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex); for (StackTraceElement st : ex.getStackTrace()) { System.out.println(st.toString()); } System.out.println(ex.getLocalizedMessage()); } }
From source file:be.iminds.aiolos.ui.DemoServlet.java
private void getComponentDetails(PrintWriter writer, String componentId, String version, String nodeId) { JSONObject componentInfo = new JSONObject(); componentInfo.put("componentId", componentId); componentInfo.put("version", version); PlatformManager platform = platformTracker.getService(); if (platform != null) { ComponentInfo c = platform.getComponent(componentId, version, nodeId); componentInfo.put("name", c.getName()); // use name as id instead of UUID NodeInfo ni = platform.getNode(nodeId); componentInfo.put("nodeId", ni.getName()); JSONArray services = new JSONArray(); for (ProxyInfo p : platform.getProxies(c)) { JSONObject serviceInfo = new JSONObject(); String serviceId = p.getServiceId(); // make the serviceId cleaner for demo StringTokenizer st = new StringTokenizer(serviceId, ","); String cleanServiceId = ""; while (st.hasMoreTokens()) { String service = st.nextToken(); int startIndex = service.lastIndexOf('.'); int endIndex = service.indexOf('-'); if (startIndex != -1 && endIndex != -1) { cleanServiceId += service.substring(startIndex + 1, endIndex); } else if (startIndex != -1) { cleanServiceId += service.substring(startIndex + 1); }// w w w . ja v a 2 s.co m if (st.hasMoreTokens()) { cleanServiceId += ","; } } serviceInfo.put("serviceId", cleanServiceId); ServiceInfo s = null; for (ServiceInfo si : p.getInstances()) { if (si.getComponent().equals(c)) { s = si; break; } } if (s != null) { ServiceMonitorInfo smi = platform.getServiceMonitorInfo(s); if (smi != null) { JSONArray methods = new JSONArray(); for (MethodMonitorInfo mmi : smi.getMethods()) { JSONObject method = new JSONObject(); method.put("methodName", mmi.getName()); method.put("time", floatFormat.format(mmi.getTime())); method.put("arg", intFormat.format(mmi.getArgSize())); method.put("ret", intFormat.format(mmi.getRetSize())); methods.add(method); } serviceInfo.put("methods", methods); } } services.add(serviceInfo); } componentInfo.put("services", services); } writer.write(componentInfo.toJSONString()); }
From source file:com.aerothai.database.os.OsService.java
public JSONObject GetOsAll() throws Exception { Connection dbConn = null;/* w w w. jav a2s . c o m*/ JSONObject obj = new JSONObject(); JSONArray objList = new JSONArray(); int no = 1; //obj.put("draw", 2); obj.put("tag", "list"); obj.put("msg", "error"); obj.put("status", false); try { dbConn = DBConnection.createConnection(); Statement stmt = dbConn.createStatement(); String query = "SELECT * FROM os"; System.out.println(query); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { JSONObject jsonData = new JSONObject(); jsonData.put("id", rs.getInt("idos")); jsonData.put("name", rs.getString("name")); jsonData.put("no", no); objList.add(jsonData); no++; } obj.put("msg", "done"); obj.put("status", true); obj.put("data", objList); } catch (SQLException sqle) { throw sqle; } catch (Exception e) { // TODO Auto-generated catch block if (dbConn != null) { dbConn.close(); } throw e; } finally { if (dbConn != null) { dbConn.close(); } } return obj; }
From source file:hd3gtv.mydmam.db.orm.CassandraOrm.java
public void pushColumn(String rowkey, Integer ttl, String name, Object o) throws InvalidClassException, ConnectionException { if (rowkey == null) { return;/*from w w w . j a va 2 s .c o m*/ } if (rowkey.equals("")) { return; } if (mutator == null) { mutator = CassandraDb.prepareMutationBatch(); } if (ttl == 0) { ttl = null; } if (o == null) { mutator.withRow(columnfamily, rowkey).putColumn(name, null_value, ttl); } else if (o instanceof String) { if (((String) o).equals(null_value)) { StringBuffer sb = new StringBuffer(); sb.append("String value equals to null String reference : security problem ?"); sb.append("["); sb.append(rowkey); sb.append("]"); sb.append(name); throw new InvalidClassException(o.getClass().getName(), sb.toString()); } mutator.withRow(columnfamily, rowkey).putColumn(name, (String) o, ttl); } else if (o instanceof byte[]) { mutator.withRow(columnfamily, rowkey).putColumn(name, (byte[]) o, ttl); } else if (o instanceof Integer) { mutator.withRow(columnfamily, rowkey).putColumn(name, (Integer) o, ttl); } else if (o instanceof Long) { mutator.withRow(columnfamily, rowkey).putColumn(name, (Long) o, ttl); } else if (o instanceof Boolean) { if ((Boolean) o) { mutator.withRow(columnfamily, rowkey).putColumn(name, "true", ttl); } else { mutator.withRow(columnfamily, rowkey).putColumn(name, "false", ttl); } } else if (o instanceof Date) { mutator.withRow(columnfamily, rowkey).putColumn(name, (Date) o, ttl); } else if (o instanceof Float) { mutator.withRow(columnfamily, rowkey).putColumn(name, String.valueOf((Float) o), ttl); } else if (o instanceof Double) { mutator.withRow(columnfamily, rowkey).putColumn(name, String.valueOf((Double) o), ttl); } else if (o instanceof UUID) { mutator.withRow(columnfamily, rowkey).putColumn(name, (UUID) o, ttl); } else if (o instanceof JSONObject) { mutator.withRow(columnfamily, rowkey).putColumn(name, ((JSONObject) o).toJSONString(), ttl); } else if (o instanceof JSONArray) { mutator.withRow(columnfamily, rowkey).putColumn(name, ((JSONArray) o).toJSONString(), ttl); } else if (o instanceof InetAddress) { mutator.withRow(columnfamily, rowkey).putColumn(name, ((InetAddress) o).getHostAddress(), ttl); } else if (o instanceof StringBuffer) { mutator.withRow(columnfamily, rowkey).putColumn(name, ((StringBuffer) o).toString(), ttl); } else if (o instanceof Calendar) { mutator.withRow(columnfamily, rowkey).putColumn(name, ((Calendar) o).getTimeInMillis(), ttl); } else if (o instanceof String[]) { JSONArray ja = new JSONArray(); String[] o_str = (String[]) o; for (int pos = 0; pos < o_str.length; pos++) { ja.add(o_str[pos]); } mutator.withRow(columnfamily, rowkey).putColumn(name, ja.toJSONString(), ttl); } else if (o instanceof Serializable) { mutator.withRow(columnfamily, rowkey).putColumn(name, serialize(o), ttl); } else if (o instanceof Enum) { mutator.withRow(columnfamily, rowkey).putColumn(name, serialize(o), ttl); } else { StringBuffer sb = new StringBuffer(); sb.append("Class type is not managed for this record "); sb.append("["); sb.append(rowkey); sb.append("]"); sb.append(name); throw new InvalidClassException(o.getClass().getName(), sb.toString()); } }
From source file:com.aerothai.database.building.BuildingService.java
public JSONObject GetBuildingAll() throws Exception { Connection dbConn = null;//from w w w.j a va 2s .com JSONObject obj = new JSONObject(); JSONArray objList = new JSONArray(); int no = 1; //obj.put("draw", 2); obj.put("tag", "list"); obj.put("msg", "error"); obj.put("status", false); try { dbConn = DBConnection.createConnection(); Statement stmt = dbConn.createStatement(); String query = "SELECT * FROM building"; System.out.println(query); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { JSONObject jsonData = new JSONObject(); jsonData.put("id", rs.getInt("idbuilding")); jsonData.put("name", rs.getString("name")); jsonData.put("no", no); objList.add(jsonData); no++; } obj.put("msg", "done"); obj.put("status", true); obj.put("data", objList); } catch (SQLException sqle) { throw sqle; } catch (Exception e) { // TODO Auto-generated catch block if (dbConn != null) { dbConn.close(); } throw e; } finally { if (dbConn != null) { dbConn.close(); } } return obj; }
From source file:csiro.pidsvc.mappingstore.ManagerJson.java
@SuppressWarnings("unchecked") public JSONObject getLookups(int page, String namespace) throws SQLException { PreparedStatement pst = null; ResultSet rs = null;//from w ww. java 2s . co m JSONObject ret = new JSONObject(); final int pageSize = 20; try { String query = ""; if (namespace != null && !namespace.isEmpty()) query += " AND ns ILIKE ?"; query = "SELECT COUNT(*) FROM lookup_ns" + (query.isEmpty() ? "" : " WHERE " + query.substring(5)) + ";\n" + "SELECT * FROM lookup_ns" + (query.isEmpty() ? "" : " WHERE " + query.substring(5)) + " ORDER BY ns LIMIT " + pageSize + " OFFSET " + ((page - 1) * pageSize) + ";"; pst = _connection.prepareStatement(query); for (int i = 1, j = 0; j < 2; ++j) { // Bind parameters twice to two almost identical queries. if (namespace != null && !namespace.isEmpty()) pst.setString(i++, "%" + namespace.replace("\\", "\\\\") + "%"); } if (pst.execute()) { rs = pst.getResultSet(); rs.next(); ret.put("count", rs.getInt(1)); ret.put("page", page); ret.put("pages", (int) Math.ceil(rs.getFloat(1) / pageSize)); JSONArray jsonArr = new JSONArray(); for (pst.getMoreResults(), rs = pst.getResultSet(); rs.next();) { jsonArr.add(JSONObjectHelper.create("ns", rs.getString("ns"), "type", rs.getString("type"))); } ret.put("results", jsonArr); } } finally { if (rs != null) rs.close(); if (pst != null) pst.close(); } return ret; }
From source file:com.nubits.nubot.tasks.SubmitLiquidityinfoTask.java
private String reportTier2() { String toReturn = ""; if (SessionManager.sessionInterrupted()) return ""; //external interruption ApiResponse balancesResponse = Global.exchange.getTrade().getAvailableBalances(Global.options.getPair()); if (balancesResponse.isPositive()) { PairBalance balance = (PairBalance) balancesResponse.getResponseObject(); Amount NBTbalance = balance.getNBTAvailable(); Amount PEGbalance = balance.getPEGAvailableBalance(); double buyside = PEGbalance.getQuantity(); double sellside = NBTbalance.getQuantity(); //Log balances JSONObject latestBalances = new JSONObject(); latestBalances.put("time_stamp", Utils.getTimestampLong()); JSONArray availableBalancesArray = new JSONArray(); JSONObject NBTBalanceJSON = new JSONObject(); NBTBalanceJSON.put("amount", sellside); NBTBalanceJSON.put("currency", NBTbalance.getCurrency().getCode().toUpperCase()); JSONObject PEGBalanceJSON = new JSONObject(); PEGBalanceJSON.put("amount", buyside); PEGBalanceJSON.put("currency", PEGbalance.getCurrency().getCode().toUpperCase()); availableBalancesArray.add(PEGBalanceJSON); availableBalancesArray.add(NBTBalanceJSON); latestBalances.put("balance-not-on-order", availableBalancesArray); if (SessionManager.sessionInterrupted()) return ""; //external interruption //now read the existing object if one exists JSONObject balanceHistory = null; try {/*from w w w . j a v a2 s .co m*/ balanceHistory = getBalanceHistory(); } catch (ParseException pe) { LOG.error("Unable to parse " + this.jsonFile_balances); } JSONArray balances = new JSONArray(); try { //object already exists in file balances = (JSONArray) balanceHistory.get("balances"); } catch (Exception e) { } //add the latest orders to the orders array balances.add(latestBalances); //then save logBalanceJSON(balanceHistory); buyside = Utils.round(buyside * Global.conversion, 2); if (Global.options.isSubmitliquidity()) { //Call RPC if (SessionManager.sessionInterrupted()) return ""; //external interruption toReturn = sendLiquidityInfoImpl(buyside, sellside, 2); } } else { LOG.error(balancesResponse.getError().toString()); } return toReturn; }