List of usage examples for com.mongodb.util JSON parse
public static Object parse(final String jsonString)
Parses a JSON string and returns a corresponding Java object.
From source file:calliope.core.database.MongoConnection.java
License:Open Source License
/** * PUT a json file to the database using dbase, docid and version * @param collName the name of the collection * @param dbase the name of the database * @param docid the document identifier// w w w.java 2 s . c om * @param version the version of the document * @param json the json to put there * @return the server response */ @Override public String putToDb(String collName, String dbase, String docid, String version, String json) throws DbException { try { DBObject doc = (DBObject) JSON.parse(json); doc.put(JSONKeys.DOCID, docid); connect(); DBObject query = getThreeFieldQuery(JSONKeys.DBASE, dbase, JSONKeys.DOCID, docid, JSONKeys.VERSION1, version); DBCollection coll = getCollectionFromName(collName); WriteResult result = coll.update(query, doc, true, false); //return removeFromDb( path ); return result.toString(); } catch (Exception e) { throw new DbException(e); } }
From source file:calliope.core.database.MongoConnection.java
License:Open Source License
/** * PUT a new json file to the database//from w ww .j a v a 2 s .c o m * @param collName the name of the collection * @param json the json to put there * @return the server response */ @Override public String addToDb(String collName, String json) throws DbException { try { DBObject doc = (DBObject) JSON.parse(json); connect(); DBCollection coll = getCollectionFromName(collName); if (doc.containsField(JSONKeys._ID)) { Object id = doc.get(JSONKeys._ID); DBObject query = new BasicDBObject(JSONKeys._ID, id); if (query != null) { WriteResult result = coll.update(query, doc, true, false); return result.toString(); } else throw new Exception("Failed to update object " + id); } else { WriteResult result = coll.insert(doc, WriteConcern.ACKNOWLEDGED); // return the new document's id ObjectId id = (ObjectId) doc.get("_id"); JSONObject jDoc = (JSONObject) JSONValue.parse(result.toString()); jDoc.put("_id", id.toString()); return jDoc.toJSONString(); } } catch (Exception e) { throw new DbException(e); } }
From source file:calliope.db.MongoConnection.java
License:Open Source License
/** * PUT a json file to the database// ww w . j a v a 2 s . c om * @param collName the name of the collection * @param docID the docid of the resource * @param json the json to put there * @return the server response */ @Override public String putToDb(String collName, String docID, String json) throws AeseException { try { docIDCheck(collName, docID); DBObject doc = (DBObject) JSON.parse(json); doc.put(JSONKeys.DOCID, docID); connect(); DBCollection coll = getCollectionFromName(collName); DBObject query = new BasicDBObject(JSONKeys.DOCID, docID); WriteResult result = coll.update(query, doc, true, false); //return removeFromDb( path ); return result.toString(); } catch (Exception e) { throw new AeseException(e); } }
From source file:calliope.db.MongoConnection.java
License:Open Source License
/** * Check that the database response is OK * @param response the json response from the MongoDB * @return true if its OK was 1.0 or the response has an _id field *///from w w w . jav a 2 s .c o m private boolean checkResponse(String response) { DBObject doc = (DBObject) JSON.parse(response); Object value = doc.get("ok"); if (value instanceof Double && ((Double) value).doubleValue() == 1.0) return true; else { value = doc.get("_id"); if (value != null) return true; else return false; } }
From source file:calliope.export.PDEFArchive.java
License:Open Source License
/** * Remove fields that will be added by the database after import * @param json the original JSON string// w w w. j a v a 2s . com * @return a possibly modified JSON string with the fields removed */ private String removeTabooFields(String json) { boolean changed = false; DBObject jdoc = (DBObject) JSON.parse(json); for (int i = 0; i < tabooFields.length; i++) { if (jdoc.containsField(tabooFields[i])) { jdoc.removeField(tabooFields[i]); changed = true; } } if (changed) json = jdoc.toString(); return json; }
From source file:cfel.servlet.ServiceServlet.java
License:Open Source License
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/* w w w.j av a2s . co m*/ * * Insert a new resource */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String type = request.getParameter("type"); String id = request.getParameter("id"); String data = request.getParameter("data"); System.out.println("doPost: type=" + type + " id=" + id + " data=" + data); if ("file".equals(type)) { // Save a file with id doPut(request, response); return; } DBCollection collection = mDS.getCollection(type); if (collection == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown collection %s", type)); return; } String action = request.getParameter("action"); if (action != null) { // Manipulate database if ("update".equals(action)) { String query = request.getParameter("query"); String update = request.getParameter("update"); String upsert = request.getParameter("upsert"); String multi = request.getParameter("multi"); DBObject queryObj = null; if (id != null) { queryObj = new BasicDBObject("_id", new ObjectId(id)); } else if (query != null) { queryObj = (DBObject) JSON.parse(query); } DBObject updateObj = update != null ? (DBObject) JSON.parse(update) : null; if (queryObj == null || updateObj == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No query or update parameters"); return; } sendJSON(collection.update(queryObj, updateObj, "true".equals(upsert), "true".equals(multi)), response); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown action %s", action)); } return; } if (data == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No data specified"); return; } // Insert a document DBObject dataObject = (DBObject) JSON.parse(data); Object dataID = dataObject.get("_id"); if (dataID != null && collection.findOne(dataID) != null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Duplicated id"); return; } collection.insert(dataObject); sendJSON(dataObject, response); }
From source file:cfel.servlet.ServiceServlet.java
License:Open Source License
/** * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse) * /*from w ww. ja v a 2s . c o m*/ * Update a resource with id */ protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String type = request.getParameter("type"); String id = request.getParameter("id"); String data = request.getParameter("data"); System.out.println("doPut: type=" + type + " id=" + id); if ("file".equals(type)) { // Save a file if (id == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No file id specified"); return; } InputStream is = null; try { mDS.saveFile(id, is = request.getInputStream(), request.getContentType()); } finally { if (is != null) { is.close(); } } return; } DBCollection collection = mDS.getCollection(type); if (collection == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown collection %s", type)); return; } if (data == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No data specified"); return; } // Update a document DBObject dataObject = (DBObject) JSON.parse(data); Object idObj = dataObject.get("_id"); // = id in source if (idObj == null && id != null) { idObj = new ObjectId(id); // = id in URI } if (idObj == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No document id specified"); return; } collection.update(new BasicDBObject("_id", idObj), dataObject, true, false); sendJSON(dataObject, response); }
From source file:ch.bfh.uniboard.persistence.mongodb.PersistedPost.java
License:GNU General Public License
/** * Method allowing to convert the current PersistedPost to the format supported by the database * @return a DBObject format of the PersistedPost *//*from w ww . j a v a2s. c o m*/ public BasicDBObject toDBObject() { BasicDBObject doc = new BasicDBObject(); //Save raw message doc.put("message", Base64.encode(message)); //Check if message is a JSON message DBObject jsonMessageContent = null; try { jsonMessageContent = (DBObject) JSON.parse(new String(message, "UTF-8")); } catch (JSONParseException | UnsupportedEncodingException ex) { Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Message is not a JSON string {0}", ex.getMessage()); } if (jsonMessageContent != null) { //save message as JSON content DBObject jsonMessage = new BasicDBObject("searchable-message", jsonMessageContent); doc.putAll(jsonMessage); } //Prepares the Alpha attributes BasicDBObject alphaList = new BasicDBObject(); for (Entry<String, Value> entry : alpha.getEntries()) { alphaList.put(entry.getKey(), entry.getValue().getValue()); } doc.put("alpha", alphaList); //Prepares the Beta attributes BasicDBObject betaList = new BasicDBObject(); for (Entry<String, Value> entry : beta.getEntries()) { betaList.put(entry.getKey(), entry.getValue().getValue()); } doc.put("beta", betaList); return doc; }
From source file:cn.b2b.index.product.create.ProductDataFromDB.java
public ProductBean getProductData(DBObject obj) { if (obj == null) { return null; }/*from w w w . ja va 2 s . co m*/ ProductBean product = new ProductBean(); product.setId(toInt(obj.get("_id"))); int userid = toInt(obj.get("uid")); product.setUserid(userid); product.setState((byte) toInt(obj.get("ss"))); if (companyMap.get(userid) != null && companyMap.get(userid).getAuditState() == 0) { product.setState((byte) 0); } product.setAuditstate((byte) toInt(obj.get("wait"))); String title = String.valueOf(obj.get("titl")); if (title != null) { product.setTitle(title); } else { product.setTitle(""); } String content = toString(obj.get("con")); if (content != null) { if (content.length() > 500) { product.setContent(content.substring(0, 500)); } else { product.setContent(content); } } else { product.setContent(""); } product.setIndustryid(toInt(obj.get("inid"))); String tradeid = this.getTrade(toInt(obj.get("tr1"))); product.setTradeid(tradeid); product.setKeyword1(toString(obj.get("k1"))); product.setKeyword2(toString(obj.get("k2"))); product.setKeyword3(toString(obj.get("k3"))); product.setProvince(toInt(obj.get("prov"))); product.setCity(toInt(obj.get("city"))); String pic = toString(obj.get("pic1")); if (pic != null && pic.trim().length() > 0) { product.setHaspic(true); product.setPic("http://files.b2b.cn/product/ProductImages/" + pic); } else { product.setPic("http://img.b2b.cn/default/20120217/images/nop2.png"); product.setHaspic(false); } product.setPrice(toString(obj.get("pric"))); String p_property = toString(obj.get("pro")); String t_property = toString(obj.get("tpro")); DBObject json_p_property = null; try { json_p_property = (DBObject) JSON.parse(p_property); } catch (Exception ex) { product.setNotfindproperties(1); ex.printStackTrace(); } DBObject json_t_property = null; try { json_t_property = (DBObject) JSON.parse(t_property); } catch (Exception ex) { product.setNotfindproperties(1); ex.printStackTrace(); } product.setBrand(this.getProperty(json_p_property, "P1")); product.setSpec(this.getProperty(json_p_property, "P3")); product.setUnit(this.getProperty(json_t_property, "T35")); product.setMincount(this.getProperty(json_t_property, "T1")); product.setInsertdate(toDatetime(toInt(obj.get("atim")))); product.setUpdatedate(toDatetime(toInt(obj.get("utim")))); product.setOuttime(toDatetime(toInt(obj.get("utim")))); product.setUrl("http://detail.b2b.cn/product/" + product.getId() + ".html"); if (certiMap.get(userid) != null) { product.setLicense(1); } else { product.setLicense(0); } if (companyMap.get(userid) != null) { product.setCompany(companyMap.get(userid)); } else { product.setCompany(null); } product.setDatatype(2); product.setBuslincese(linceseMap.get(userid) == null ? 0 : 1); return product; }
From source file:cn.cnic.bigdatalab.flume.sink.mongodb.EventParser.java
License:Apache License
public Object parseValue(final FieldDefinition fd, final String stringValue) { if (fd == null || fd.getType() == null) { try {//from w w w.j a va2 s. c o m return JSON.parse(stringValue); } catch (JSONParseException ex) { // XXX: Default to String log.trace("Could not parse as JSON, defaulting to String: {}", stringValue); return stringValue; } } switch (fd.getType()) { case DOUBLE: return Double.parseDouble(stringValue); case STRING: return stringValue; case OBJECT: case ARRAY: // TODO: should we use customizable array representation? // TODO: should we check that the result is indeed an array or object? return JSON.parse(stringValue); case BINARY: SimpleFieldDefinition sfd = (SimpleFieldDefinition) fd; final String encoding = (sfd.getEncoding() == null) ? DEFAULT_BINARY_ENCODING : sfd.getEncoding().toLowerCase(Locale.ENGLISH); if ("base64".equals(encoding)) { return BaseEncoding.base64().decode(stringValue); } else { throw new UnsupportedOperationException("Unsupported encoding for binary type: " + encoding); } // TODO: case "UNDEFINED": case OBJECTID: return new ObjectId(stringValue); case BOOLEAN: return Boolean.parseBoolean(stringValue); case DATE: DateFormat dateFormat = ((DateFieldDefinition) fd).getDateFormat(); if (dateFormat == null) { if (StringUtils.isNumeric(stringValue)) { return new Date(Long.parseLong(stringValue)); } else { return ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(stringValue).toDate(); } } else { try { return dateFormat.parse(stringValue); } catch (ParseException ex) { // XXX: Default to string log.warn("Could not parse date, defaulting to String: {}", stringValue); return stringValue; } } case NULL: // TODO: Check if this is valid return null; // TODO: case "REGEX": // TODO: case "JAVASCRIPT": // TODO: case "SYMBOL": // TODO: case "JAVASCRIPT_SCOPE": case INT32: return Integer.parseInt(stringValue); case INT64: return Long.parseLong(stringValue); case DOCUMENT: return populateDocument((DocumentFieldDefinition) fd, stringValue); default: throw new UnsupportedOperationException("Unsupported type: " + fd.getType().name()); } }