JAXB: How to list identical child elements having different tags names - jaxb

I have an XML in following format:
<servers>
<server_1>
<name>S1</name>
<user>User1</user>
<pass>pass1</pass>
</server_1>
<server_2>
<name>S2</name>
<user>User2</user>
<pass>pass2</pass>
</server_2>
<server_3>
<name>S3</name>
<user>User3</user>
<pass>pass3</pass>
</server_3>
</servers>
There can be multiple child elements under servers. And I am having trouble figuring out how to parse these using JAXB unmarshel. If the child would have identical name I could have just unmarshelled them into a list.
I also looked at #XMLAnyElement annotation which would allow me to have these elements into a list but I was facing some type cast issues since doing that gives ElementNSImpl and then I'd have to convert it to a simple Server entry class. Is that the only way to process such case?
Can't I use regex in #XMLElement's name field to populate such entries ignoring the different tags (server_1 , server_2 etc) or any other way to disregard the different child element tags.
I was using this guide to understand XMLAnyElement behavior: http://blog.bdoughan.com/2010/08/using-xmlanyelement-to-build-generic.html but this is not really for my kind of use case.
Another approach I was thinking is of modifying the parent xml itself and replacing server_X type tags with server using Java FileReaders before unmarshling the XML file.
I will appreciate help or pointing me in right direction.
Edit: I see that following code works-
..
..
#XmlAnyElement
public List<ElementNSImpl> getServer() {
return server;
}
..
..
public void printElem() {
if(server!=null) {
for(ElementNSImpl serverEntry :server) {
NodeList nodeList= ftpEntry.getChildNodes();
System.out.println("length:"+nodeList.getLength());
for(int i=0;i<nodeList.getLength()-1;i++)
System.out.println(nodeList.item(i).getNodeName()+" :"+nodeList.item(i).getTextContent());
}
}
}
But java gives warning message on using ElementNSImpl directly:
Access restriction: The type 'ElementNSImpl' is not API (restriction on required library 'C:\Program Files (x86)\Java\jre1.8.0_171\lib\rt.jar')
So I am not sure if it is okay to use ElementNSImpl like this.

Related

Antlr4 contextSuperClass to add custom properties for a two pass interpreter

I have just discovered contextSuperClass and have been experimenting with using it to provide scope annotations when building a symbol table in a first pass (I have a forward reference DSL).
I set the option in the grammar:
options {
tokenVocab=MyLexer;
language = CSharp;
contextSuperClass = interpreter.MyParserRuleContext;
}
and I have a class that derives from ParserRuleContext:
public class MyParserRuleContext : ParserRuleContext
{
public MyParserRuleContext()
{ }
public MyParserRuleContext(ParserRuleContext parent, int invokingStateNumber) : base(parent, invokingStateNumber)
{
}
public IScope ContextScope { get; set; }
}
So far so good. I use ParseTreeWalker with a listener (Enter/Exit methods) to walk the tree for the 1st pass and build the symbol table adding local scopes, etc into my ContextScope custom property.
The first issue is of course after the symbol table pass I am at the end of the token stream - the tree is walked.
The 2nd parse uses a visitor to evaluate the final result.
I have two questions:
How do I "reset" the parser so that it is at the root again without loosing scopes I have added into my custom property?
The second question is broader, but similar. Is this even a reasonable way to add scope annotations to the parse tree?
I have previously tried to use ParseTreeProperty<IScope> to add scope annotations, but the problem is similar. During the 2nd phase, the context objects provided in the visitor are not the same objects added to ParseTreeProperty<IScope> concurrent dictionary from the 1st pass - so they are not found. Between the 1st & 2nd passes I have only found parser.reset() as a way to start the parser over, and (of course) it appears to fully reset everything and I loose the any state I created in the 1st pass.
I am likely missing completely missing something here - so any help to put me in the right direction will be greatly appreciated.

xml namespace issues when building an xml file in nodejs xmlbuilder2

