Converting xml to domain object in Grails - grails

I'm a grails newbie working on a project for fun. I'm serializing a class like this:
def msg = (listing as XML).toString()
the trying to deserialize a class using the XMLSlurper like this:
def root = new XmlSlurper().parseText(listingString)
def sellerNode = root.seller
I'm trying to reconstruct this object:
Listing{
Date dateCreated
String description
Date endDateTime
String name
Float startingPrice
Customer winner
static hasMany = [bids: Bid] // B-4
static belongsTo = [seller: Customer]
}
}
from this xml:
<?xml version="1.0" encoding="UTF-8"?>
<listing>
<bids>
<bid>
<amount>10.5</amount>
<bidder>
<accountExpired>false</accountExpired>
<accountLocked>false</accountLocked>
<dateCreated/>
<emailAddress>validguy#valid.com</emailAddress>
<enabled>false</enabled>
<password>secret</password>
<passwordExpired>false</passwordExpired>
<username>validguy</username>
</bidder>
<dateCreated>2012-04-08 21:16:41.423 CDT</dateCreated>
<listing/>
</bid>
<bid>
<amount>10.0</amount>
<bidder>
<accountExpired>false</accountExpired>
<accountLocked>false</accountLocked>
<dateCreated/>
<emailAddress>validguy#valid.com</emailAddress>
<enabled>false</enabled>
<password>secret</password>
<passwordExpired>false</passwordExpired>
<username>validguy</username>
</bidder>
<dateCreated>2012-04-08 21:16:41.415 CDT</dateCreated>
<listing/>
</bid>
</bids>
<dateCreated/>
<description>A test listing</description>
<endDateTime>2012-04-09 21:16:41.407 CDT</endDateTime>
<name>Default</name>
<seller>
<accountExpired>false</accountExpired>
<accountLocked>false</accountLocked>
<dateCreated/>
<emailAddress>validguy#valid.com</emailAddress>
<enabled>false</enabled>
<password>secret</password>
<passwordExpired>false</passwordExpired>
<username>validguy</username>
</seller>
<startingPrice>10.0</startingPrice>
<wasNotificationSent>false</wasNotificationSent>
<winner>
<accountExpired>false</accountExpired>
<accountLocked>false</accountLocked>
<dateCreated/>
<emailAddress>validguy#valid.com</emailAddress>
<enabled>false</enabled>
<password>secret</password>
<passwordExpired>false</passwordExpired>
<username>validguy</username>
</winner>
</listing>
First I'm having issues getting to the values of each node. I've tried def seller = new Customer(name:sellerNode.#username) but that doesn't work since I assume #username needs to be an attribute and not an element.
Second, do I have to parse this xml "by hand"? Isn't there a better way to deserialize this xml automatically?
I already looked at a couple of posts and including this one: Import XML into a Grails Domain Class however as you can see, my xml doesn't have attributes like the xml in this post.
Thanks,

If the source of the XML is a web request, you can add parseRequest: true to the UrlMapping for your controller, grails will parse the XML request automatically. The XML will be presented as params and you can do data binding the same as any other request.
If you're getting the XML from another source, take a look at the XML to parameter map conversion in the class XMLParsingParameterCreationListener.groovy.

I did look at the class aTaylor suggested but due to time constraints I ended up parsing the xml with the slurper this way:
def listing = new XmlSlurper().parseText(listingXML)
def winner = listing."winner"."username".text()
I was constrained by the fact that I can only get at text values. For instance, I couldn't deserialize the bids elements into a collection and perform calculations like bids.Max(b->b.amount). That was my ultimate goal.
BTW - This is was not a web request. It was a MQ message serialized as xml.

Related

Read RDF:foaf file with Apache Jena

I have a problem with reading RDF file, which is using foaf tags. I would like to read it with Apache Jena. Below is the snippet of the RDF file.
<rdf:RDF xmlns="http://test.example.com/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:foaf="http://xmlns.com/foaf/0.1/">
<foaf:Person rdf:about="http://test.example.com/MainPerson.rdf">
<foaf:firstName>John</foaf:firstName>
<foaf:lastName>Doe</foaf:lastName>
<foaf:nick>Doe</foaf:nick>
<foaf:gender>Male</foaf:gender>
<foaf:based_near>Honolulu</foaf:based_near>
<foaf:birthday>08-14-1990</foaf:birthday>
<foaf:mbox>john#example.com</foaf:mbox>
<foaf:homepage rdf:resource="http://www.example.com"/>
<foaf:img rdf:resource="http://weknowmemes.com/wp-content/uploads/2013/09/wat-meme.jpg"/>
<foaf:made>
Article: Developing applications in Java
</foaf:made>
<foaf:age>24</foaf:age>
<foaf:interest>
Java, Java EE (web tier), PrimeFaces, MySQL, PHP, OpenCart, Joomla, Prestashop, CSS3, HTML5
</foaf:interest>
<foaf:pastProject rdf:resource="http://www.supercombe.si"/>
<foaf:status>Student</foaf:status>
<foaf:geekcode>M+, L++</foaf:geekcode>
<foaf:knows>
<foaf:Person>
<rdfs:seeAlso rdf:resource="http://test.example.com/Person.rdf"/>
</foaf:Person>
</foaf:knows>
<foaf:knows>
<foaf:Person>
<rdfs:seeAlso rdf:resource="http://test.example.com/Person2.rdf"/>
</foaf:Person>
</foaf:knows>
<foaf:knows>
<foaf:Person>
<rdfs:seeAlso rdf:resource="http://test.example.com/Person3.rdf"/>
</foaf:Person>
</foaf:knows>
</foaf:Person>
</rdf:RDF>
I just don't understand how to read this data with Apache Jena in regular POJO object. Any help will be appreciated (couldn't find tutorial on the web for this kind of parsing).
I don't know if I understood your problem. But if you need to read RDF file to a POJO object, you have a lot of choice. For example, you can read your rdf file using Jena to a model, and then create POJO objects using the methods proposed by the framework to get the values of your properties.
This is a code example that extracts the foaf:firstName from your file
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.util.FileManager;
public class Test {
//First, create a Jena model and use FileManager to read the file
public static Model model = ModelFactory.createDefaultModel();
public static void main(String[] args) {
//Use FileManager to read the file and add it to the Jena model
FileManager.get().readModel(model, "test.rdf");
//Apply methods like getResource, getProperty, listStatements,listLiteralStatements ...
//to your model to extract the information you want
Resource person = model.getResource("http://test.example.com/MainPerson.rdf");
Property firstName = model.createProperty("http://xmlns.com/foaf/0.1/firstName");
String firstNameValue = person.getProperty(firstName).getString();
System.out.println(firstNameValue);
}
}
You can use those methods in the setters of your POJO class. You can find a very good introduction here

