Java: xml to singleton (using maven & jaxb) - java

I want to do such thing completely automatically by maven.
I have a .xml file with some data. There is some references by ids from one object in this xml to another, and so on. I don't have .xsd of this .xml.
I need exactly two things:
1) Compile this xml to Java classes.
2) Creating one Singleton class named by this .xml name and containing all .xml data relative the inner .xml structure.
For example, my .xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<MyBigSinletonWithAllData>
<Cars>
<Car id="1" speed = "5"/>
<Car id="2" speed = "3"/>
</Cars>
</MyBigSinletonWithAllData>
And I want to get somehting like this, as automatic output:
class MyBigSinletonWithAllData {
List<Cars> cars;
}
class Car {
double speed;
}
class MyBigSinletonWithAllDataSingleton {
MyBigSinletonWithAllData INSTANCE = new MyBigSinletonWithAllData();
/* And here we read an INSTANCE from our .xml file */
}
So, my question is how to do this fully automatically by Maven?
I don't want to code manually the "MyBigSinletonWithAllDataSingleton", I just want to get it already generated for me, so I need only to write code line like this:
MyBigSinletonWithAllDataSingleton.INSTANCE
to get full access to all data that written in relative .xml file.
For now I use "maven-jaxb2-plugin" to generate Java classes from .xsd; But I also need a tool that do .xsd from .xml, and tool that create automatically read/write operations to singleton.

In Java SOAP based webservices there are different implementation like apache axis and apche cxf. In that implementations we have tools which we will run or simply we will pass the XML file to that tool so corresponding binding classes will be generated.
Please look into their code so that it will helps you.
or may be some different tools also will be there(google it).
And yes you can convert xml to xsd file.
Go through the link
Conver XML to XSD

Related

How can I parse yaml comments using java?

