vrijdag 16 augustus 2013

reading properties from tomcat

Introduction

This actually an issue I ran into more then one time. Howto read and test properties needed from the conf folder on the tomcat server. The solution is quit simple.

The solution
             
               // get the conf folder inside the catalina home folder
File configDir = new File(System.getenv("CATALINA_HOME"), "conf");
               // reading the property file
File configFile = new File(configDir, propertyFileName);
InputStream properties = null;;
try {
                       //read it as a stream
                  properties = new FileInputStream(configFile);
                        //load the the stream into java.util.properties.
this.properties.load(properties);
} catch (FileNotFoundException fnfe) {
LOGGER.error("could not find   properties " + fnfe.getMessage());
} catch (IOException ioe) {
LOGGER.error("could not access  time properties " + ioe.getMessage());

}

have fun!

dinsdag 25 juni 2013

Component based development

Introduction

In my humble opinion component based development helps the developers in the maintance lifecycle of the product. this does not mean that the development time is longer. That totally depends on  how you setup your development process. What I mean is that during development You need to think about the design and what are the components that you are going to build. Interesting part of this is, that you have to think before you start. In the maintenance mode it is easier. The code is organized, much smaller and dont forget the separation of concerns and contracting that allready should been dealth with.
One of the first questions that pops up, is on what level do I build components. A layer like the web, business or a persistence layer could allready be called a component. You can take this up to functionality that is a component inside for example a layer. It could be even a part of the functionality that becomes a component.

That the granuality of this design can give you a bit of a headache is obvious. You can  see components as separate, individual working applications. This means that you have to package and assemble. Every component can be come for example a jar file and the application is nothing but an assembled puzzle of jar files dealing with the functionality as requested. The second option you have is: you dont package them but still create a fully working application and deal with the contracting part. This way you have embedded components. This is not very helpfull for distribution and standarisation. It also creates the pitfall that contracting and separation of concerns is neglected and in the end you still create god classes and the end product will be a moloch.

Why component based development

1. Flexibility
2 Re-usability
3. Maintainability
4. distribution of components.
5. standardization organization wide.

1. flexibility

The flexibility lies the most in the fact that it is a small independent application. It has its own contracts to deal with the outside world and it does only need things as property files that are defined inside of it. This makes it  extremely adaptable to the outside world. Actually it is the other way around. The outside world is adapting to our component. The component has a contract and all it wants is us to follow that contract.

2. reusability

With the flexibility comes the reusabiltiy Here also counts that the world has to adapt to our litle component. As long everybody applies to the contract it can be used in any part of the application you like. You dont need to copy or duplicate it. If you want some extended code to do something else in a another part of the code, you just wright a piece of code that adapts to those wishes. Depending if it is part of the original functionality you add as part of the component or leave it outside.

3. Maintainability

The maintainability is in fact another item that is handled by the contracting and the piece of code being small.
The contracting part makes it easier because of the fact that the component  is not depending on the state of the calling component. It only gets the desired data through te contract. So rebuilding our small component will have no effect on the the rest if of the code. Keep in mind, the only time that it effects the caller component, is because you changed the contract. I think that a small island of code in the case of maintainability speaks for it self.

4. Distrubtion of components

Why should we limit the bounderies of a component which is working indepedently to the borders of our first component build application. It is so easy to extract this component from its habitat and move it to another application. The only think you might want to take care of in this case is versioning.  Different applications might not update at the same time. but that is quite easy solvable with toolings like maven and artifactory. Or any other tool  you prefer.

5 standarisation organisation wide

If we continue the path of distrubution of components, then we can state that a component could be something that is used by every application in the compagny. Why should you build your own if it allready exists. That way we can standarize.

What are the pitfalls:

1. you have to come up with a good design.
2. It is necessary to follow up this design during development
3. discuss the parts  that are grey area if it becomes part of layers
Think about transaction handling, remote connection handling etc..
4. unclear requirements or conflicts between usability or reusabilty

Conclusion:

In general I would say that the development of components based application can save time in development and maintenance. the trick is to design and set it up correctly. Take care of the pitfalls before you reach them. In follow up of faster development you will also have faster time to market.

Have fun!

maandag 13 mei 2013

setting up a restfull service

Prologue:

Most of the time, when  we need a webservice we setup a soap service. With tools like Spring and jax-ws this became quite easy. Sometimes You need a service but soap is too much and too complicated. So we rely on rest.

The biggest difference between SOAP and  restfull is: soap is a xml structured protocol on top of the http protocol. Rest is still hitching along on the http protocol. Beside the states get and post you can also use put and delete.

Setting up:

The setup of a rest service is allmost as easy as setting up a soap service. You can use maven3 for the dependency management. The pom would look something like this:


  <dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1-ea</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.17.1</version>
</dependency>
  <dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.17.1</version>
</dependency>
  <dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>simplerestservice</finalName>
  </build>

Ofcourse you can download the libraries manually and put them in the WEB-INF/lib folder.

The code:


@Path("test")
public class AutoComplete {

@GET
@Produces("text/plain")
public String getAutoComplete(){
return "this will get some data";
}

@DELETE
@Produces("text/plain")
public String getAutoComplete2(){
return "this is the functioanality too delete.";
}


All the annotations you see here are the jax-ws-rs annotations (The dependency is in the pom).
The @path annotation is responsible for initializing the endpoint of this service. In this case the url would look something like : http:mypersonaldomain.com/test. This will be for the get and the delete. In javascript or html you will set the http method to get or delete in this case.
For example : <form method = "GET"/> or <form method = "DELETE"/>

Conclusion:

Sometimes it is wise to reconcider if a soap service is what you need. If it is a simple webservice that handles  only data in the end, you might concider using a restfull service.

Have fun!


zondag 7 april 2013

Annotations

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 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:

  1. Dom. Document Object Model.
  2. Marshalling
  3. Sax. Simple Api for Xml.
  4. Stax. Streaming Api for Xml.
  5. 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:
2. Marshalling

Marshalling is the technique where an object (xml in our case) is transformed in a suitable and workable object which can be used for transformation or storage.

Examples of Marshalling libraries 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:
4. Stax. Streaming Api for Xml.

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. Use the Runnable Interface
  2. Granuality of the synchronized parts
  3. Static code
  4. Scoping the objects in the threads.
  5. Order of executing the threads 
  6. 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 finalThis 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
  1. Public methods and constructors are accesible everywhere in your application and also in the applications that are using your application as a library. 
  2. Protected methods are only accesible inside the package where the classes are and outside when inherited.
  3. Package aka scope or friendly, is only accesible inside the package including inherited. 
  4. Private is only accesible inside the class scope.
  5. Local is only accesible inside the method where it is declared. 
 Examples

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!