Rendering XML data in GWT application - gwt

I have an XML object which comes as the response from a web service. I obtain the XML data using
Document xmlDoc = XMLParser.parse( response );
What is the easier and better way to render the xmlDoc in my DialogBox widget?
EDIT
Am having an XML object. I want to render the data inside a panel and show it on the GUI. Hope this helps.
To put in a better way,
Is it possible to directly add XML document to a panel in GWT, or we should parse the same and build the panel ourselves?
Thanks.

you have to parse the web service response
Document messageDom = XMLParser.parse( response );
Then, you can get the node value by
String nodeValue = "";
final NodeList nlist = messageDom.getElementsByTagName( tagName );
if (nlist == null || nlist.getLength() <= 0)
nodeValue = "";
else
nodeValue = nlist.item(0).getFirstChild().getNodeValue();
from here, you can now set panel component value to nodeValue

Related

xPages REST Service Results into Combobox or Typeahead Text Field

I've read all the documentation I can find and watched all the videos I can find and don't understand how to do this. I have set up an xPages REST Service and it works well. Now I want to place the results of the service into either a combobox or typeahead text field. Ideally I would like to know how to do it for both types of fields.
I have an application which has a view containing a list of countries, another view containing a list of states, and another containing a list of cities. I would like the first field to only display the countries field from the list of data it returns in the XPages REST Service. Then, depending upon which country was selected, I would like the states for that country to be listed in another field for selection, etc.
I can see code for calling the REST Service results from a button, or from a dojo grid, but I cannot find how to call it to populate either of the types of fields identified above.
Where would I call the Service for the field? I had thought it would go in the Data area, but perhaps I've just not found the right syntax to use.
November 6, 2017:
I have been following your suggestion, but am still lost as can be. Here's what I currently have in my code:
x$( "#{id:ApplCountry}" ).select2({
placeholder: "select a country",
minimumInputLength: 2,
allowClear : true,
multiple: false,
ajax: {
dataType: 'text/plain',
url: "./Application.xsp/gridData",
quietMillis: 250,
data: function (params) {
return {
search:'[name=]*'+params.term+'*',
page: params.page
};
},
processResults: function (data, page) {
var data = $.map(data, function (obj) {
obj.id = obj.id || obj["#entityid"];
obj.text = obj.text || obj.name;
return obj;
});
},
return {results: data};
}
}
});
I'm using the dataType of 'text/plain' because that was what I understood I should use when gathering data from a domino application. I have tried changing this to json but it makes no difference.
I'm using processResults because I understand this is what should be used in version 4 of select2.
I don't understand the whole use of the hidden field, so I've stayed away from that.
No matter what I do, although my REST service works if I put it directly in the url, I cannot get any data to display in the field. All I want to display in the field is the country code of the document, which is in the field named "name" (not my choice, it's how it came before I imported the data from MySQL.
I have read documentation and watched videos, but still don't really understand how everything fits together. That was my problem with the REST service. If you use it in Dojo, you just put the name of the service in a field on the Dojo element and it's done, so I don't understand why all the additional coding for another type of domino element. Shouldn't it work the same way?
I should point out that at some points it does display the default message, so it does find the field. Just doesn't display the country selections.
I think the issue may be that you are not returning SelectItems to your select2, and that is what it is expecting. When I do something like you are trying, I actually use a bean to generate the selection choices. You may want to try that or I'm putting in the working part of my bean below.
The Utils.getItemValueAsString is a method I use to return either the string value of a field, or if it is not on the document/empty/null an empty string. I took out an if that doesn't relate to this, so there my be a mismatch, but I hope not.
You might be able to jump directly to populating the arrayList, but as I recall I needed to leverage the LinkedHashMap for something.
You should be able to do the same using SSJS, but since that renders to Java before executing, I find this more efficient.
For label/value pairs:
LinkedHashMap lhmap = new LinkedHashMap();
Document doc = null;
Document tmpDoc = null;
allObjects.addElement(doc);
if (dc.getCount() > 0) {
doc = dc.getFirstDocument();
while (doc != null) {
lhmap.put(Utils.getItemValueAsString(doc, LabelField, true), Utils.getItemValueAsString(doc, ValueField, true));
}
tmpDoc = dc.getNextDocument(doc);
doc.recycle();
doc = tmpDoc;
}
}
List<SelectItem> options = new ArrayList<SelectItem>();
Set set = lhmap.entrySet();
Iterator hsItr = set.iterator();
while (hsItr.hasNext()) {
Map.Entry me = (Map.Entry) hsItr.next();
// System.out.println("after: " + hStr);
SelectItem option = new SelectItem();
option.setLabel(me.getKey() + "");
option.setValue(me.getValue() + "");
options.add(option);
}
System.out.println("About to return from generating");
return options;
}
I ended up using straight up SSJS. Worked like a charm - very simple.