Add Resource Bundles Programmatically

I have a faces-config.xml file with some resource bundles declared, like this:
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>de</supported-locale>
<supported-locale>es</supported-locale>
<supported-locale>pt</supported-locale>
<supported-locale>zh</supported-locale>
</locale-config>
<resource-bundle>
<base-name>messages.Messages</base-name>
<var>bundle</var>
</resource-bundle>
<resource-bundle>
<base-name>countries.Countries</base-name>
<var>countryBundle</var>
</resource-bundle>
</application>
</faces-config>
These resource bundles are registered and can be used in any .xhtml file, but is there any way to register these resource bundles programmatically? I mean by the use of dynamic code instead of a xml declaration.
Here's a simplified version of what I'm doing using CDI:
#ApplicationScoped
public class BundleProducer {
#Produce #RequestScoped #Named
public ResourceBundle getMsgBundle() {
Locale userLocale = Faces.getLocale();
return ResourceBundle.getBundle("messages", userLocale);
}
}
Note the use of omnifaces' getLocale() to avoid a ton of boilerplace code (for a less sane version, you can substitute FacesContext.getCurrentInstance().getViewRoot().getLocale() like in the tutorial you linked to).
This will cause the CDI framework to call getMsgBundle once each request if it needs to access to msgBundle thanks to the #Named annotation. In this simple case, I'm relying on the ResourceBundle internal caching and lookup mechanisms to produce my bundle efficiently. You can execute any logic you like here (eg, load stuff from the enclosing BundleProducer) as long as you return a ResourceBundle from the method (you're not allowed to return null).
Repeat as you like with more methods producing different bundles.
Not sure if I got what you were after, so just comment if you need more clarification.
For easier handling of FacesMessage stuff, I'd recommend having a look at omnifaces' Messages utility class. I use something like this to be able to optionally give bundle keys as message strings:
#Singleton
#Startup
public class MessageResolverInit {
#PostConstruct
public void initMessageResolver() {
Messages.setResolver(new Messages.Resolver() {
#Override
public String getMessage(String message, Object... params) {
Locale userLocale = Faces.getLocale();
ResourceBundle b = ResourceBundle.getBundle("msgs", userLocale);
if (b.containsKey(message)) {
return MessageFormat.format(b.getString(message), params);
}
return message;
}
});
}
Note that I use b as a variable name only for demo purposes. Usage goes like this:
Messages.addGlobalError("my_msg_key", param1);
Messages.addGlobalInfo("I'm a standalone message");
Here is the answer from Oracle documentation: Using FacesMessage to Create a Message

How to pass parameter in birt and display them in report using scripted dataset?

How will i be able to
set parameters from java class
access it from Birt report
please elaborate i am new to this.
Use IRunAndRenderTask class in your java program to add parameters.
eg:
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
// pass necessary parameters
task.setParameterValue("ordParam", (new Integer(10101))); //static parameter
task.setParameterValue("value", Integer.parseInt(value)); // pass dynamic parameter
task.validateParameters();
Also add a new parameter in Data Explorer Report parameter with name same as that you have given in your program. like here "value".
And Atlast,Drag your parameter in your report Design. and its done.
Welcome user.
To print Birt Report in Excel format Use EXCELRenderOption class.
EXCELRenderOption xlsOptions = new EXCELRenderOption(options);
xlsOptions.setOutputFormat("xls");
response.setHeader( "Content-Disposition", "attachment; filename="+downloadFileName);
xlsOptions.setImageHandler(new HTMLServerImageHandler());
xlsOptions.setOutputStream(response.getOutputStream());
//xlsOptions.setOption(IRenderOption.EMITTER_ID,"org.uguess.birt.report.engine.emitter.xls");
xlsOptions.setOption(IRenderOption.EMITTER_ID, "org.eclipse.birt.report.engine.emitter.prototype.excel");
iRenderTask.setRenderOption(xlsOptions);

InvalidOperationsException during XML-Serialization in XNA

I have a question concerning an Error I experience while trying to read an XML-File through the XNA 4.0 Content Pipeline in order to build Objects. First I reused old XNA 3.1 Code of mine which worked back in the day but now throws the an Error Message:
Building content threw InvalidOperationException: Instanzen von abstrakten Klassen können nicht erstellt werden. (Unable to build Instances of abstract Classes - roughly translated)
at ReflectionEmitUtils()
...and goes on forever, I can post it, if it's needed, but for better readability of my initial request..
Then I used this Method but it throws the same error.
These are the relevant pieces of source code:
I've written a class to define the content/structure of the XML-File:
public class Command
{
public List<bool> mButtons;
public List<Keys> keys;
public Enum iD;
}
And this is my XML File, with which I want to build Command-Objects
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
<Asset Type="KinectRTS_Input.Command">
<mButtons>true/mButtons>
<keys>
<Item>LeftControl/Item>
</keys>
<iD>SMulti/iD>
</Asset>
</XnaContent>
(In my code, the Brackets are all correct, though since this Form processes XML-Tags...;))
I used a Test-Application in order to find out, which Format the XNA-Serializer uses to output List-Items and enums, so I'm reasonably sure, that there's not the error.
It looks like either your XML is invalid or your Model is. For the mButtons field, you have defined it as a List<bool> but in the XML it's a bool not a List<bool>. I would either edit the XML to have the <mButtons> element contain a single <Item> element or change the declaration of mButtons in the Model to be a bool not List<bool>.
Too easy...the problem wasn't with the Lists, in fact the Test-Application mentioned in my request actually returned XML-Tags with Item-Tags for the keys-List and without Item-Tags for the bool-list. Wrapping the bool into Item-Tags resulted in an " at not expected"-Error. I have no idea, why the Serializer handles List and List differently, though.
The problem was the Enum 'iD', which is an abstract class and thus throws the Error mentiones above. It seems that I was overwhelmed by the sheer size of the error-message and just disregarded the crucial bit of info - that the Serializer tries to build an abstract class.
But thanks anyway. – Kuroni Kaimei