When I include this line in my template for nodejs xmlbuilder2:
template = {
'jcr:root': {
...
'#xmlns:jcr': 'http://www.jcp.org/jcr/1.0', // this one
...
}
}
I get the following error.
NamespaceError: The operation is not allowed by Namespaces in XML. [XMLNS] Qualified name includes a prefix but the namespace is null.
If I take it out, and paste "xmlns:jcr="..." in the xml file, and put it in AEM, it works (I should clarify, these are content fragments I'm making), but it does not show up in AEM without that line. I found this googling the error:
"if the qualified name includes a prefix, the namespace URI cannot be null or an empty string. if the reserved xmlns prefix is used, the namespace URI must match the corresponding specified system URI."
If I understand this right, my namespace URI is not null, and I am using xmlns:, so I need to change the uri to the right one? but this is the one that AEM has in its xml files when I download them.
I also think node doesn't like that 'xmlns:jcr' is an attribute of jcr:root, so it is defining jcr inside a jcr element, but again this is all copied verbatim from a file AEM made and I downloaded.

Partial objects with JAXB?

I'm working to create some services with JAX-RS, and am relatively new to JAXB (actually XML in general) so please don't assume I know the pre-requisites that I probably should know! Here's the questions: I want to send and receive "partial" objects in XML. That is, imagine one has an object (Java form, obviously) with:
class Thing { int x, String y, Customer z }
I want to be able to send an XML output that contains (dynamically chosen, so I can't use XmlTransient) just x, or just z, or x and y, but not z, or any other combination that suits my client. The point, obviously, is that sometimes the client doesn't need everything, so I can save some bandwidth (particularly with lists of deep, complex objects, which this example clearly doesn't illustrate!).
Also, for input, the same bandwidth argument applies; I would like to be able to have the client send just the particular fields that should be updated in, say, a PUT operation, and ignore the rest, then have the server "merge" those new values onto existing objects and leave the un-mentioned fields unchanged.
This seems to be supported in the Jackson JSON libraries (though I'm still working on it), but I'm having trouble finding it in JAXB. Any ideas?
One thought that I was pondering is whether one can do this in some way via Maps. If I created a Map (potentially nested Maps, for nested coplex objects) of what I want to send, could JAXB send that with a plausible structure? And if it could create such a map on input, I guess I could work through it to make the updates. Not perfect, but maybe?
And yes, I know that the "documents" that will be flying around will probably fail to comply with schemas, having missing fields and all that, but I'm ok with that, provided the infrastructure can be made to work.
Oh, and I know I could do this "manually" with SAX, StAX, or DOM parsing, but I'm hoping there's a rather more automatic way, particularly since JAXB handles the whole objects so effortlessly.
Cheers,
Toby
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
EclipseLink JAXB (MOXy) offerst this support through its object graph extension. Object graphs allow you to specify a subset of properties for the purposes of marshalling an unmarshalling. They may be created at runtime programatically:
// Create the Object Graph
ObjectGraph contactInfo = JAXBHelper.getJAXBContext(jc).createObjectGraph(Customer.class);
contactInfo.addAttributeNodes("name");
Subgraph location = contactInfo.addSubgraph("billingAddress");
location.addAttributeNodes("city", "province");
Subgraph simple = contactInfo.addSubgraph("phoneNumbers");
simple.addAttributeNodes("value");
// Output XML - Based on Object Graph
marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, contactInfo);
marshaller.marshal(customer, System.out);
or statically on the class through annotations:
#XmlNamedObjectGraph(
name="contact info",
attributeNodes={
#XmlNamedAttributeNode("name"),
#XmlNamedAttributeNode(value="billingAddress", subgraph="location"),
#XmlNamedAttributeNode(value="phoneNumbers", subgraph="simple")
},
subgraphs={
#XmlNamedSubgraph(
name="location",
attributeNodes = {
#XmlNamedAttributeNode("city"),
#XmlNamedAttributeNode("province")
}
)
}
)
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
For More Information
http://blog.bdoughan.com/2013/03/moxys-object-graphs-partial-models-on.html
http://blog.bdoughan.com/2013/03/moxys-object-graphs-inputoutput-partial.html
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html

Xceed WPF PropertyGrid : decorating property with Category : compiler error

