When I try parse a java object to xml. My xml doesn't look fine and it doesn't have close tags , I have a value which is a not required and I am seeing the value.
This is my class :
#Root(name="root")
public class Example {
#Element(name="message" , required = false)
private String text;
#Attribute(name="id", required = true)
private int index;
#Attribute( required = false)
private int index2;
public String getMessage() {
return text;
}
public int getId() {
return index;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
And when I did this :
Serializer serializer = new Persister();
Example example1 = new Example();
example1.setIndex(111111);
String path = Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
File folder = new File(path);
File file1 = new File(folder, "qqq.xml");
try {
serializer.write(example1, file1);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
My output XML looks like this :
<root index2="0" id="1
Why I have a index2="0" ? and don't have id="1" ?
Related
I have some classes in my project and when I want to instantiate object from them using myClass.newInstance() to build SQL queries, it just creates the object with one field and I can't retrieve all class fields to complete my query. When I get size of my object it returns '1' instead of '3'.
Any idea what should I do?
Here-under you can find one class and my query builder.
#JupiterEntity
#TableName(name="tbl_person")
public class Person {
#PrimaryKey
#DbColumn(name = "clmn_id")
private int id;
#DbColumn(name="clmn_name", length = 1024)
private String name;
#DbColumn(name="clmn_family", length = 1024)
private String family;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
}
And here is when I want to instantiat an object from my class:
public MySQLEntityManager() {
StringBuilder stringBuilder = new StringBuilder();
if(ServiceLocator.getConfiguration().createDDL()) {
for(Class entityClass : ServiceLocator.getConfiguration().getEntities()) {
Object obj = new Object();
try {
obj = entityClass.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
stringBuilder.append("DROP TABLE ")
.append("'")
.append(ServiceLocator.getConfiguration().getDatabaseName())
.append("'.'")
.append(getTableName(obj)).append("' ");
System.out.println(stringBuilder.toString());
stringBuilder.setLength(0);
stringBuilder.append("CREATE TABLE")
.append("'")
.append(ServiceLocator.getConfiguration().getDatabaseName())
.append("'.'")
.append(getTableName(obj)).append("' ");
Map<Field, Object> fields = ReflectionHelper.getValuesOfFields(obj);
for(Field field : fields.keySet()) {
System.out.println(field.getName() + " -> " + fields.get(field));
}
String delimiter = "";
for (Field field : fields.keySet()) {
String columnName = field.getName();
if (field.isAnnotationPresent(DbColumn.class)) {
DbColumn dbColumn = field.getAnnotation(DbColumn.class);
columnName = dbColumn.name();
}
stringBuilder.append(delimiter).append(columnName);
delimiter = ", ";
}
System.out.println("*****" + stringBuilder.toString());
delimiter = "";
System.out.println(stringBuilder.toString());
}
}
}
So the problem is that ReflectionHelper.getValuesOfFields(obj) isn't returning what you want. You can debug that, or use obj.getClass().getDeclaredFields() instead of some NIH junk.
I have an xml input as below
<Confirmations>
<SystemConf>
<SysCnf>
<MessageId>1</MessageId>
</SysCnf>
<SysCnf>
<MessageId>2</MessageId>
</SysCnf>
</SystemConf>
</Confirmations>
and these are my classes
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "Confirmations")
public class Confirmations
{
#XmlElementWrapper(name = "SystemConf")
#XmlElement(name = "SysCnf")
private List<SystemConfirmation> systemConfirmations = null;
public List<SystemConfirmation> getSystemConfirmations()
{
return systemConfirmations;
}
public void setSystemConfirmations(List<SystemConfirmation> systemConfirmations)
{
this.systemConfirmations = systemConfirmations;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "SysCnf")
public class SystemConfirmation
{
#XmlElement(name = "MessageId")
private String messageId;
public void setMessageId(String messageId)
{
this.messageId = messageId;
}
public String getMessageId()
{
return messageId;
}
#XmlAnyElement(value = SysConfXmlStringHandler.class)
private String xml;
public String getXml()
{
return xml;
}
}
public class SysConfXmlStringHandler implements DomHandler<String, StreamResult>
{
private static final String SYSCONF_START_TAG = "<SycCnf>";
private static final String SYSCONF_END_TAG = "</SysCnf>";
private StringWriter xmlWriter = new StringWriter();
#Override
public StreamResult createUnmarshaller(ValidationEventHandler errorHandler)
{
return new StreamResult(xmlWriter);
}
#Override
public String getElement(StreamResult rt)
{
String xml = rt.getWriter().toString();
System.out.println(xml);
int beginIndex = xml.indexOf(SYSCONF_START_TAG) + SYSCONF_START_TAG.length();
int endIndex = xml.indexOf(SYSCONF_END_TAG);
return xml.substring(beginIndex, endIndex);
}
#Override
public Source marshal(String n, ValidationEventHandler errorHandler)
{
try
{
String xml = SYSCONF_START_TAG + n.trim() + SYSCONF_END_TAG;
StringReader xmlReader = new StringReader(xml);
return new StreamSource(xmlReader);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
Question
In the xml field of the SystemConfirmation class I want the whole xml of that particular SystemConfirmation block xmml element, which would be below
<SysCnf>
<MessageId>1</MessageId>
</SysCnf>
Does anyone know how to achieve this? I tried the above code but I was only getting MessageId block in the xml and if I add multiple fields in SystemConfirmation than I only get the first one.
Im quite new to Rhino and trying to convert a javascript object to a java object but unable to do so. It doesnt seem to evaluate properly.
The javascript that I have is,
var myObject = new Object();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);
And I have the following java class that I want to evaluate this to,
public class Person extends ScriptableObject {
private int id;
private String string1;
private String string2;
public Person() {}
public void jsConstructor() {
this.string1 = "";
this.string2 = "";
this.id = 0;
}
public int getID()
{
return this.id;
}
public void jsSet_id(int value)
{
this.id = value;
}
public int jsGet_id()
{
return this.id;
}
public String jsGet_string1()
{
return this.string1;
}
public void jsSet_string1(String value)
{
this.string1 = value;
}
public String jsGet_string2() {
return this.string2;
}
public void jsSet_string2(String value)
{
this.string2 = value;
}
#Override
public String toString() {
return id + " " + string1 + " " + string2;
}
#Override
public String getClassName() {
return "Person";
}
And the skeleton of my parser is,
public class MyParser {
public String PrintObj(ScriptableObject obj) {
// Need to convert to Person object here
// Obviously casting doesnt work here
return null;
}
}
Thanks
OK figured it out !
First of all i needed to define the class in javascript as. It was complaining at first it couldn't find the class without the namespace "com". Had to add that...
defineClass("com.Person")
var myObject = new Person();
myObject.string1 = 'Hello';
myObject.string2 = 'World';
myObject.id = 1;
var parser = new Packages.com.MyParser();
var returnStr = parser.PrintObj(myObject);
And then in the parser I added the following,
public String PrintObj(ScriptableObject obj) {
try {
Person pObj = (Person)Context.jsToJava(obj, Person.class);
System.out.println("Printing person: " + pObj);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
I am trying replace the arrays I have with arraylists so I don't have to worry about managing the arrays and can clean up my code. I have only just taught myself arraylists so I am having some issues. Mainly in these classes where all my "sets" and "gets" are. I don't think I have the right syntax because I am getting an ArrayList/String conflict error. Basically trying to get:
public static ArrayList<Resource> importResourcesFromXML(String documentLocation)
to import an arraylist of resources from an XML document. I also wanted to convert my arrays in Resources and my T_Resources into arraylists as well. This is the code I have so far, I believe I have Resources implemented correctly but could use help with the other two getting the XML resources to display properly.
EDIT: I want to if at all possible eliminate the array entirely and replace it with an arraylist. I want to try and avoid converting an array to an arraylist.
import java.util.ArrayList;
public class Resources {
//private static final int MAX_SUBJECTS = 20;
private String title;
private String description;
private Identifier identifier;
ArrayList<Subject> subject = new ArrayList<Subject>();
//private int subjectCount;
public Resources() {
title = "unknown title";
description = "unknown description";
identifier = null;
//subjects = new Subject[MAX_SUBJECTS];
//subjectCount = 0;
}
public void setTitle(String newTitle) {
title = newTitle;
}
public String getTitle() {
return title;
}
public void setDescription(String newDescription) {
description = newDescription;
}
public String getDescription() {
return description;
}
public void setIdentifier(Identifier newIdentifier) {
identifier = newIdentifier;
}
public Identifier getIdentifier() {
return identifier;
}
public void addSubject(Subject newSubject) {
subject.add(newSubject);
}
public ArrayList<Subject> getSubjects() {
//Subject[] result = new Subject[subjectCount];
//System.arraycopy(subjects, 0, result, 0, subjectCount);
return subject;
}
}
public class ResourceImporter {
// This operation loads the XML document specified by the document location, which can a file or a URL,
// and returns a reference to the document. If the operation cannot successfully load the document
// the operation returns the null reference.
//
private static Document loadXMLDocument(String documentLocation) {
// The XML document.
//
Document documentIn = null;
// The parser that reads in an XML files.
//
DocumentBuilder parser = null;
// Pull the document
//
try {
// Obtain a document parser.
//
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
parser = builderFactory.newDocumentBuilder();
documentIn = parser.parse(documentLocation);
} catch (ParserConfigurationException p) {
System.out.println("Error creating parser.");
System.out.println(" " + p.getMessage());
} catch (SAXException s) {
System.out.println("Document is not well formed.");
System.out.println(" " + s.getMessage());
} catch (IOException i) {
System.out.println("Error accessing the file.");
System.out.println(" " + i.getMessage());
} catch (Exception e) {
System.out.println("Unknown error occurred.");
System.out.println(" " + e.getMessage());
}
return documentIn;
}
public static ArrayList<Resource> importResourcesFromXML(String documentLocation) {
ArrayList<Resource> resource = new ArrayList<Resource>();
Document doc;
Element resourceElement;
Element titleElement;
String title;
Element descriptionElement;
String description;
Element identifierElement;
String identifiers;
Element urlElement;
String url;
NodeList subjectList;
Element subjectElement;
String subjects;
Element categoryElement;
String category;
Element subcategoryElement;
String subcategory;
doc = loadXMLDocument(documentLocation);
resourceElement = (Element)doc.getElementsByTagName("resource").item(0);
if (resourceElement != null) {
titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);
resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );
descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);
resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );
identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);
if (identifierElement != null) {
Identifier identifier = new Identifier();
urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);
identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );
resource.setIdentifier(identifier);
subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);
if (subjectElement != null) {
subjectList = subjectElement.getElementsByTagName("subject");
for (int i=0; i < subjectList.getLength(); ++i) {
Subject subject = new Subject();
subjectElement = (Element)subjectList.item(i);
categoryElement = (Element)subjectElement.getElementsByTagName("category").item(0);
subject.setCategory( categoryElement == null ? "unknown" : categoryElement.getTextContent() );
subcategoryElement = (Element)subjectElement.getElementsByTagName("subcategory").item(0);
subject.setSubcategory( subcategoryElement == null ? "unknown" :subcategoryElement.getTextContent() );
resource.addSubject(subject);
}
}
}
}
return resource;
}
}
import java.util.ArrayList;
public class T_Resources {
public static void main(String[] args) {
ArrayList<Resource> resource = ResourceImporter.importResourcesFromXML("http://free1.ed.gov/xml/gemexport.xml");
displayResources(resource);
}
private static void displayResources(ArrayList<Resource> resource) {
ArrayList<Subject> subjects;
System.out.println(resource.getTitle());
System.out.println(resource.getDescription());
System.out.println(resource.getIdentifier().getURL());
subjects = resource.getSubjects();
for (int i=0; i < subjects.size(); ++i) {
System.out.println(subjects.getCategory() + " :: " + subjects.getSubcategory());
}
System.out.println();
}
}
public class Subject {
private String category;
private String subcategory;
public Subject() {
String category = "unknown";
String subcategory = "unknown";
}
public Subject(Subject subject) {
category = subject.category;
subcategory = subject.subcategory;
}
public void setCategory(String newCategory) {
category = (newCategory == null) ? "unknown" : newCategory;
}
public String getCategory() {
return category;
}
public void setSubcategory(String newSubcategory) {
subcategory = newSubcategory;
}
public String getSubcategory() {
return subcategory;
}
}
public class Identifier {
private String url;
public Identifier() {
url = "unknown";
}
public void setURL(String newURL) {
url = newURL;
}
public String getURL() {
return url;
}
}
Let me know if I'm misinterpreting things, but if all you're looking for is a way to convert a primitive array into an ArrayList then I would use the following:
arrayList = Arrays.asList(array);
I want to serialize a object hierarchy including a list of objects which derive from the base class 'Thing'. This works fine, including deserialization - but XML-Simple insists in writing an attribute which specifies the actual used Java-class
when I create a xml file with the java code below, the content is like this:
<example1>
<things>
<fruit class="com.mumpitz.simplexmltest.Apple" id="17">
<sugar>212</sugar>
</fruit>
<fruit class="com.mumpitz.simplexmltest.Orange" id="25" weight="11.2"/>
</things>
</example1>
but this is not what I want.
I'd like to have
<example1>
<things>
<apple id="17">
<sugar>212</sugar>
</apple>
<orange id="25" weight="11.2"/>
</things>
</example1>
'apple' and 'orange' elements without a class attribute, not 'fruit' with such an attribute. Is this possible?
(The second xml complies to a existing schema; adding extra attributes is not an option)
Here's the code:
package com.mumpitz.simplexmltest;
import java.io.File;
import java.util.ArrayList;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
class Fruit {
#Attribute(name = "id")
protected final int id;
Fruit(
#Attribute(name = "id")
int id) {
this.id = id;
}
int getObjectId() {
return id;
}
}
#Root
class Apple extends Fruit {
private final int sugar;
#Element(type = Fruit.class)
public Apple(
#Attribute(name = "id")
int id,
#Element(name = "sugar")
int sugar) {
super(id);
this.sugar = sugar;
}
#Element(name = "sugar")
public int getSugar() {
return this.sugar;
}
#Override
public String toString() {
return "id: " + id + ", sugar: " + sugar;
}
}
#Root
class Orange extends Fruit {
#Attribute
public double weight;
public Orange(
#Attribute(name = "id")
int id) {
super(id);
}
#Override
public String toString() {
return "id: " + id + ", weight: " + weight;
}
}
#Root
public class Example1 {
#ElementList
public ArrayList<Fruit> things = new ArrayList<Fruit>();
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("things:\n");
for (int i=0; i<things.size(); i++) {
sb.append(" " + things.get(i).toString() + "\n");
}
return sb.toString();
}
//////////////////////////////////
static Example1 createDummy() {
Example1 d = new Example1();
d.things.add(new Apple(17, 212));
Orange or = new Orange(25);
or.weight = 11.2;
d.things.add(or);
return d;
}
static String msg;
static Example1 res;
static public String getMessage() {
String m = msg;
msg = null;
return m;
}
static public boolean write(String path) {
Serializer serializer = new Persister();
Example1 example = Example1.createDummy();
File result = new File(path);
try {
serializer.write(example, result);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
static public boolean read(String path) {
Serializer serializer = new Persister();
File source = new File(path);
try {
res = serializer.read(Example1.class, source);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
public static Object getResult() {
return res;
}
}
some hours later I found the solution. You simply have to
Read the manual
Use the #ElementListUnion annotation
package com.mumpitz.simplexmltest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.ElementListUnion;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
// the base class
#Element
class Thing {
static int count=0;
Thing() {
this.id = ++count;
}
#Attribute
protected int id;
public int getId() {
return id;
}
}
// first derived class
#Element
class Car extends Thing {
#Attribute
private String name;
Car(#Attribute(name="name") String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "ID: " + id + " Car: " + name;
}
}
// second derived class
#Element
class House extends Thing {
#Attribute
private int price;
House(#Attribute(name="price") int price) {
this.price = price;
}
public int getPrice() {
return this.price;
}
#Override
public String toString() {
return "ID: " + id + " House: " + price;
}
}
// a class with a list of base class instances
#Root(name="ListOfThings")
public class Example4 {
// specify the derived classes used in the list
#ElementListUnion({
#ElementList(entry="house", inline=true, type=House.class),
#ElementList(entry="car", inline=true, type=Car.class)
})
private ArrayList<Thing> list = new ArrayList<Thing>();
public void add(Thing t) {
list.add(t);
}
public List<Thing> getProperties() {
return list;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Example4 contains " + list.size() + " elements:\n");
for (Thing t : list) {
sb.append(" " + t.toString() + "\n");
}
return sb.toString();
}
//////////////////////////////////
// test code
//////////////////////////////////
static String msg;
static Example4 res;
static public String getMessage() {
String m = msg;
msg = null;
return m;
}
static private Example4 createDummy() {
Example4 d = new Example4();
d.add(new Car("Mercedes"));
d.add(new House(34000000));
d.add(new Car("VW"));
d.add(new House(230000));
return d;
}
//////////////////////////////////
// serialize / deserialize
//////////////////////////////////
static public boolean write(String path) {
Serializer serializer = new Persister();
File result = new File(path);
Example4 example = Example4.createDummy();
try {
serializer.write(example, result);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
static public boolean read(String path) {
Serializer serializer = new Persister();
File source = new File(path);
try {
res = serializer.read(Example4.class, source);
} catch (Exception e) {
e.printStackTrace();
msg = e.getMessage();
return false;
}
return true;
}
public static Object getResult() {
return res;
}
}