XML to Java Object - java

I am trying to convert an XML file to a Java Object, now, I have read of JAXB, XStream, Sax and DOM, I'd like to convert this sort of type of xml:
<testxml testtype="converting" duration="100.00" status="successful" />
it might be as well as:
<testxml testype="converting" duration="100.00"> successful </textxml>
I wanted to know if there is anything out there (and possibly not 3rd party) that I can use, without declaring a template in DTD or in JAXB in XSD but Java (therefore I will declare a java class called testxml with all the relevant variable i.e. testtype, duration, status>
Thank you all for your time.

The class below using JAXB Annotations will do exactly what you need, no need to create an XSD or a template using Java 1.6+:
#XmlRootElement
public class TestXML {
private String testtype;
private double duration;
private String status;
public void setTesttype(String testtype) {
this.testtype = testtype;
}
#XmlAttribute
public String getTesttype() {
return testtype;
}
public void setDuration(double duration) {
this.duration = duration;
}
#XmlAttribute
public double getDuration() {
return duration;
}
public void setStatus(String status) {
this.status = status;
}
#XmlValue
public String getStatus() {
return status;
}
public static void main(String args[]) {
TestXML test = JAXB.unmarshal(new File("test.xml"), TestXML.class);
System.out.println("testtype = " + test.getTesttype());
System.out.println("duration = " + test.getDuration());
System.out.println("status = " + test.getStatus());
}
}
Using this as test.xml:
<testxml testtype="converting" duration="100.00"> successful </testxml>

You can do this pretty simply by using java.xml.bind.annotations on a Java class and JAXB.Unmarshal
JAXB is part of the JRE in java 1.6+

Try XStream/XPP3. That's good stuff. Takes a couple of hours to figure out. Does all the magic for you.

Personally I use XStream # http://x-stream.github.io/ It's really easy to use and still offers enough features in case you need them. Unfortunately it looks like the project is not actively maintained anymore, but I haven't seen an alternative so far that suits my needs as well. I'd say it's worth spending a bit of time to check it out ;-)
edit: when you can use Java 6, I completely agree the other answers are preferable!

Related

Create a simple XML-document database Java

I need some Java help.
I have got a class like this
public class Thing {
private String name;
private int price;
public Thing(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
And my main looks like this
public class Main {
public static void main(String[] args) {
Thing Bowl = new Thing("Bowl", 20);
} }
What I would like to do is make a simple XML-document database. So I can add different kind of things in my database. How can I implement this kind of database in my system?
It's not correct to call what you're talking about a database. You just want to save a Java class as an XML file. Jackson is a good library that allows for both JSON and XML encode/decode and using it, can be done as so given a POJO:
ObjectMapper xmlMapper = new XmlMapper();
List<Thing> things = new ArrayList<>();
things.add(bowl);
String xmlData = xmlMapper.writeValueAsString(things);
List<Thing> thingsFromXml = xmlMapper.readValue(xmlData, new TypeReference<List<Thing>>(){});
Although the question is very broad, I'll do my best to guide you along.
An overarching system for XML consists out of various subsystems. First of all, you're going to need a way to parse the XML documents. There are many open source libraries out there that you can use. Even if you insist on writing it from scratch, referencing work that others have made is always useful.
See this:
Which is the best library for XML parsing in java
Then once you have a system in place in which you can parse the documents, you'll need a way to organize the parsed data. The way to approach this is subject to the practical use of the system. For example, if you use XML as the standard format for loading data in a game and thus deal with many different types of data such as items, objects, locations and so forth. You'll want a dynamic way to reload the data, the factory design pattern would work well in this use-case.
See this: https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

Is it possible to build an object like this at runtime in java?

As the title says....
I want to build a POJO with four field variables and at certain runtime events create an instance of this POJO with access to possibly maybe two or three of the fields.
public class Category implements Serializable {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Lets say I create a new Category object but I only want to be able to have access to the name field during runtime. Is there a design pattern I can use to achieve this? I thought about the strategy pattern and looked at the builder but I am still confused if I can do this in java.
Basically the overall goal is to grab an object from a database and return it as a JSON response in jax rs. But sometimes I dont want a complete object returned but only lets say halve of the object to be accessible at during certain runtime events. My apologies if this seems like a dumb question but I know what I want to do but just don't know the best way.
I have the same problem with you, and my project was used springmvc,and the json tool is jackson.With the problem solved, I just use #JsonIgnore.For more details,just read jackson-how-to-prevent-field-serialization
So someone correct me if I am wrong or see a better option than this...with alot of objects this can be alot of extra code for serialization and deserialization...Jackson Provisions is what I need. I can use the annotation #JsonView(DummyClass.class) on the field variable. I will accept this a the best answer in a day or two unless someone else posts a better response.
// View definitions:
class Views {
static class Public { }
static class ExtendedPublic extends PublicView { }
static class Internal extends ExtendedPublicView { }
}
public class Bean {
// Name is public
#JsonView(Views.Public.class) String name;
// Address semi-public
#JsonView(Views.ExtendPublic.class) Address address;
// SSN only for internal usage
#JsonView(Views.Internal.class) SocialSecNumber ssn;
}
With such view definitions, serialization would be done like so:
// short-cut:
objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);
// or fully exploded:
objectMapper.getSerializationConfig().setSerializationView(Views.Public.class);
// (note: can also pre-construct config object with 'mapper.copySerializationConfig'; reuse)
objectMapper.writeValue(out, beanInstance); // will use active view set via Config
// or, starting with 1.5, more convenient (ObjectWriter is reusable too)
objectMapper.viewWriter(ViewsPublic.class).writeValue(out, beanInstance);
This information was pulled from http://wiki.fasterxml.com/JacksonJsonViews
with jackson 2.3, I can do this with JAX-RS
public class Resource {
#JsonView(Views.Public.class)
#GET
#Produces(MediaType.APPLICATION_JSON )
public List<Object> getElements() {
...
return someResultList;
}
}

good json lib like ios JSONModel

can tell me if android have the same lib link
https://github.com/icanzilb/JSONModel
or
http://www.touch-code-magazine.com/JSONModel/
I parse JSON only need write set and get, and then make JSON to object mapping and serialization.
Check Gson and Jackson. Both are very easy to use, I prefer Gson because it works without annotations in the POJOs. There's lots of examples to be found on how to use them to serialize and deserialize JSON.
Gson does a great job for this;
You can read a little tutorial about it here which should get you started;
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
You also have Genson lib that has nice features, perfs, provides alternatives to annotations and is easy to use.
I would recommend the lib FastJson , it is fast than protocol buf and jackson , you can try this .
maybe FastPojo help you, a wilde card pojo class
https://github.com/BaselHorany/FastPojo
usually you make a modle class like this
public class Msg {
private int id;
private String name;
private Double doub;
private Boolean bool;
public Msg(String id,.....,.........) {
this.id = id;
........
}
public String getId() {
return id;
}
........
public void setId(String id) {
this.id = id;
}
........
}
for each variable you define its type and make setter and getter voids and pass it in a Routine process and then you use it like this usually
//set
Msg msg = new Msg();
msg.setId(id);
msg.setName(name);
........
//get
msg.getId();
.........
BUT with FastPojo you dont need custom modle because it is a "Wilde Card class" that can define objects type and then set and get them appropriately you just set and get directly> so:
Usage
just copy the class to your project
FastPojo msg = new FastPojo();
msg.set1(id);
msg.set2(name);
msg.set3(1.55);
msg.set4(true);
//get first variable where s is the type you should remember it s for string, i for int, d for double and b for boolean.
msg.get1i();//get id int
msg.get2s();//get string name
msg.get3d();//get double 1.55
msg.get4b();//get boolean true

Generate Getters and setters without underscore (not prefix/suffix) + eclipse

My variable is
private String category_code = null;
My getter and setter is generated as
public String getCategory_code() {
return category_code;
}
public void setCategory_code(String category_code) {
this.category_code = category_code;
}
Is it possible to generate
public String getCategorycode() {
return category_code;
}
public void setCategorycode(String categorycode) {
this.category_code = category_code;
}
I checked Properties-->Code Style-->Fields but that is only for prefix and suffix.
Or should I just rename my variables as m_categoryCode? and get my output as follows?
public String getCategoryCode() {
return m_categoryCode;
}
public void setCategoryCode(String categoryCode) {
m_categoryCode = categoryCode;
}
Which is better?
The names of the getter and setter methods are derived from the field name. If you use a prefix or suffix for fields (e.g. fValue, _value, val_m), you can specify the suffixes and prefixes in the Code Style preference page (Windows > Preferences > Java > Code Style).
reference at here
Java code tends to follow the camelCaseStyle, not the c_underscore_style. Following the existing standards will generally help you in a variety of ways (you will be able to better read others' code and others will be able to better read your code, where "others" are other developers in the same language). also, the tooling for the language tends to work better (case in point).

how to create java file programmatically

I am creating a util-class which writes .java Files that act as coverter - generator.
This util-class will generate AConverter.java' (refer below sample)
I want know how to write the util-class.
I googled, and found the recommendation to use apache bcel. But I couldn't find an example to write the .java File from a String and have it working in my program.
The expectation is...
class ADTO
{
private String empId;
private String empName;
private String dept;
//setters and getters
}
class ABO
{
private String loginId;
private String userName;
private String group;
//setter and getter
}
class AConverter
{
public void doConvertFromDB(ADTO source, ABO dest)
{
dest.setLoginId(source.getEmpId());
...
}
public void doConvertFromBO(ABO source, ADTO dest)
{
dest.setEmpId(source.getLoginId());
...
public ADTO getSourceClass()
{
return ADTO.class;
}
public ABO getDestClass()
{
return ABO.class;
}
}
The above class AConverter will generated by the new Util-class.
You would almost certainly benefit from trying to do this a different way, the number of ways this scheme could fail is worryingly large. Here are some suggestions:
Add a caster method of some sort:
class ADTO
{
private String empId;
private String empName;
private String dept;
// setters and getters
public ABO toABO() // caster method (ABO will need a toADTO() as well)
{
ABO a = new ABO();
a.setSomething(getSomethingEquivalent());
...
return a;
}
}
A proxy class, perhaps a subclass of the intended class. You would need 2, one derived from each class.
class ADTO_Proxy extends ADTO
{
private ABO abo;
public ADTO_Proxy(ABO a)
{
super();
abo = a;
}
#override
public String getEmployeeId()
{
return abo.getLoginId();
}
// other setters and getters
}
Rather than trying to make an adapter, merge the classes. Could be easily accomplished with the following:
class ADTO
{
private String empId;
private String empName;
private String dept;
// getters and setters for each variable by each name
public String getEmployeeId()
{ return empId; }
public String getLoginId()
{ return empId; }
public String getEmployeeName()
{ return empName; }
public String getUsername()
{ return empName; }
public String getDepartment()
{ return dept; }
public String getGroup()
{ return dept; }
// setters
}
This could also be done with interfaces.
HateYourselfLaterâ„¢ Ratings:
The first method ranks a 2, the best of the three. Rating earned because you won't ever find yourself accidentally switching between the two and not much other code has to be changed.
The second method ranks a -3, in the middle of the three. Rating earned because you may occasionally mix up objects that are of one type of the other, with possible unintended side effects. You can reduce this to a rating of 0 if you omit setters from the proxy classes, but this limits functionality.
The third method gets a -5, the worst of the three. Rating earned because there is a lot of possibility for side effects and the redundant code will probably trip you up later. However, you can make rate 1 by refactoring everything to properly use only one class, but that might take a lot of work, and you'll hate yourself for it now.
That said, your original idea of generating a class on the fly to convert between the two ranks about a -10 because it will be horribly difficult to maintain and very sensitive to any changes of the underlying classes, and will probably be easy to break.
HateYourselfLaterâ„¢ Scale ranges from -10 to 10, with 10 being the largest amount of like, and -10 being the largest amount of hate.
Original Answer:
You want a decompiler. There are several java decompilers available to pick from, I'll list a few:
Showmycode - easy to use, decent decompiling, online (thus unsuitable for corporate material), screws up built in class names and nested anonymous classes
Jad - downloadable, CLI, works but produces ugly code, linux version is out of date (use windows version with wine if necessary) , screws up enums, foreach loops, and some try/catches
Fernflower - CLI, hard to find, best output of the three, author is SO user, decent looking output, screws up try/catches sometimes
None of them are perfect, but that's just a result of the fact that some data gets lost during compilation, and decompilers must guess what the program originally looked like.
You can do multiple things.
You SHOULD decide what you want to do precisely and then get a matching library do it for you and learn that library.
BCEL is one such library. I've used Java-APT in the past successfully for similar purposes.
For your understanding I will write some things about generating classes below, but please, don't develop this yourself, you most likely will end up stuck.
If you want to have your class available within the same JVM you are currently running (in opposition to: you want to generate code and then compile the whole program again and restart it) then you have to:
Create the File, write your String to it.
Compile the File (a rough way to do so would call javac from the code)
load the classes into your classloader.

Categories