I have basically the same question as the one I asked here. Adding the using Xceed.Wpf.Toolkit.PropertyGrid.Attributes directive solved that.
This time, the compiler does not like [Category("Shipping")] decoration.
[Category("Shipping")]
public string ShipAddress { get; set; }
How can I deduce or determine what namespace needs to be included when I run into obstacles like this?
Here are the using directives I've included already:
using Xceed.Wpf.Toolkit.PropertyGrid;
using Xceed.Wpf.Toolkit.PropertyGrid.Editors;
using Xceed.Wpf.Toolkit.PropertyGrid.Commands;
using Xceed.Wpf.Toolkit.PropertyGrid.Converters;
using Xceed.Wpf.Toolkit.PropertyGrid.Attributes;
The xaml is this:
<xctk:PropertyGrid AutoGenerateProperties="True" Name="XPG1" IsCategorized="True" />
I know this is an older question, but since it's unanswered I thought it would be helpful to provide one anyway. In this case you need the following using statement:
using System.ComponentModel;
In general, the best way to figure out what namespace or using statement you need is to look for the name of the attribute in the Object Browser under the Xceed namespace, and if you can't find it there, on Google.
One thing to remember - while it shows up as just [Category] in code, the actual name of the class will be CategoryAttribute.

How to compare 2 xsd schema files for equivalent functionality

I would like to compare 2 XSD schemas A and B to determine that all instance documents valid to schema A would also be valid to schema B. I hope to use this to prove that even though schema A and B are "different" they are effectively the same. Examples of differences this would not trigger would be Schema A uses types and Schema B declares all of it's elements inline.
I have found lots of people talking about "smart" diff type tools but these would claim the two files are different because they have different text but the resulting structure is the same. I found some references to XSOM but I'm not sure if that will help or not.
Any thoughts on how to proceed?
Membrane SOA Model - Java API for WSDL and XML Schema
package sample.schema;
import java.util.List;
import com.predic8.schema.Schema;
import com.predic8.schema.SchemaParser;
import com.predic8.schema.diff.SchemaDiffGenerator;
import com.predic8.soamodel.Difference;
public class CompareSchema {
public static void main(String[] args) {
compare();
}
private static void compare(){
SchemaParser parser = new SchemaParser();
Schema schema1 = parser.parse("resources/diff/1/common.xsd");
Schema schema2 = parser.parse("resources/diff/2/common.xsd");
SchemaDiffGenerator diffGen = new SchemaDiffGenerator(schema1, schema2);
List<Difference> lst = diffGen.compare();
for (Difference diff : lst) {
dumpDiff(diff, "");
}
}
private static void dumpDiff(Difference diff, String level) {
System.out.println(level + diff.getDescription());
for (Difference localDiff : diff.getDiffs()){
dumpDiff(localDiff, level + " ");
}
}
}
After executing you get the output shown in listing 2. It is a List of
differences between the two Schema documents.
ComplexType PersonType has changed: Sequence has changed:
Element id has changed:
The type of element id has changed from xsd:string to tns:IdentifierType.
http://www.service-repository.com/ offers an online XML Schema Version Comparator tool that displays a report of the differences between two XSD that appears to be produced from the Membrane SOA Model.
My approach to this was to canonicalize the representation of the XML Schema.
Unfortunately, I can also tell you that, unlike canonicalization of XML documents (used, as an example, to calculate a digital signature), it is not that simple or even standardized.
So basically, you have to transform both XML Schemas to a "canonical form" - whatever the tool you build or use thinks that form is, and then do the compare.
My approach was to create an XML Schema set (could be more than one file if you have more namespaces) for each root element I needed, since I found it easier to compare XSDs authored using the Russian Doll style, starting from the PSVI model.
I then used options such as auto matching substitution group members coupled with replacement of substitution groups with a choice; removal of "superfluous" XML Schema sequences, collapsing of single option choices or moving minOccurs/maxOccurs around for single item compositors, etc.
Depending on what your XSD-aware comparison tool's features are, or you settle to build, you might also have to rearrange particles under compositors such as xsd:choice or xsd:all; etc.
Anyway, what I learned after all of it was that it is extremely hard to build a tool that would work nice for all "cool" XSD features out there... One test case I remember fondly was to deal with various xsd:any content.
I do wonder though if things have changed since...

Resources