How to convert a pojo to xml using "as" keyword

I have a requirement to send an object as xml to a webservice. I already have the pojo, now I need to convert it to xml using Groovy. In grails I have used the as keyword, what is the equivalent code to do this in Groovy?
Example Grails code:
import grails.converters.*
render Airport.findByIata(params.iata) as XML
A naive example of doing this with StreamingMarkupBuilder would be:
class Airport {
String name
String code
int id
}
Writable pogoToXml( object ) {
new groovy.xml.StreamingMarkupBuilder().bind {
"${object.getClass().name}" {
object.getClass().declaredFields.grep { !it.synthetic }.name.each { n ->
"$n"( object."$n" )
}
}
}
}
println pogoToXml( new Airport( name:'Manchester', code:'MAN', id:1 ) )
Which should print:
<Airport><name>Manchester</name><code>MAN</code><id>1</id></Airport>
The as keyword is actually part of the Groovy language spec. The part you are missing is the XML class that does the conversion. This is really just a fancy class that walks the POJO and writes the XML (possibly using MarkupBuilder).
Groovy does not have a built-in class like grails.converters.XML that makes it so easy. Instead, you'll need to manually build the XML using MarkupBuilder or StreamingMarkupBuilder.
Neither of these will automatically convert a POJO or POGO to XML, you'll have to either process this yourself manually, or use reflection to automate the process.
I'd suggest that you might be able to copy the grails converter over, but it may have a lot of dependencies. Still, it's open source, that might be a starting point if you need a more reusable component.

Resources