Read nested XML to model with hasMany association, Sencha, ExtJS - xml-parsing

I am trying to parse the following xml (after hosting in my local machine) and load it to store.
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user>
<id>2</id>
<name>shameel</name>
<post>
<user_id>5</user_id>
<title>programmer</title>
<body>nothing</body>
</post>
<post>
<user_id>6</user_id>
<title>newpost</title>
<body>congrats</body>
</post>
</user>
<user>
<id>3</id>
<name>abdulls</name>
<post>
<user_id>5</user_id>
<title>programmer1</title>
<body>nothing1</body>
</post>
<post>
<user_id>6</user_id>
<title>newpost1</title>
<body>congrats1</body>
</post>
<post>
<user_id>7</user_id>
<title>newpost1</title>
<body>congrats1</body>
</post>
</user>
</users>
The models used are as follows:
Ext.define("SectionModel", {
extend : 'Ext.data.Model',
config : {
fields : [{
name : 'section',
type : 'string',
mapping : '#section'
}],
proxy : {
type : 'ajax',
url : 'http://localhost:8080/sample1.xml', //sample1.xml is the file
reader : {
type : 'xml',
rootProperty : 'configs',
record : 'navigation'
}
},
hasMany : [{
model : 'ArticlesModel',
name : 'articlesModel',
associationKey:'sections'
}]
}
});
Ext.define("ArticlesModel", {
extend : 'Ext.data.Model',
config : {
fields : [{
name : 'title',
type : 'string',
mapping : '#title'
}, {
name : 'value',
type : 'string',
mapping : '#value'
}],
proxy : {
type : 'ajax',
url : 'http://localhost:8080/sample1.xml', //sample1.xml is the file
reader : {
type : 'xml',
rootProperty : 'navigation',
record : 'section'
}
},
belongsTo : 'SectionModel'
}
});
Store used as below:
Ext.define("SectionStore", {
extend : 'Ext.data.Store',
config : {
model : 'SectionModel',
autoLoad : 'true'
}
});
I try to access the content as below:
var store = Ext.data.StoreManager.get('SectionStore');
if (!store) {
console.log("Store not found");
return;
}
store.load(function(records, operation, success) {
for (var i = 0; i < store.getCount(); i++) {
var section_title = store.getAt(i).get('section');
var subsection_val = store.getAt(i).articlesModel().get('title');//this function fails saying no "get" function for the object
}
});
Here I am able to obtain section_title. But cannot get subsection_val. I ve tried this with the proxy in store, but could not fix it. Can any one please help.

I ran into similar issues with parsing nested XML elements. Unfortunately, after much hacking around in the XML Parsing code, I eventually gave up. (Ended up writing a passthrough to our web services that would transform the response in to JSON)
You can read about my (mis)-adventures here:
http://www.sencha.com/forum/showthread.php?189537-Sencha-Touch-2.0-nested-XML-parsing

Related

Require form-urlencoded request body with swagger-core

Using Dropwizard with swagger-core and swagger-jaxrs2 2.2.6, how can you mark the requestBody of a x-www-form-urlencoded request as required?
#POST
#Path("/do-something")
#Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
#Operation(summary = "Does something")
public void doSomething(#NotNull #FormParam("what") String what) {
// ...
}
This generates the following:
"/do-something" : {
"post" : {
"summary" : "Does something",
"operationId" : "doSomething",
"requestBody" : {
/* missing here: "required": true */
"content" : {
"application/x-www-form-urlencoded" : {
"schema" : {
"required" : [ "what" ],
"type" : "object",
"properties" : {
"what" : {
"type" : "string"
}
}
}
}
}
},
"responses" : { /* ... */ }
}
},
Parameter what is required, however the requestBody as a whole is not marked as required. Generated TypeScript clients therefore allow to omit it.
I could annotate the operation with something like #RequestBody(required = true), but this disables the auto detection of the parameters.
Do you have any idea how to solve this without rewriting half the documentation manually?

How to read an aggregated entity from Odata Service SAP ui5

