public void addNewUser(MongoClient mdbClient, String newUserName, String newUserPassword, DBManagement.DBRole roles) {
System.out.println("inside addNEw User method");
Map<String, String> user = new LinkedHashMap<String, String>();
user.put("createUser", newUserName);
user.put("pwd", newUserPassword);
List<Map<String, String>> listOfRoles = new ArrayList<Map<String, String>>();
Map<String, String> role1 = new LinkedHashMap<String, String>();
role1.put("role",roles.getRole());
role1.put("db", roles.getDb());
listOfRoles.add(role1);
user.put("roles", listOfRoles.toString());
System.out.println("MAP: " + user);
try{
String json = new ObjectMapper().writeValueAsString(user);
/*String json = new ObjectMapper().convertValue(user);*/
System.out.println(json);
//String jsonCommand = "{ createUser: \" + newUserName +"/" + " ," + "pwd: /" + newUserPassword + "/" + " ," + "roles : [" + roles_str + "]}" ;
String jsonCommand = json;
System.out.println("createUserString-->"+jsonCommand);
Document command = new Document(Document.parse(jsonCommand));
Document collStatsResults = mdbClient.getDatabase("admin").runCommand(command);
System.out.println(collStatsResults.toJson());
} catch(Exception e) {
System.out.println("Error " + e);
}
}
I am getting output string as -{"createUser":"demoUser2","pwd":"password","roles":"[{role=dbOwner, db=udata}]"}
Expected output- {"createUser":"demoUser2","pwd":"password","roles":[{"role":"dbOwner", "db":"udata"}]}
Firstly i used JSONObject() but it doesnt care about the json sequence ,so i tried with linkedhashMap but facing array conversion issue..can anyone help.Or is there any other way to generate json sequentially.
Related
I want to convert JSON response to Map what is the best approach to get the desired output using GSON library.
I try this and I'm getting only the ArrayList value.
Map<String, Object> map = gson.fromJson(response, HashMap.class);
ArrayList responseOptions = (ArrayList) map.get("data");
output:
[{language=Java, value=8}, {language=Ruby, value=7}, {language=Python, value=7}]
Sample JSON Response
{
"data":[
{
"language":"Java","value":"8"
},
{
"language":"Ruby","value":"7"
},
{
"language":"Python","value":"6"
}]
}
Desired Output in Map
{Java=8, Ruby=7, Python=6}
Test code
String str = "{\n" +
" \"data\":[\n" +
" {\n" +
" \"language\":\"Java\",\"value\":\"8\"\n" +
" },\n" +
" {\n" +
" \"language\":\"Ruby\",\"value\":\"7\"\n" +
" },\n" +
" {\n" +
" \"language\":\"Python\",\"value\":\"6\"\n" +
" }]\n" +
"}";
Map map = new Gson().fromJson(str, Map.class);
List data = (List) map.get("data");
Map<String, String> result = new HashMap<>();
for (Object o : data) {
Map m = (Map) o;
result.put(m.get("language").toString(), m.get("value").toString());
}
System.out.println(result);
Test result
I have a PostRequest here that I want to be able to save data to different tables. About the #RequestBody I get a JsonString that I want to split to be able to execute an INSERT INTO query.
Here is my PostRequest:
#PostMapping(value = "/config/test/{tableName}/{schemaName}")
public String postValue(#RequestBody String values, #PathVariable("tableName") String tableName, #PathVariable("schemaName") String schemaName) {
String keyString = "";
String valueString = "";
final String sql = "INSERT INTO " + schemaName + "." + tableName + "(" + keyString + ") VALUES(" + valueString + ")";
final Query query = em.createNativeQuery(sql);
query.executeUpdate();
return values;
}
And here's my JSONString:
{
"id": 23,
"indexNummer": 4,
"indexName": "Gewichtung Alter Periode ohne Maßnahmen",
"minVal": 51.0,
"maxVal": 85.0,
"indexWert": 1
}
Is there any way to split my string so that my two strings keyString, valueString are filled as follows?
keyString = "id,indexNumber,indexName,minVal,maxVal,indexValue"
valueString="23,4, "Is there any way to split my string so that my two strings keyString, valueString are filled as follows?
keyString = "id, indexNumber, indexName, minVal, maxVal, indexValue"
valueString="23, 4, "Gewichtung Alter Periode ohne Maßnahmen", 51.0, 85.0, 1"
You can convert JSONString into Map or you can directly read it is map and then do the following
#PostMapping(value = "/config/test/{tableName}/{schemaName}")
public Map postValue(#RequestBody Map<String, Object> values, #PathVariable("tableName") String tableName,
#PathVariable("schemaName") String schemaName) {
String keyString = "";
String valueString = "";
Set<String> keySet = values.keySet();
for (String key : keySet) {
// add comma after first key-value pair only.
if (keyString.length() > 0) {
keyString += ",";
valueString += ",";
}
keyString += key;
Object valueObj = values.get(key);
if (valueObj instanceof String) {
valueString = valueString + "\"" + valueObj.toString() + "\"";
} else if (valueObj instanceof Integer) {
Integer valueInt = (Integer) valueObj;
valueString = valueString + valueInt;
} else if (valueObj instanceof Double) {
Double valueDouble = (Double) valueObj;
valueString = valueString + valueDouble;
}
}
final String sql = "INSERT INTO " + schemaName + "." + tableName + "(" + keyString + ") VALUES(" + valueString + ")";
final Query query = em.createNativeQuery(sql);
query.executeUpdate();
return values;
}
Use com.fasterxml.jackson.databind.ObjectMapper as below:
ObjectMapper mapper =new ObjectMapper();
String string="{\r\n"
+ " \"id\": 23,\r\n"
+ " \"indexNummer\": 4,\r\n"
+ " \"indexName\": \"Gewichtung Alter Periode ohne Maßnahmen\",\r\n"
+ " \"minVal\": 51.0,\r\n"
+ " \"maxVal\": 85.0,\r\n"
+ " \"indexWert\": 1\r\n"
+ "}";
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
};
HashMap<String, String> map = mapper.readValue(string, typeRef);
String keys = map.keySet().stream().collect(Collectors.joining(","));
String values = map.values().stream().collect(Collectors.joining(","));
System.out.println(keys);
System.out.println(values);
Output :
indexNummer,maxVal,minVal,indexName,id,indexWert
4,85.0,51.0,Gewichtung Alter Periode ohne Maßnahmen,23,1
I am having a JSON data as shown below:
{
"table" : "customer",
"uniqueColumn" : "customer",
"uniqueColVal" : "cust_786",
"columns" :
[{
"column_1" : "column_1 Val",
"column_2" : "column_2 Val",
"column_..." : "column_... Val",
"column_..." : "column_... Val",
"column_..." : "column_... Val",
"column_n" : "column_n Val"
}]
}
I need a query to be executed and should be in the below form
UPDATE customer SET column_1 = 'column_1 Val', column_2 = 'column_2 Val', column_... = 'column_... Val', column_n = 'column_n Val' WHERE customer = 'cust_786';
I am using Spring MVC for processing this and the code I wrote is as follows. It is not complete.
#Override
public Map<String, Object> updateTabColumnValues(Map<String, Object> data)
{
Map<String, Object> response = new HashMap();
try
{
String table= data.get("table").toString();
String uniqueid = data.get("uniqueid").toString();
if (table!=null && uniqueid !=null)
{
String column = null, columnVal = null, updateColumn = null, updateColumnVal = null;
JSONObject jsonObj = new JSONObject(data);
JSONArray columnsToUpdate = jsonObj.getJSONArray("columns");
for (int i = 0; i < columnsToUpdate.length(); i++)
{
if (i == columnsToUpdate.length() - 1)
{
JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
column = json_Obj.keys().next().toString();
columnVal = json_Obj.getString(column).toString();
updateColumn = updateColumn + column.toString();
updateColumnVal = updateColumnVal + " = " + columnVal.toString() + "'";
}
}
System.out.println("UPDATE " + table+ " SET " + updateColumn +" = " + updateColumnVal + " WHERE " + data.get("uniqueColumn").toString() +" = '" + data.get("uniqueColVal").toString() +"';");
}
else
{
response.put("status", false);
LOGGER.info("Failed to get table>>> " + table+ " OR uniqueid >>> " + uniqueid);
}
}
catch (Exception e)
{
response.put("status", false);
LOGGER.error("Error #editLayerAttributeByUniqueID ", e);
System.err.println("Error #editLayerAttributeByUniqueID " + e);
}
return response;
}
It would be very much helpful if someone could help me out here. Thanks in advance.
I could find a satisfying answer at the end. Please follow the below instructions.
You need to import some packages and I am mentioning the Maven repository for the same below. Add the dependency in your pom.xml
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
<!-- For PostgreSQL Database connectivity -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>
Now Import the packages in your Impl file as follows:
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.jdbc.core.JdbcTemplate;
The logic is explained in the below code
public JdbcTemplate getJdbcTemplate()
{
return jdbcTemplate;
}
#Override
//Defines a Map named as updateTabColumnValues to get data from client
public Map<String, Object> updateTabColumnValues(Map<String, Object> data)
{
//Defines a Map named as response to send data to client
Map<String, Object> response = new HashMap();
try
{
String table = data.get("table").toString();
String uniqueColumn = data.get("uniqueColumn").toString();
String uniqueValue = data.get("uniqueValue").toString();
if ((uniqueColumn != null && uniqueValue != null) && table != null)
{
String column;
String columnVal;
String keyValuePair = "";
String query = null;
JSONObject jsonObj = new JSONObject(data);
//Gets values in the key columns to columnsToUpdate
JSONArray columnsToUpdate = jsonObj.getJSONArray("columns");
//Loops each elements with in the array
if (columnsToUpdate.length() > 0)
{
for (int i = 0; i < columnsToUpdate.length(); i++)
{
if (i == columnsToUpdate.length() - 1)
{
//Create Key Value pair without adding comma at the end
JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
column = json_Obj.keys().next();
columnVal = json_Obj.getString(column);
keyValuePair = keyValuePair + column + " = '" + columnVal + "'";
}
else
{
//Create Key Value pair with comma at the end
JSONObject json_Obj = columnsToUpdate.getJSONObject(i);
column = json_Obj.keys().next();
columnVal = json_Obj.getString(column);
keyValuePair = keyValuePair + column + " = '" + columnVal + "' , ";
}
}
int queryValidator = -1;
query = "UPDATE " + table +" SET "+ keyValuePair + " WHERE " + uniqueColumn + " = '" + uniqueValue +"';";
LOGGER.info("Query is >>> " + query);
//Uses getJdbcTemplate() to run query
queryValidator = getJdbcTemplate().update(query);
//Validating the query execution status with database
if (queryValidator >= 0)
{
response.put(stateOfstatus,true);
}
else
{
response.put(stateOfstatus,false);
}
}
else
{
response.put(stateOfstatus, false);
}
}
else
{
response.put(stateOfstatus, false);
LOGGER.info("Failed to get table >>> " + table + " OR uniqueColumn >>> " + uniqueColumn + " OR uniqueValue >>>" + uniqueValue);
}
}
catch (Exception e)
{
response.put(stateOfstatus, false);
LOGGER.error("Error in updateTabColumnValues ", e);
response.put("message", e);
}
return response;
}
This was an RnD related task taken under a special usecase. The above logic perfectly and effectivelty delivers the output.
I'm trying to compare my Input XML to an expected TXT
But somehow it fails and I have no clue why. I think this is because I'm writing a negative test (expected TXT contains error message, which is produced by xquery due to invalid inputs)
Comparing two XMLs are working(without negative test).
public void testHeader(String inputHeaderFileName, String expectedResultFileName) throws Exception {
HashMap<String, Object> xqueryParametersMap = new HashMap<String, Object>();
xqueryParametersMap.put("udgHeader", db.parse(getFileFromTestDataBasePath(inputHeaderFileName)));
this.test(xqueryParametersMap, expectedResultFileName);
}
public void test(Map<String, Object> xqueryParametersMap, String expectedResultFileName) throws Exception {
String expectedOutput = readFile(testDataBasePath + File.separator + expectedResultFileName, encoding);
String result = transform(xqueryParametersMap).xmlText(new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(2));
if (printTransformedXmlToConsoleBoolean) System.out.println(result);
Diff diff = new Diff(expectedOutput, result);
diff.overrideDifferenceListener(new IgnoreTextAndAttributeValuesDifferenceListener());
assertTrue("Grundstruktur des Resultats ist anders als in '" + expectedResultFileName + "' erwartet!\n\n" + diff + "\n\n", diff.similar());
DetailedDiff detailDiff = new DetailedDiff(compareXML(expectedOutput, result));
#SuppressWarnings("unchecked")
List<Difference> allDifferences = detailDiff.getAllDifferences();
assertEquals("Tatsaechliches Ergebnis weicht von '" + expectedResultFileName + "' ab!\n\n" + detailDiff + "\n\n", 0, allDifferences.size());
}
private XmlObject transform(Map<String, Object> xqueryParametersMap) throws Exception {
XmlObject xmlObject = XmlObject.Factory.newInstance();
XmlOptions options = new XmlOptions();
Map<String, Object> paramMap = new HashMap<String, Object>();
Iterator<Entry<String, Object>> it = xqueryParametersMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> pairs = it.next();
Object value = pairs.getValue();
String key = pairs.getKey();
if (value instanceof Document) {
XmlObject inputXml = XmlObject.Factory.parse(getStringFromDocument((Document) value));
paramMap.put(key, getXmlObject(inputXml));
} else if (value instanceof String) {
XmlString string = XmlString.Factory.newInstance();
string.setStringValue(value.toString());
paramMap.put(key, string);
}
}
String xqueryFileContent = readFile(xQueryUnderTestPath, encoding);
options.setXqueryVariables(paramMap);
xqueryFileContent = xqueryFileContent.replaceAll("(?s)\\s*?\\(:.*?:\\)", "");
XmlObject[] resultsObjects = xmlObject.execQuery(xqueryFileContent, options);
if (resultsObjects.length < 1)
{
//throw new NoResultException();
throw new Exception("Xquery transformation did not return a result");
}
else if (resultsObjects.length > 1)
{
//throw new NonUniqueResultException("result size is '" + resultsObjects.length + "'");
throw new Exception("Xquery transformation did return more than one result: " + resultsObjects.length);
}
else return resultsObjects[0];
}
'
The test:
public void testRecipientListNegative() throws Exception {
recipientTester.testHeader("input.xml", "expected.txt");
}
Stacktrace:
org.apache.xmlbeans.XmlRuntimeException: weblogic.xml.query.exceptions.XQueryUserException: line 29, column 5: fase: Unknown msg-name/recipient combination ['ARS_XYZ'/'ESM']! Please check fase recipient list.
at weblogic.xml.query.runtime.core.Error.fetchNext(Error.java:61)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.IfThenElse.fetchNext(IfThenElse.java:91)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.IfThenElse.fetchNext(IfThenElse.java:91)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.constructor.AtomicElementConstructor.fetchNext(AtomicElementConstructor.java:129)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.constructor.SuperElementConstructor.getPhase2(SuperElementConstructor.java:388)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.matEverything(PartMatElemConstructor.java:123)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.fetchNext(PartMatElemConstructor.java:197)
at weblogic.xml.query.iterators.GenericIterator.peekNext(GenericIterator.java:163)
at weblogic.xml.query.runtime.constructor.SuperElementConstructor.getPhase2(SuperElementConstructor.java:388)
at weblogic.xml.query.runtime.constructor.PartMatElemConstructor.fetchNext(PartMatElemConstructor.java:229)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.LetIterator.fetchNext(LetIterator.java:133)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.LetIterator.fetchNext(LetIterator.java:133)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.xdbc.iterators.ItemIterator.fetchNext(ItemIterator.java:86)
at weblogic.xml.query.iterators.LegacyGenericIterator.next(LegacyGenericIterator.java:109)
at weblogic.xml.query.runtime.qname.InsertNamespaces.fetchNext(InsertNamespaces.java:216)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at weblogic.xml.query.runtime.core.ExecutionWrapper.fetchNext(ExecutionWrapper.java:88)
at weblogic.xml.query.iterators.GenericIterator.next(GenericIterator.java:104)
at org.apache.xmlbeans.impl.store.XqrlImpl$SegmentedIterator.next(XqrlImpl.java:1656)
at org.apache.xmlbeans.impl.store.XqrlImpl.loadTokenStream(XqrlImpl.java:1410)
at org.apache.xmlbeans.impl.store.XqrlImpl.loadTokenStream(XqrlImpl.java:1383)
at org.apache.xmlbeans.impl.store.XqrlImpl.executeQueryToXmlObjects(XqrlImpl.java:1575)
at org.apache.xmlbeans.impl.store.XqrlImpl.access$000(XqrlImpl.java:53)
at org.apache.xmlbeans.impl.store.XqrlImpl$CompiledQuery.objectExecute(XqrlImpl.java:302)
at org.apache.xmlbeans.impl.store.Query.objectExecQuery(Query.java:80)
at org.apache.xmlbeans.impl.store.Xobj.exec_query(Xobj.java:2525)
at org.apache.xmlbeans.impl.values.XmlObjectBase.execQuery(XmlObjectBase.java:525)
at de.db.udg.componenttest.XQueryTester.transform(XQueryTester.java:271)
at de.db.udg.componenttest.XQueryTester.test(XQueryTester.java:210)
at de.db.udg.componenttest.XQueryTester.testHeader(XQueryTester.java:172)
at XQueryTest.testRecipientListNegative(XQueryTest.java:38)
the lines which are failing according to stacktrace:
this.test(xqueryParametersMap, expectedResultFileName);
String result = transform(xqueryParametersMap).xmlText(new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(2));
XmlObject[] resultsObjects = xmlObject.execQuery(xqueryFileContent, options);
I have a HashMap
HashMap<String, String> cntrlInfo = new HashMap<String, String>();
in this map some values are there I need to read the value one by one i want store the values in string.
for example {GBP,001,101,CHDP}
now I would like to store
String ccy=GBP; how i can assign the values in string
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
HashMap<String, String> cntrlInfo = new HashMap<String, String>();
cntrlInfo.put("A", "GBP");
cntrlInfo.put("B", "001");
cntrlInfo.put("C", "101");
cntrlInfo.put("D", "CHDP");
StringBuilder sb = new StringBuilder();
for (String val : cntrlInfo.values()) {
sb.append(val);
}
System.out.println("sb = " + sb);
String ccy = sb.substring(sb.indexOf("GBP"), sb.indexOf("GBP") + 3);
String foo = sb.substring(sb.indexOf("001"), sb.indexOf("001") + 3);
String bar = sb.substring(sb.indexOf("101"), sb.indexOf("101") + 3);
String f = sb.substring(sb.indexOf("CHDP"), sb.indexOf("CHDP") + 4);
System.out.println("ccy = " + ccy);
System.out.println("foo = " + foo);
System.out.println("bar = " + bar);
System.out.println("f = " + f);
}
}