How to edit pasted content using the Open XML SDK

I have a custom template in which I'd like to control (as best I can) the types of content that can exist in a document. To that end, I disable controls, and I also intercept pastes to remove some of those content types, e.g. charts. I am aware that this content can also be drag-and-dropped, so I also check for it later, but I'd prefer to stop or warn the user as soon as possible.
I have tried a few strategies:
RTF manipulation
Open XML manipulation
RTF manipulation is so far working fairly well, but I'd really prefer to use Open XML as I expect it to be more useful in the future. I just can't get it working.
Open XML Manipulation
The wonderfully-undocumented (as far as I can tell) "Embed Source" appears to contain a compound document object, which I can use to modify the copied content using the Open XML SDK. But I have been unable to put the modified content back into an object that lets it be pasted correctly.
The modification part seems to work fine. I can see, if I save the modified content to a temporary .docx file, that the changes are being made correctly. It's the return to the clipboard that seems to be giving me trouble.
I have tried assigning just the Embed Source object back to the clipboard (so that the other types such as RTF get wiped out), and in this case nothing at all gets pasted. I've also tried re-assigning the Embed Source object back to the clipboard's data object, so that the remaining data types are still there (but with mismatched content, probably), which results in an empty embedded document getting pasted.
Here's a sample of what I'm doing with Open XML:
using OpenMcdf;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
...
object dataObj = Forms.Clipboard.GetDataObject();
object embedSrcObj = dateObj.GetData("Embed Source");
if (embedSrcObj is Stream)
{
// read it with OpenMCDF
Stream stream = embedSrcObj as Stream;
CompoundFile cf = new CompoundFile(stream);
CFStream cfs = cf.RootStorage.GetStream("package");
byte[] bytes = cfs.GetData();
string savedDoc = Path.GetTempFileName() + ".docx";
File.WriteAllBytes(savedDoc, bytes);
// And then use the OpenXML SDK to read/edit the document:
using (WordprocessingDocument openDoc = WordprocessingDocument.Open(savedDoc, true))
{
OpenXmlElement body = openDoc.MainDocumentPart.RootElement.ChildElements[0];
foreach (OpenXmlElement ele in body.ChildElements)
{
if (ele is Paragraph)
{
Paragraph para = (Paragraph)ele;
if (para.ParagraphProperties != null && para.ParagraphProperties.ParagraphStyleId != null)
{
string styleName = para.ParagraphProperties.ParagraphStyleId.Val;
Run run = para.LastChild as Run; // I know I'm assuming things here but it's sufficient for a test case
run.RunProperties = new RunProperties();
run.RunProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("test"));
}
}
// etc.
}
openDoc.MainDocumentPart.Document.Save(); // I think this is redundant in later versions than what I'm using
}
// repackage the document
bytes = File.ReadAllBytes(savedDoc);
cf.RootStorage.Delete("Package");
cfs = cf.RootStorage.AddStream("Package");
cfs.Append(bytes);
MemoryStream ms = new MemoryStream();
cf.Save(ms);
ms.Position = 0;
dataObj.SetData("Embed Source", ms);
// or,
// Clipboard.SetData("Embed Source", ms);
}
Question
What am I doing wrong? Is this just a bad/unworkable approach?

How to retrieve the value from the data attribute in node js via form submit with method post