I want to use a yml configuration file in my project. I am using jackson-dataformat-yaml for parsing yml files. But I need to parse yml comments as well. I used the similar approach in python using ruamel yaml. How can I do the same in java?
Upd.
What for? Well, I wanted to make it possible to override my configuration options by using command line arguments. So, to generate description message for each option, I wanted to use my comments. Like this:
In my config.yml
# Define a source directory
src: '/foo/bar'
# Define a destination directory
dst: '/foo/baz'
So when you run your program with the --help flag, you'll see the following output:
Your program can be ran with the following options:
--src Define a source directory
--dst Define a destination directory
The main benefit in such a model is that you don't ever need to repeat the same statement twice, because they can be retrieved from the configuration file.
Basically, you have three layers of data:
Your configuration schema. This defines the values that are to be defined in the configuration file.
The configuration file itself, which describes the usual configuration on the current machine.
One-time switches, which override the usual configuration.
The descriptions of what each value does belong to the schema, not to the configuration file itself. Think about it: If someone edits the configuration file on their machine and changes the comments, your help output would suddenly show different descriptions.
My suggestion would be to add the descriptions to the schema. The schema is the Java class you load your YAML into. I am not sure why you are using Jackson, since it uses SnakeYaml as parser and SnakeYaml is perfectly able to deserialize into Java classes, but has more configuration options since it does not generalize over JSON and YAML like Jackson does.
Here's a general idea how to do it with SnakeYaml (beware, untested):
// ConfigParam.java
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface ConfigParam { String description(); }
// Configuration.java
public class Configuration {
#ConfigParam("Define a source directory")
String src;
#ConfigParam("Define a destination directory")
String dst;
}
// loading code
Yaml yaml = new Yaml(new Constructor(Configuration.class));
Configuration config = yaml.loadAs(input, Configuration.class);
// help generation code
System.out.println("Your program can be ran with the following options:")
for (Field field: Configuration.class.getFields()) {
ConfigParam ann = field.getAnnotation(ConfigParam.class);
if (ann != null) {
System.out.println(String.format("--%s %s", field.getName(), ann.description());
}
}
For mapping actual parameters to the configuration, you can also loop over class fields and map the parameters to the field names after having loaded the configuration (to replace the standard values with the given ones).

XML unmarshalling

I want to unmarshall the below XML file
<uc-export clientvers="9.00">
<JOBS_WINDOWS AttrType="WINDOWS" client="0001" name="BEP.WIN.SRZ2AY" system="UC4_EXP">
<ATTR_JOBS state="1">
<AutoDeactNo>6</AutoDeactNo>
<ActAtRun>2</ActAtRun>
</ATTR_JOBS>
</JOBS_WINDOWS>
</uc-export>
want to get the value of in my java program.
I have found a complex solution as of now if there any simple way to proceed rather than creating java class inside another java class.
You can try using JAXB Java Architecture for XML Binding. See here for an example.
Another option to consider is Apache XMLBeans. In XMLBeans, you would create an XSD file which the above XML you gave matches. XMLBeans would compile this XSD file and generate an XmlObject POJO corresponding to the XSD file. Let us call this class (interface) YourXMLDocument. Once these steps are out of the way, you can simply parse your input XML file ("input.xml") with the following line of code:
YourXMLDocument yourDoc = YourXMLDocument.Factory.parse("input.xml");
See here for more information.

Configuring New Relic custom metrics with YAML

According to the New Relic Documentation:
Starting in version 2.10.0, you can monitor specific methods in your application without modifying code by using a custom instrumentation XML file.
It also says:
Prior to 2.10.0, YAML files could be used for custom instrumentation. These YAML files are still supported.
I can't find documentation for the YAML format anywhere. I'm assuming it's pretty similar to the XML structure, but it can't be a 1-to-1 match.
"Where can I find documentation" seems like a terrible Stack Overflow question, so here is specifically what I want to know. Given the following Java class:
public class Test {
public void foo() {
bar();
}
private void bar() {
}
}
What New Relic YAML configuration would I use to track both foo and bar where foo is a transaction entry point and bar is not (assuming I inferred the meaning of that attribute correctly)?
Thanks a lot!
Patrick
I talked to the folks over at New Relic. The documentation regarding the yml configuration has been removed because it has been deprecated. The old yml configuration support is there for backward compatibility; however, new features have been added to the xml configuration that are not supported by the yml configs . . . for example, method matching without parameter specifications.
The supported approach to custom extensions is to use the XML configuration. A few notes from my experience in case it helps someone else with similar problems.
The custom xml examples documentation at the time of writing has a sample that's invalid if you try to validate it with the command mentioned in the custom monitoring by xml document.
Here's a sample script that worked for me:
<?xml version="1.0" encoding="UTF-8"?>
<extension
xmlns="https://newrelic.com/docs/java/xsd/v1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="newrelic-extension extension.xsd "
name="HelloWorldExtension" version="1.0"
>
<instrumentation>
<pointcut transactionStartPoint="true">
<className>com.autopilotllc.HelloWorld</className>
<method>
<name>sayHello</name>
</method>
</pointcut>
</instrumentation>
</extension>

Use a class field in the 'plugin.xml' for an eclipse plugin

I am currently working on a little Eclipse plugin and I have to deal with the classic 'plugin.xml' stuff, such as the creation of a nature:
<extension
id="aplugin.natures.MyNature.NATURE_ID.id"
name="Sample Project Nature"
point="org.eclipse.core.resources.natures">
Now in this particular example, I must, somewhere in my plugin code, give this 'id' as a String to some Eclipse function. So I need to create a specific class like:
package aplugin.natures;
public class MyNature implements IProjectNature {
public static final String NATURE_ID = "aplugin.natures.MyNature.NATURE_ID.id"; //$NON-NLS-1$
}
And here comes my problem, I got some copy and paste of my 'id'. I must admit that I am not very proud of it.
So my question is, does someone know a way to use the 'NATURE_ID' field in the 'MyNature' class directly in the 'plugin.xml' file ?.
In the end I wish to write something like:
<extension id="${aplugin.natures.MyNature.NATURE_ID}" ... >
That is not possible by design.
The idea is that the Eclipse core can load the plugin.xml files for all resolved plug-ins/bundles without loading/activating the plug-ins. Resolving your construct above would normally require Eclipse to resolve all references for the class - MyNature in this case - which can easily lead to the activation of many other dependent plug-ins. Not good.
So - by design - all data in plugin.xml must be self-contained. (With the possible exception of localized strings).

XML unmarshalling with Castor and Grails

I have a grails project that contains a few domain objects. I am using a java project in this code which can parse a document for me. The controller that calls that Java project is using JAXB to generate XML from the object returned by the Java project.
I want to use this XML document (which is generated after some text parsing, using JAXB) to populate my Domain classes in my grails project. How does this work in grails? Can I use something like Castor, and create a mapping using the names of my groovy classes? The idea is I want to generate new entries in the database and save it for the user based on whatever text was parsed out of the document they uploaded.
How does this even work in grails anyway? Can I create a new Domain object from another object's controller with something like
Project p = new Project();
and then do a p.save()?
Download the Castor Core and Castor XML jars from here and put them in the lib directory (there's probably a better way to manage this dependency using Grails' dependency management, but this one's a quick and dirty).
With Castor introspection mode you don't need to worry about creating mapping files if your XML matches up nicely with your domains. Here's an example:
grails-app/domain/MyDomain.groovy
class MyDomain {
String foo
String bar
}
grails-app/controllers/MyController.groovy
import org.exolab.castor.xml.Unmarshaller
import java.io.ByteArrayInputStream
class MyController {
def myAction = {
def xml = '''
<myDomain>
<foo>My Foo String</foo>
<bar>My Bar String</bar>
</myDomain>
'''
def reader = new ByteArrayInputStream(xml.bytes).newReader()
def domain = (MyDomain)Unmarshaller.unmarshal(MyDomain.class, reader)
domain.save()
def count = MyDomain.countByFoo('My Foo String')
render "Found $count results"
}
}
Navigate to localhost:8080/appname/my/myAction and it should display "Found N results", N > 0.

Categories

Resources