In OData Model V2, I'm struggling by reading the odata of my mocked server:
I want to get access to the child entity which is associated with a Parent entity.
From Open_Station I can navigate to_Order_Header:
[{
"results": [
{
"__metadata": {
"id": "http://WebService/Open_Station(Station='CHE1',Task='5246')",
"uri": "http://WebService/Open_Station(Station='CHE1',Task='5246')",
"type": "cds_zui_check_dialog.Open_StationType"
},
"Station": "CHE1",
"Task": "5246",
"to_Order_Header": {
"__deferred": {
"uri": "http://WebService/Open_Station(Station='CHE1',Task='5246')/to_Order_Header"
}
}
}
]
}
]
And from to_Order_Header, I can navigate to Order_Item or Stock:
[{
"__metadata" : {
"id" : "http://WebService/Order_Header(OrderNumber='00000000100000000853',Station='CHE1',OrderIndicator='')",
"uri" : "http://WebService/Order_Header(OrderNumber='00000000100000000853',Station='CHE1',OrderIndicator='')",
"type" : "cds_zui_check_dialog.Order_HeaderType"
},
"OrderNumber" : "00000000100000000853",
"Station" : "CHE1",
"OrderIndicator" : "",
"to_Order_Items" : {
"__deferred" : {
"uri" : "http://WebService/Order_Header(OrderNumber='00000000100000000853',Station='CHE1',OrderIndicator='')/to_Order_Items"
}
},
"to_Stock" : {
"__deferred" : {
"uri" : "http://WebService/Order_Header(OrderNumber='00000000100000000853',Station='CHE1',OrderIndicator='')/to_Stock"
}
}
]
In my controller, I have a metho ReadOdata read data like this:
ReadOdata: function()
{
var oModel = new sap.ui.model.odata.v2.ODataModel("http://WebService");
return new Promise(function(resolve, reject)
{
oModel.read("Open_Station(Station='CHE1',Task='5246')/to_Order_Header", {
success : function (data) {
resolve(data);
},
error: function (oError) {
reject(oError);
}
});
});
},
I always get a failure like this:
Request failed with status code 404: GET Open_Station(Station='CHE1',Task='5246')/to_Order_Header
- [{"code":404,"message":"Resource not found","persistent":false,"targets":["/Open_Station(Station='CHE1',Task='5246')/to_Order_Header"],"type":"Error"}]
sap.ui.model.odata.ODataMessageParser
I think the way I want to read the associated entity is wrong. Please help me.
I found a solution. It was a failure in the annotation of the Path:
Instead of writing:
oModel.read("**to_Open_Station**(Station='CHE1',Task='5246')/to_Order_Header", {
I was writing:
oModel.read("*Open_Station*(Station='CHE1',Task='5246')/to_Order_Header", {
In the MetaData, the NavigationProperty was called to_Open_Station.

Create Interactions in yMarketing with OData Service CUAN_IMPORT_SRV

I work on a SAPUI5 application (in Web IDE) which creates an interaction in Hybris Marketing. Therefore I use OData service CUAN_IMPORT_SRV. I already tried it with a simple Postman request and it worked fine. The interaction was created in Hybris Marketing.
The example JSON body for upload looks like this (oriented by Call OData Service):
{
"Id" : "",
"Timestamp" : "/Date(1506014140593)/",
"UserName" : "UNAME",
"SourceSystemId" : "ANY",
"Interactions" : [
{
"Key" : "",
"CampaignId" : "",
"CommunicationMedium" : "BUSINESS_DOCUMENT",
"ContactId" : "005056966DBE1EE4B299CD12B99F60C4",
"ContactIdOrigin" : "SAP_HYBRIS_MKT_IC",
"ContentData" : "First Event",
"ContentTitle" : "",
"InitiativeId" : "100001622",
"InitiativeVersion" : 0,
"InteractionType" : "CRM_ACTIVITY",
"IsAnonymous" : false,
"MarketingOrchestrationId" : 0,
"Quantifier" : 1,
"Timestamp" : "/Date(1506014140283)/"
}
]
}
It shall not be discussed if the data makes sense or not. It's right now just a test case. In my SAPUI5 application I started writing a simple function which shall handle the data upload. I oriented on this topic.
This is my function:
onPressScan: function() {
sap.ndc.BarcodeScanner.scan(
function(mResult) {
if (!mResult.cancelled) {
// begin POST Interaction with OData
var oModel = new sap.ui.model.odata.v2.ODataModel("https://host:port/sap/opu/odata/sap/CUAN_IMPORT_SRV/", true, "UNAME", "PASSWORD");
oModel.setHeaders({
"X-CSRF-Token" : "Fetch"
});
var jsonString = '{ "Id" : "", "Timestamp" : "/Date(1506014140591)/", "UserName" : "UNAME", "SourceSystemId" : "ANY", "Interactions" : [ ' +
'{ "Key" : "" , "CampaignId" : "" , "CommunicationMedium" : "BUSINESS_DOCUMENT" , "ContactId" : "005056966DBE1EE4B299CD12B99F60D4" ' +
', "ContactIdOrigin" : "SAP_HYBRIS_MKT_IC" , "ContentData" : "Try from Scanner App", "ContentTitle" : "Scan", "InitiativeId" : "100001622" ' +
', "InitiativeVersion" : 0, "InteractionType" : "CRM_ACTIVITY", "IsAnonymous" : false, "MarketingOrchestrationId" : 0, "Quantifier" : 1, "Timestamp" : "/Date(1506014140281)/" }]}';
var json = JSON.parse(jsonString);
// get X-CSRF-Token for POST request
oModel.read("/$metadata", null, null, true, function(oData, oResponse) {
var xcsrfToken = oResponse.headers["x-csrf-token"];
oModel.setHeaders({
"X-CSRF-Token" : xcsrfToken,
"Content-Type" : "application/json"
});
// POST interaction to yMarketing
oModel.create("/ImportHeaders", json, null, function() {
alert("Create successful");
}, function(){
alert("Create failed");
});
}, function() {
alert("Read failed");
});
}}, function(Error) {
sap.m.MessageBox.error("Scanning failed due to following error: " + Error, {
title: "Error while scanning"
});
}
);
}
When I try the application I get the following error:
When declaring the OData Model I use a correct system UNAME and PASSWORD for reading and writing. What do I do wrong?
Any hints well appreciated!
Click Chrome Icon > Options > Add this behind your target path:
--disable-web-security --user-data-dir

Loading OData without Table or List object in SAPUI5

I have 2 weeks looking for an example to understand how the OData works.
I have defined in the Manifest.json my url with the OData service
{
"_version" : "1.7.0",
"sap.app" : {
"id" : "test",
"type" : "application",
"i18n" : "i18n/i18n.properties",
"applicationVersion": {
"version" : "1.0.0"
},
"title" : "{{appTitle}}",
"description" : "{{appDescription}}",
"sourceTemplate": {
"id" : "servicecatalog.connectivityComponent",
"version" : "0.0.0"
},
"dataSources" : {
"Test" : {
"uri" : "/sap/opu/odata/sap/ZMY_SERVICE_SRV/",
"type" : "OData",
"settings" : {
"odataVersion" : "2.0",
"localUri" : "localService/metadata.xml"
}
}
}
}..
"models": {
"i18n": {
"type": "sap.ui.model.resource.ResourceModel",
"settings": {
"bundleName": "test.i18n.i18n"
}
},
"Test": {
"type": "sap.ui.model.odata.v2.ODataModel",
"settings": {
"defaultOperationMode": "Server",
"defaultBindingMode": "TwoWay",
"defaultCountMode": "None"
},
"dataSource": "Test"
},
and in my Component.js within the Init method:
init: function() {
// call the base component's init function
UIComponent.prototype.init.apply(this, arguments);
// create the views based on the url/hash
this.getRouter().initialize();
// set the device model
this.setModel(models.createDeviceModel(), "device");
var sServiceUrl = this.getMetadata().getManifestEntry("sap.app").dataSources["Test"].uri;
var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceUrl);
this.setModel(sabModel, "/Test");
sabModel.read(sServiceUrl, "Test");
}
I donĀ“t want to use a Table or a List to load the OData from Backend. I want to load the information "manually" and based on what I got from the Backend, I want to navigate to one or another View.
Debugging the result in the navigator I see the following error: Console
Checking the Error Log I can see: Error Log
If I test the service in Backend works fine: OData Service
I got:
<?xml version="1.0"?><feed xml:base="http://Myserver:8000/sap/opu/odata/sap/ZMY_SERVICE_SRV/"
xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
<id>http://Myserver:8000/sap/opu/odata/sap/ZMY_SERVICE_SRV/TestSet</id>
<title type="text">TestSet</title>
<updated>2017-10-23T20:37:55Z</updated>
-<author>
<name/>
</author>
<link title="TestSet" rel="self" href="TestSet"/>
-<entry>
<id>http://Myserver:8000/sap/opu/odata/sap/ZMY_SERVICE_SRV/TestSet('1')</id>
<title type="text">TestSet('1')</title>
<updated>2017-10-23T20:37:55Z</updated>
<category scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" term="ZMY_SERVICE_SRV.Test"/>
<link title="Test" rel="self" href="TestSet('1')"/>
-<content type="application/xml">
-<m:properties xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<d:Pernr>1</d:Pernr>
<d:Nachn>TestUser</d:Nachn>
<d:Vorna>UserTest</d:Vorna>
<d:SavingDate m:null="true"/>
<d:Option/>
<d:MsgType/>
<d:MsgNumb/>
</m:properties>
</content>
</entry>
Thank you for your help!!! Any input is more than welcome!!
try this
var oModel = this.getModel("Test");//get the model
oModel.read("/TestSet", {
method: "GET",
success: function(data) {
alert(JSON.stringify(data));
},
error: function() {
}
});
Read the API documentation about "read" method:
https://sapui5.netweaver.ondemand.com/#/api/sap.ui.model.odata.v2.ODataModel
You should not specify the service URL in read method, because it automatically gets concatenated with "sPath", which you pass as a first argument. You should use the name of entityset (is defined in $metadata) you want to read starting with slash "/".

Not being able to map model in JsonStore using JsonReader in Sencha Touch

I am facing a problem in sencha while mapping Ext.data.JsonStore model using Ext.data.JsonReader.
Json response from server (server model):
{"rows":[{"id":1,"firstname":"Bill"},{"id": 2,"firstname":"Ben"}]}
Model used in Json Store:
Ext.regModel( 'mycabinet', {
fields: [
{ name : 'DeviceId', type: 'int' },
'CabinetName']
});
json Reader code:
var iccDeviceReader = new Ext.data.JsonReader({
// metadata configuration options:
idProperty: 'id',
root: 'rows',
fields: [
{name: 'CabinetName', mapping: 'firstname'},
{name:'DeviceId',mapping:'id'}
]
});
json store code:
app.iccDS = new Ext.data.JsonStore( {
model : 'mycabinet',
sorters : 'CabinetName',
getGroupString : function(record) { return record.get('CabinetName')[0]; },
proxy : {
type: 'ajax',
url : '/icc/js/data.js',
reader:iccDeviceReader
},
autoLoad: true
} );
I am expecting that "mycabinet" model will get populated with "server model". However, mapping doesnt occur.
I even tried using convert without any success(name:'DeviceId',mapping:'id',convert: function(v){return v.id;})
Any help will be highly appreciated.
Thanks
Remove the "fields" option from your Reader and change 'CabinetName' to {name: 'CabinetName', mapping: 'firstname'} in your model config.
Also, idProperty should also go into your model config.
Following code solved my problem...
Ext.regModel( 'mycabinet', {
fields: [
{ name : 'DeviceId', type: 'int',mapping:'id' },
{name: 'CabinetName', mapping: 'firstname'}]
});
app.iccDS = new Ext.data.JsonStore( {
model : 'mycabinet',
sorters : 'CabinetName',
getGroupString : function(record) { return record.get('CabinetName')[0]; },
proxy : {
type: 'ajax',
url : '/icc/js/data.js'
},
autoLoad: true
} );
I am not using jsonReader anymore.

Resources