I will present a few tricks I'm using systematically to create Java applications easily supervisable ( the best practices I'm following ). My first POST, on that subject, will introduce how I'm using JMX to deliver peaces of software that will be correctly managed and monitored by the team of technicians in charge of it.
1 - JMX (Java Management Extensions) and MBeans objects
2 - Using MBeans to make the application configurable 'in live'
3 - Why using this standard
4 - Persisting the MBean in an XML file
@XmlRootElement(name="test")
public class Test implements TestMBean {
@XmlElement(name="count")
@Override
public Integer getCount() {
return(this.count);
}
@Override
public void setCount(Integer count) {
this.count=count;
}
/**
* persist in the XML File
*/
protected synchronized void save() {
try {
Marshaller ma = context.createMarshaller();
ma.marshal(this, new File(configFileName));
} catch(Exception e) {
System.err.println("unable to save file"+e.getMessage());
}
}
/**
* construct the MBean from the XML file
* @param xmlFileName
* @return
*/
protected static Test makeFromXMLFile(String xmlFileName) {
File configFile = new File(xmlFileName);
Test result = null ;
if (configFile.exists()) {
try {
Unmarshaller un = context.createUnmarshaller();
result=(Test) un.unmarshal(configFile);
} catch (Exception e) {
throw new RuntimeException("unable to read config file",e);
}
}
if (result==null) {
result = new Test();
}
result.configFileName = xmlFileName ;
result.save();
return(result);
}
private Integer count ;
private String configFileName;
private final static JAXBContext context ;
static {
try {
context = JAXBContext.newInstance(Test.class);
} catch (JAXBException e) {
throw new RuntimeException("Programmatic error :",e);
}
}
}
As you can see in this exemple, you just need to add some very simple annotations on the bean's properties you want to be saved in the XML file : that's what we did on the Count MBean attribut.
5 - Conclusion
Don't hesitate to provide many MBeans in your software : with a very little cost, you will be able to deliver an application configurable in live, easily monitored and managed.
Aucun commentaire:
Enregistrer un commentaire