Introduction
I have been working with Annotations for a while now. There are three different ways to read the information coming from these annotations. All three of them are inflicted through the Reflection API.
this.getclass.getDeclaredFields().getDeclaredAnnotations();
An annotation might look something like this:
@Retention(RetentionPolicy.RUNTIME) //you need to have this. Otherwise it does not work.
public @interface Thest {
String test(); // required
String test2() default =""; //optional
}
An annotation can handle only basic types like String, int double etc. It also can deal with Enum types.
1. Bad design:
This is the first way I found on the internet how too deal with annoations. Personally I think it is the less elegant of the three I know:
if(@test instanceof Test){
test = (@Test)test;
}
String test = test. test();
This method is not elegant because If you have a good design you know what Annotation is requested. So you dont have too test the instance.
2. Getting rid of the casts
Also casting is not necassary. If you look at what Java provides you with:
Test test =field.getAnnotation(Test.class);
This still requires a good design to get rid of the isInstance of part.
3. For the fast and furious:
Lets be honest the best thing we can do as programmers is design this baby and get rid of all the trouble that can excist. But then there is reality (Which comes with managers and deadlines) These are the moments where we need a solution in the middle:
In this example we have a bit more complex situation:
@Type (field = Field.type
@Test (value = "test")
The point I am trying to make is that if you have more then one annotation, that could be per annotated field or just in general, you might find yourself in time shortage (what is new?) and need a solution that doesnt require time too design but still gives you the oppurtunity too read all you need.
private void translateAnnotations(Annotation annotation){
String[] values = annotation.toString().split(",");
for (int i = 0; i < values.length; i++) {
String value = values[i];
if(value.startsWith(AT)){
String[] tempValue = value.split("\\.");
int arrayLength = tempValue.length-1;
value = tempValue[arrayLength];
}
createTestElements(value);
}
}
private void createTestElements(String testElement){
String part = null;
if(Character.isUpperCase(TestElement.charAt(0))){
String[] testElementParts = testElement.split("\\(");
part = testElementParts[0];
}
testElement = testElement.substring(testElement.indexOf('(') + 1, testlement.length());
String[] valueParts = testElement.split("=");
if(valueParts.length > 1){
if(testElement.endsWith(")")){
testElement = testElement.substring(0, testElement.length()-1);
}
String[] testElements = testElement.split("=");
if(testElements[0].trim().equals(TEST)){
testBean.setQuery(testElements[1]);
}
else if(testElements[0].trim().equals(ATTRIBUTE_NAME)){
testBean.setTest(AT + estElements[1]);
}
else if(testElements[0].trim().equals(ELEMENT_NAME)){
testBean.setElementName(testElements[1]);
}else if(testElements[0].trim().equals(PART)){
testBean.setType(testElements[1]);
if(part != null){
testBean.setPart(part);
}
}else if(testElements[0].trim().equals(TEST_SUB_SECTION)){
testDataBean.setTestSubSection(testElements[1]);
}
}
}
Conclusion:
The best thing you can do with annotations, design the thing so that you know who is visiting. But in some cases delivering is the main thing they put on your mind and you need something in the middle.
For design patterns have a look at: http://en.wikipedia.org/wiki/Software_design_pattern
And in this perticulair case I would be interested in the Visitor pattern.
Have Fun!
zondag 7 april 2013
zondag 9 december 2012
xml and java
Introduction:
There are several ways to deal with xml in Java. Depending on the requierements that are stated, you choose the weapons for your duel. Roughly you can divide the xml libraries that are available in Java in the following groups:
3. Sax. Simple Api for Xml.
A Sax parser does not read the whole dom object into memory but reads as a sequential stream. This makes that the resource usage, compared to the dom parsers is significant less. The downside is, that you can retreive anything back from the top ones you passed it. It is event based.
Examples of Sax parsers:
Stax libraries are stuck in the middel of Sax and Dom. It is not designed to push the data from the xml stream to the application, but vica versa. It pulls the required data into the application from the xml stream.
Examples of Stax parsers:
Axiom (parses not only Stax)
woodstox
jax
5. Xslt Extensible Stylesheet Language Transformations
Xslt is a language which can do operations on a existing xml structure, and transform this into a new xml structure. In java this means that the xml file will be parsed by a sax parser like Xerces or Crimson. From here we can use the xslt language combined with xpath queries.
Examples of xslt parsers:
XDK
Conclusion
To work with Java and Xml you need to know want and what your requirements are.
So, research and Have Fun.
There are several ways to deal with xml in Java. Depending on the requierements that are stated, you choose the weapons for your duel. Roughly you can divide the xml libraries that are available in Java in the following groups:
- Dom. Document Object Model.
- Marshalling
- Sax. Simple Api for Xml.
- Stax. Streaming Api for Xml.
- Xslt Extensible Stylesheet Language Transformations
The API's:
1. Dom:
These kind of API's create the full xml into memory and structure it in Java classes. The benefit of this is that all the information contained in the xml document is searchable and available. The downside is that, if there are several, bigger documents, it costs a lot of resources to work with it.
Examples of Dom API's are:
3. Sax. Simple Api for Xml.
A Sax parser does not read the whole dom object into memory but reads as a sequential stream. This makes that the resource usage, compared to the dom parsers is significant less. The downside is, that you can retreive anything back from the top ones you passed it. It is event based.
Examples of Sax parsers:
- Xerces (parses not only Sax)
- Axiom (parses not only Sax)
- Ælfred2, (parses not only Sax)
- Crimson, (bundled into JDK 1.4)
- Oracle's XML Parser for Java v2
- Piccolo
- The System Integration Automation Parser for XML
- XP 0.5
Stax libraries are stuck in the middel of Sax and Dom. It is not designed to push the data from the xml stream to the application, but vica versa. It pulls the required data into the application from the xml stream.
Examples of Stax parsers:
Axiom (parses not only Stax)
woodstox
jax
5. Xslt Extensible Stylesheet Language Transformations
Xslt is a language which can do operations on a existing xml structure, and transform this into a new xml structure. In java this means that the xml file will be parsed by a sax parser like Xerces or Crimson. From here we can use the xslt language combined with xpath queries.
Examples of xslt parsers:
XDK
Conclusion
To work with Java and Xml you need to know want and what your requirements are.
So, research and Have Fun.
woensdag 3 oktober 2012
Java Thread safely
Introduction.
The cycle of learning never ends but starts often. In the case where threads are used It is an interesting cycle. One of the dangers of Java is that everybody can create and run threads. But the avoiding the pitfalls is needs a bit more experience. So lets see what we can do to avoid the known pitfalls.
The pitfalls:
Lets make a list of some pitfalls:
1. The Runnable Interface
This is important. Dont overload your class with unnecessary weight by letting it inherit from Thread.
Create a Thread and feed it with your object.
2. Granuality of the synchronized parts
You can ask yourself why is that important. You can say The more I have in my synchronized block the Less can go wrong. Or Why not the whole method that is easy and save anyway.
The consideration here is performance. Threads will wait on eachother when reaching a synchronized block. So the less you put in there the better it performs.
3. Static code:
Static code is something that gives a headache in multi threaded environments. It is on class level and not on an instance level. This means it is out of the scope of the ThreadManager and out of the scope of the garbage collector. My advice in most of the cases you setup an application, use it only when necessary and don't use it in a threaded envirnonment.
4. Scoping the objects in threads:
All the objects that are accesible in multiple threads should be scoped correctly. Public accessible member are also accesible over threads. This could give the case where you are using the synchronized block to prevent the threads to alter the values of the object while this is not necessarily.
5. Order of executing the threads
As you might create a number of threads, beware of the fact that in Java you cann't predict the order in which the threads will be executed. To test copy my example and instancate the ThreadObject in multiple threads with different names.
6. Setting members to Final
The final keyword in Java is a debatable one. As it does not occur in the compiled code it seems to be useless for many developers. My personal opinion about it is: It is not useless it is a programmers safety net. You do not need it to be compiled. It is like a frontdoor lock. So even in the matter of threads we can set members to final. This helps us to prevent other programmers to change the object. and leave them with nothing else then changing the values of the members of this object.
Example of a save thread:
public class NewThread {
/** this one is running in the main thread to execute the application.
* Dont use it as something that lives in one of your threads.
**/
public static void main(String[] args){
ThreadObject threadObject = new ThreadObject();
threadObject.setName("Pieter");
Thread thread = new Thread(threadObject);
thread.start();
}
public class ThreadObject implements Runnable {
private String name;
public String getName() {
/**
* HERE COULD HAVE BEEN SOME OTHER CODE
*/ synchronized (name) {
return name;
}
/**
* HERE COULD HAVE BEEN SOME OTHER CODE
*/
}
protected void setName(String name) {
/**
* HERE COULD HAVE BEEN SOME OTHER CODE
*/
synchronized (name) {
this.name = name;
}
/**
* HERE COULD HAVE BEEN SOME OTHER CODE
*/
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
System.out.println(getName());
}
Have fun!
The cycle of learning never ends but starts often. In the case where threads are used It is an interesting cycle. One of the dangers of Java is that everybody can create and run threads. But the avoiding the pitfalls is needs a bit more experience. So lets see what we can do to avoid the known pitfalls.
The pitfalls:
Lets make a list of some pitfalls:
- Use the Runnable Interface
- Granuality of the synchronized parts
- Static code
- Scoping the objects in the threads.
- Order of executing the threads
- Setting members to Final
1. The Runnable Interface
This is important. Dont overload your class with unnecessary weight by letting it inherit from Thread.
Create a Thread and feed it with your object.
2. Granuality of the synchronized parts
You can ask yourself why is that important. You can say The more I have in my synchronized block the Less can go wrong. Or Why not the whole method that is easy and save anyway.
The consideration here is performance. Threads will wait on eachother when reaching a synchronized block. So the less you put in there the better it performs.
3. Static code:
Static code is something that gives a headache in multi threaded environments. It is on class level and not on an instance level. This means it is out of the scope of the ThreadManager and out of the scope of the garbage collector. My advice in most of the cases you setup an application, use it only when necessary and don't use it in a threaded envirnonment.
4. Scoping the objects in threads:
All the objects that are accesible in multiple threads should be scoped correctly. Public accessible member are also accesible over threads. This could give the case where you are using the synchronized block to prevent the threads to alter the values of the object while this is not necessarily.
5. Order of executing the threads
As you might create a number of threads, beware of the fact that in Java you cann't predict the order in which the threads will be executed. To test copy my example and instancate the ThreadObject in multiple threads with different names.
6. Setting members to Final
The final keyword in Java is a debatable one. As it does not occur in the compiled code it seems to be useless for many developers. My personal opinion about it is: It is not useless it is a programmers safety net. You do not need it to be compiled. It is like a frontdoor lock. So even in the matter of threads we can set members to final. This helps us to prevent other programmers to change the object. and leave them with nothing else then changing the values of the members of this object.
Example of a save thread:
public class NewThread {
/** this one is running in the main thread to execute the application.
* Dont use it as something that lives in one of your threads.
**/
public static void main(String[] args){
ThreadObject threadObject = new ThreadObject();
threadObject.setName("Pieter");
Thread thread = new Thread(threadObject);
thread.start();
}
public class ThreadObject implements Runnable {
private String name;
public String getName() {
/**
* HERE COULD HAVE BEEN SOME OTHER CODE
*/ synchronized (name) {
return name;
}
/**
* HERE COULD HAVE BEEN SOME OTHER CODE
*/
}
protected void setName(String name) {
/**
* HERE COULD HAVE BEEN SOME OTHER CODE
*/
synchronized (name) {
this.name = name;
}
/**
* HERE COULD HAVE BEEN SOME OTHER CODE
*/
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
System.out.println(getName());
}
Have fun!
donderdag 27 september 2012
keep on scoping on different packages
Introduction:
Scoping the methods and constructors the right way can be quite a headache. In a lot of libraries I see that most of the classes are public accessable. This makes it for the user of those libraries confusing to use. So to keep myself in shape I write this little reminder.
Scoping
Public class Scoping{
public String publicScope;
protected String protectedScope;
String packageScope;
private privateScope;
}
If you write a library that can be used by others, I think with the design, the word userFriendly should be considered.
Beside good and working examples and completed documentation scoping can be helpfull. If your contract is one of the few things which is accesible, mistakes by your users (other programmers) are made less.
One of the last things I show as an example is a small trick to avoid using public when you are using classes from different packages:
package example.superclass;
public abstract class SuperClass{
protected String protectedScope;
protected String getProtectedScope{
return this.protectedScope;
}
protected String setPrivateScope(String privateScope){
this.protectedScope = protectedScope;
}
}
package example.subclass;
public class SubClass{
protected String getProtectedScope{
return super.protectedScope;
}
protected String setPrivateScope(String privateScope){
super.protectedScope = protectedScope;
}
}
package example.superclass;
public class callSubClassThroughSuperClass{
SuperClass class = new SubClass();
public static void main(String[] args){
class.setProtectedScope("scope has been set");
System.out.println(class.getProtectedScope);
}
}
As you noticed are the class callSubClassThroughSuperClass and the SuperClass in the same package. This makes the protected methods of the SuperClass accesible for this class. The SubClass
is in a different package and accesses the protected methods through inheritence. This way you can bridge the distance between two packages and still use a scoping that protects usages from the outisde.
Have fun!
Scoping the methods and constructors the right way can be quite a headache. In a lot of libraries I see that most of the classes are public accessable. This makes it for the user of those libraries confusing to use. So to keep myself in shape I write this little reminder.
Scoping
- Public methods and constructors are accesible everywhere in your application and also in the applications that are using your application as a library.
- Protected methods are only accesible inside the package where the classes are and outside when inherited.
- Package aka scope or friendly, is only accesible inside the package including inherited.
- Private is only accesible inside the class scope.
- Local is only accesible inside the method where it is declared.
Public class Scoping{
public String publicScope;
protected String protectedScope;
String packageScope;
private privateScope;
}
If you write a library that can be used by others, I think with the design, the word userFriendly should be considered.
Beside good and working examples and completed documentation scoping can be helpfull. If your contract is one of the few things which is accesible, mistakes by your users (other programmers) are made less.
One of the last things I show as an example is a small trick to avoid using public when you are using classes from different packages:
package example.superclass;
public abstract class SuperClass{
protected String protectedScope;
protected String getProtectedScope{
return this.protectedScope;
}
protected String setPrivateScope(String privateScope){
this.protectedScope = protectedScope;
}
}
package example.subclass;
public class SubClass{
protected String getProtectedScope{
return super.protectedScope;
}
protected String setPrivateScope(String privateScope){
super.protectedScope = protectedScope;
}
}
package example.superclass;
public class callSubClassThroughSuperClass{
SuperClass class = new SubClass();
public static void main(String[] args){
class.setProtectedScope("scope has been set");
System.out.println(class.getProtectedScope);
}
}
As you noticed are the class callSubClassThroughSuperClass and the SuperClass in the same package. This makes the protected methods of the SuperClass accesible for this class. The SubClass
is in a different package and accesses the protected methods through inheritence. This way you can bridge the distance between two packages and still use a scoping that protects usages from the outisde.
Have fun!
woensdag 19 september 2012
split a String and keep the token
Sometimes you want to split a String but still need the token for finding the parts you need. I setup an example to deal with this:
You have a String that contains a list of friends. All you want is to print out those names and not the first part of the String.
private void checkNames(){
String name = "This is a list with friends, Fred, Ted, Robert,Maria, Roberta, Kaya";
String splitExp = "(?=[:,])"; //The last char in the brackets [] is the token in our case the comma.
String[] splittedNames = name.split(splitExp);
for (int i = 0; i < splittedNames.length; i++) {
if(splittedNames[i].startsWith(",")){
//print it remove the comma and spaces
System.out.println(splittedNames[i].substring(1).trim());
}
}
This will give you a clean list of your friends names.
Have fun.
You have a String that contains a list of friends. All you want is to print out those names and not the first part of the String.
private void checkNames(){
String name = "This is a list with friends, Fred, Ted, Robert,Maria, Roberta, Kaya";
String splitExp = "(?=[:,])"; //The last char in the brackets [] is the token in our case the comma.
String[] splittedNames = name.split(splitExp);
for (int i = 0; i < splittedNames.length; i++) {
if(splittedNames[i].startsWith(",")){
//print it remove the comma and spaces
System.out.println(splittedNames[i].substring(1).trim());
}
}
This will give you a clean list of your friends names.
Have fun.
maandag 27 augustus 2012
JSTL Velocity or Freemarker
Introduction:
After a couple of years of experience, I tried different ways to deal with beans and pages. There are many ways to deal with this. Most of the times I used JSTL, Freemarker, Velocity or the spring Taglibs. Now i am trying to get clear what is the best way of dealing I can use.
Why jstl:
I used jstl a lot for the coupling of the beans and the jsp's. This still gives you the freedom to use also the java <%%> tags. In my opinion it is not wise to do this simply of the fact, that you run into the risk of starting to use business logic in the jsp's which is straight against the mvc pattern and the multi tier architecture. The only real downside of the JSTL's for me: is that for different functions you need different libraries declared in your jsp:
- Core tags
- Formatting tags
- Sql tags
- xml tags
The only taglib I do not like to use is the sql tags. I believe that this kind of functionality should be left to handled by the persistence tier.
The conclusion for using JSTL is: It is a very usefull set of libraries which can help you to create a good separation of your model and view. It still offers a lot of freedom which should be handled thoughtfully. In an development tool as Eclipse you might experience that this tool does not see it as on the classpath and gives compile errors in that sense. At runtime this example will work.
An examples:
//This is the jstl import
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
//Looping through a list of names in the items you have//
//to declare the full path. In this case it a list in the customer class.//
<c:forEach var="costumerNames" items="${com.my.customer.names}">
//printing the names in al HTML list.//
<LI> <c:out value="${customerNames.name}"/> </LI>
</c:forEach>
Why velocity
Velocity brings you the freedom to use their templates only or embed them in a Jsp. The bridging between the model and view. The plus of Velocity against the JSTL is that it works in different areas of your application. You can as easily use it for pages as for the layout for automated emails. It has a lot more functionality which makes it much more flexible to work with. Instead of bringing extra technology into the Jsp, there is an template created a .vm file, wich is compiled into a view.
The conclusion:
If there is a need for a lot of flexibility even in a legacy system where there are allready Jsp's velocity is a flexible tool.
- It adapts to many application areas
- It offers a simple, clear syntax for the template designer
- It offers a simple programming model for the developer
- Because templates and code are separate, you can develop and maintain them independently
- The Velocity engine easily integrates into any Java application environment, especially servlets
- Velocity enables templates to access any public method of data objects in the context
an example for a web app:
The servlet.xml example:
<!-- register servlet
dont take this part to letterly. This is als depending on the frontend
framework you are using.
-->
<servlet> <servlet-name>applicationServlet</servlet-name> <servlet-class>my.velocity.VelocityServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>applicationServlet</servlet-name> <url-pattern>/myApplication</url-pattern> </servlet-mapping> <!-- mapping all .vm files to velocity servlets --> <servlet> <servlet-name>velocity</servlet-name> <servlet-class>org.apache.velocity.tools.view.servlet.VelocityViewServlet</servlet-class> <!-- load my toolbox --> <init-param> <param-name>org.apache.velocity.toolbox</param-name> <param-value>/WEB-INF/toolbox.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>velocity</servlet-name> <url-pattern>*.vm</url-pattern> </servlet-mapping>
The toolbo.xml example (place it in the WEB-INF):
<toolbox> <tool> <key>date</key> <scope>application</scope> <class>org.apache.velocity.tools.generic.DateTool</class> </tool> </toolbox>
The java part:In this part you have to create a bean with a member "name" that has getters and setters. With whatever framework you use as frontend technology (serlets, struts,spring, etc...) set this as a request parameter with the name "name". This,
ofcourse comes back in the html.
The html part:<h2> $name is using velocity</h2>
Why freemarker
Freemarker is an template engine, which might be seen as simular to Velocity. The difference in what they
can do sits in the functionality they have. If you have light requirements Velocity is the answer
to your question on the other hand if you like one of the following functionalities out of the box
you might consider using Freemarker:
Number and date support
|
An example:
The java class:
//Freemarker configuration object
Configuration cfg =
new
Configuration();
try
{
//Load template from source folder
Template template = cfg.getTemplate(
"src/helloworld.ftl"
);
// Build the data-model
Map<String, Object> data =
new
HashMap<String, Object>();
data.put(
"message"
,
"Hello World!"
);
//List parsing
List<String> countries =
new
ArrayList<String>();
countries.add(
"India"
);
countries.add(
"United States"
);
countries.add(
"Germany"
);
countries.add(
"France"
);
data.put(
"countries"
, countries);
// Console output
Writer out =
new
OutputStreamWriter(System.out);
template.process(data, out);
out.flush();
// File output
Writer file =
new
FileWriter (
new
File(
"C:\\FTL_helloworld.txt"
));
template.process(data, file);
file.flush();
file.close();
}
catch
(IOException e) {
e.printStackTrace();
}
catch
(TemplateException e) {
e.printStackTrace();
}
}
The ftl Code:
<#list countries as country>
${country_index + 1}. ${country}
</#list>
The output:
1. India
2. United States
3. Germany
4. France
I hope this helps to choose the tool you need. I started out a new project and decided to use the jstl and the spring taglibs. They provided me with all I need.
But if I need something heavier the next time I might use Velocity or Freemarker to suit my needs.
Have fun!
maandag 6 augustus 2012
resizing images on the fly
Intro:
After determining where the files are and how to move them into another folder as I showed in my previous post Howto create a set of files on the fly, It is fun to resize the files which are images in this case (makes it easier).
The problem:
We have a set of images, which might change and dont want to resize them by hand everytime.
The solution:
The solution lies hidden in Java as many times. The following example shows howto resize:
A working version or the sources you can download from:
http://sourceforge.net/projects/imageicon/files/imageicon-1.0-SOURCES.jar/download
Or check out the sources from:
ssh://git.code.sf.net/p/imageicon/code
After determining where the files are and how to move them into another folder as I showed in my previous post Howto create a set of files on the fly, It is fun to resize the files which are images in this case (makes it easier).
The problem:
We have a set of images, which might change and dont want to resize them by hand everytime.
The solution:
The solution lies hidden in Java as many times. The following example shows howto resize:
private void createIcons(String path){
int width=100;
int height = 100;
File imageInput = File(path);
ImageIcon imageIcon = new ImageIcon(path);
BufferedImage imageResize =
new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2d = imageResize.createGraphics();
graphics2d.addRenderingHints(
}
new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
graphics2d.drawImage(imageIcon.getImage(), 0, 0, height, width,
null);
String iconName = path.replaceAll(
IMAGES, ICONS);
try {
ImageIO.write(imageResize,
"png", new File(iconName));
}
catch (IOException ioe) {
LOGGER.error("The image " + iconName + " could not be saved!");
}
In my previous post I had a line "String filePath =path.replace(IMAGES, ICONS); " all you have to do is to replace that line with: "createIcons(image.getAbsolutePath());" and you be on your way with a full subset of folders and resized images. The only kind of images I had it never working with was BMP.
A working version or the sources you can download from:
http://sourceforge.net/projects/imageicon/files/imageicon-1.0-SOURCES.jar/download
Or check out the sources from:
ssh://git.code.sf.net/p/imageicon/code
have fun.
Abonneren op:
Posts (Atom)