Java tutorial
//------------------------------------------------------------------------- // Copyright (c) Sam&Co group. All Rights Reserved. // // This software is the confidential and proprietary information of // Sam&Co. // // Project name: Sam&Co // // Platform : Java virtual machine // Language : JAVA 1.8 // // Original author: ${user} // //------------------------------------------------------------------------- // SAM&CO MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF // THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SAM&CO SHALL NOT BE // LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, // MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. // // THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE // CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE // PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT // NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE // SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE // SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE // PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). Sam&Co // SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR // HIGH RISK ACTIVITIES. //------------------------------------------------------------------------- package sam.com.training.model.util; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; import sam.com.training.PersistenceException; import sam.com.training.model.Member; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; /** * Class documentation to be filled TODO */ public class PersistenceUtil { // -------------------------------------------------------------------------- // Static members // -------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Members // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Implements interface <IMyInterface> // ------------------------------------------------------------------------- // -------------------------------------------------------------------------- // Methods // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // Any other separator such as "Utility methods", etc. // -------------------------------------------------------------------------- public static Object fromDBObjectToModelObject(DBObject aDBObject) throws PersistenceException { byte[] jsonData = aDBObject.toString().getBytes(); // create ObjectMapper instance ObjectMapper objectMapper = new ObjectMapper(); Member aMember; try { aMember = objectMapper.readValue(jsonData, Member.class); return aMember; } catch (JsonParseException jSonEx) { jSonEx.printStackTrace(); throw new PersistenceException(jSonEx); } catch (JsonMappingException jSonMappingEx) { jSonMappingEx.printStackTrace(); throw new PersistenceException(jSonMappingEx); } catch (IOException ioEx) { ioEx.printStackTrace(); throw new PersistenceException(ioEx); } } @SuppressWarnings("unchecked") public static DBObject fromModelObjectToDBObject(Object aMember) throws PersistenceException { // create ObjectMapper instance ObjectMapper objectMapper = new ObjectMapper(); try { StringWriter jSonString = new StringWriter(); objectMapper.writeValue(jSonString, aMember); Map<String, String> allContentMap = new HashMap<String, String>(); DBObject aDBObject = new BasicDBObject(); allContentMap = objectMapper.readValue(jSonString.toString().getBytes(), Map.class); aDBObject.putAll(allContentMap); return aDBObject; } catch (JsonParseException jSonEx) { jSonEx.printStackTrace(); throw new PersistenceException(jSonEx); } catch (JsonMappingException jSonMappingEx) { jSonMappingEx.printStackTrace(); throw new PersistenceException(jSonMappingEx); } catch (IOException ioEx) { ioEx.printStackTrace(); throw new PersistenceException(ioEx); } } /** * * this method is used to construct the mongodb query which uses the * $elemMatch query operator. see the detail of $elemMatch in * http://docs.mongodb * .org/manual/reference/operator/query/elemMatch/#op._S_elemMatch The * intention is to create a json structure as below based on the * input:targettedField string and paramSearch Map For instance, * targettedField: student.term.subjects paramSearch:$gte=1000,$lt=3000 * expected output { student: { term: { $elemMatch: { subjects: { * {$lt:3000,$gte:1000} } } } } } * * * @param targettedField * The field on which the criteria is applied * @param paramSearch * The map to have key-value pair of query selector and its * corresponding value About the mongodb query selector please refer * to http://docs.mongodb.org/manual/reference/operator/query/ * @return */ public static DBObject constructSelectorCriteriaQuery(String targettedField, Map<String, Object> paramSearch, QueryOperatorEnum operator) { if (paramSearch != null && paramSearch.size() > 0) { DBObject allQuerySelectorOperators = new BasicDBObject(); String[] arrFields = targettedField.split("\\."); Map<String, Object> dbObjectMaps = new HashMap<String, Object>(); if (arrFields != null && arrFields.length > 0) { BasicDBObject elMatchCriteriaWithField = null; for (int counter = arrFields.length - 1; counter >= 0; --counter) { // the last element in the array is the actual field on which the // criteria is applied if (counter == arrFields.length - 1) { // bind all query selectors operator to the targetted field // this should produce // {aField:{$gte : 1000,$lt : 3000}} BasicDBObject targettedFieldDBObject = null; Set<Entry<String, Object>> searchParams = paramSearch.entrySet(); Iterator<Entry<String, Object>> iiParams = searchParams.iterator(); while (iiParams.hasNext()) { Entry<String, Object> anEntry = iiParams.next(); if (anEntry.getKey().equals(QueryOperatorEnum.REGEX.operator)) { String strRgex = (String) anEntry.getValue(); String[] arrRegex = strRgex.split("/"); Pattern regexPattern = Pattern.compile(arrRegex[1], Pattern.CASE_INSENSITIVE); targettedFieldDBObject = new BasicDBObject(arrFields[counter], regexPattern); } else { allQuerySelectorOperators.put(anEntry.getKey(), anEntry.getValue()); targettedFieldDBObject = new BasicDBObject(arrFields[counter], allQuerySelectorOperators); } } // bind the targetted DBOject with the $elemMatch // this should produce // {$elemMatch:{aField:{$gte : 1000,$lt : 3000}}} switch (operator) { case ELEMENT_MATCH: elMatchCriteriaWithField = new BasicDBObject( QueryOperatorEnum.ELEMENT_MATCH.getOperator(), targettedFieldDBObject); dbObjectMaps.put(QueryOperatorEnum.ELEMENT_MATCH.getOperator(), elMatchCriteriaWithField); break; default: dbObjectMaps.put(QueryOperatorEnum.ELEMENT_MATCH.getOperator(), targettedFieldDBObject); break; } } else { DBObject dbObject = new BasicDBObject(arrFields[counter], dbObjectMaps.get(QueryOperatorEnum.ELEMENT_MATCH.getOperator())); dbObjectMaps.put(QueryOperatorEnum.ELEMENT_MATCH.getOperator(), dbObject); } } return (DBObject) dbObjectMaps.get(QueryOperatorEnum.ELEMENT_MATCH.operator); } } return null; } }