How to get the value from the data attribute in node js via form submit.
I want to get a 2nd information from user!
My first try was this:
Clientside:
input(type="submit" ,name="responseValue" , value="yes", data="question1" )
input(type="submit" ,name="responseValue" , value="no", data="question2" )
Serverside:
//works ok
var responseValue = req.body.responseValue;
//following does not work
var questionNumber = req.body.data
Is there any solution for this without a hidden field ?
You can concatenate string in the value field and then separate it at server side.
Your client side may look like this.
input(type="submit",name="responseValue", value="yes,question1")
Then at server side you can separate the string responseValue by the index of ','.

Open xml encoding

Im using Open XML SDK to read and write information to custom xml parts in a Word document.
Im serializing a xml structure into a class , modifying the data and serializing it back into the document.
Example code
DocumentFormat.OpenXml.Packaging.CustomXmlPart myPart = GetCustomXmlPart(mainPart, AITNamespaces.SiteDataNameSpace);
StreamReader myStrR = new System.IO.StreamReader(myPart.GetStream());
string myXML = myStrR.ReadToEnd();
sitedata = ObjectXMLSerializer<WDSiteData>.LoadString(myXML);
Site selSite = _applicationService.GetApplicationData().Sites.Find(item => item.Id == siteId);
sitedata.SiteId= selSite.Id;
sitedata.SiteName = "ööööaaaaaåååå"; // selSite.SiteName;
myXML = ObjectXMLSerializer<WDSiteData>.GetXMLString(sitedata);
myPart = GetCustomXmlPart(wordProcDocument.MainDocumentPart, AITNamespaces.SiteDataNameSpace);
using (StreamWriter sw = new StreamWriter(myPart.GetStream(FileMode.Create)))
{
sw.Write(myXML);
}
My problem is that the national characters become encoded and the text "ööööaaaaaåååå" is displayed in the word document as "????????aaaaa????????"
The actual encoding is done
myXML = ObjectXMLSerializer<WDSiteData>.GetXMLString(sitedata);
Anyone has a clue on how to go about handling national characters this way.
For whom it concerns , my trouble was that in my serializer the encoding was fixed
return ASCIIEncoding.ASCII.GetString(memStream.ToArray());
When i changed to
return ASCIIEncoding.UTF8.GetString(memStream.ToArray());
all is well.

How to send a POJO as a callback param using PrimeFaces' RequestContext?

I can send callback param(s) and it works perfectly as long as I am only sending some primitive types like String. But the same thing does not work for even the simplest POJO. PrimeFaces guide says that the RequestContext.addCallbackParam() method can handle POJOs and it coverts them into JSON. I don't know why it's not working in my case.
Has anybody done that?
Solution found! ---------------------------------------------------------------------
I did some research and found the answer to this question.
And the solution was to use some JSON library (right now I am using GSON) to convert Java objects to JSON objects.
new Gson().toJson(someJavaObj)
returns string. Just send the string as the param and on the client side using js' eval or some js library's function to turn that into JSON again.
Actually, it was pretty clean and simple.
Sorry I actually did not post the solution. Below is the my solution -
Action method in the backing bean -
public void retrievePieData() {
List<String> categories = new ArrayList<String>();
categories.add("Electronic");
categories.add("Food");
categories.add("Liguor");
categories.add("Stationary");
categories.add("Mechanical");
List<Integer> itemCounts = new ArrayList<Integer>();
itemCounts.add(5);
itemCounts.add(20);
itemCounts.add(1);
itemCounts.add(50);
itemCounts.add(10);
RequestContext reqCtx = RequestContext.getCurrentInstance();
reqCtx.addCallbackParam("categories", new Gson().toJson(categories));
reqCtx.addCallbackParam("itemCounts", new Gson().toJson(itemCounts));
}
PrimeFaces p:commandButton in the view -
<p:commandLink action="#{pieDataProvider.retrievePieData}" oncomplete="feedPieData(xhr, status, args);" value="Pie chart demo" update="pieData" />
Javascript function -
function feedPieData(xhr, status, args) {
var categories = eval('(' + args.categories + ')');
var itemCounts = eval('(' + args.itemCounts + ')');
options.xAxis.categories = categories;
var series = {
data: []
};
series.name = new Date().toString();
series.data = itemCounts;
options.series = [series];
chart = new Highcharts.Chart(options);
}
I would really appreciate and welcome any suggestion or opinion.
Thank you!