dinsdag 3 december 2013

Time for joda time

Introduction:


Calculating time in Java is doable but it is a bit of a pain in the backside. Using the calendar, getting the days and the hours and the minutes and calculate them one by one. I been playing around with joda time and that is a relieve. They encapsulated all the complex calcuations and retrieving in methods which can be chained when necesarry.

The example:

In this example I calculate the delivery date and time of a shop. It is calculating one of those days the shop has customized times. Like normally they start at 9 in the morning but this day they start at 8.

String opening = null;
opening = "8";
String[] defaultOpenTime = defaultTime.getDefaultOpeningTime().split(":");
int defaultOpenHour = Integer.parseInt(defaultOpenTime[0]);
int customizedOpenHour = Integer.parseInt(opening);
DateTime customTime = DateTime.parse("01-12-2013");
customTime =
                customTime.hourOfDay()
                .setCopy(customizedOpenHour)
                 .minuteOfHour()
                 .setCopy(opening);
 DateTime defaultTime =
                 DateTime.now()
                 .hourOfDay()
                 .setCopy(defaultOpenHour)
                  .minuteOfHour()
                  .setCopy(defaultOpenTime[1])
                  .secondOfMinute()
                  .setCopy(00);
Hours diffHours = Hours.hoursBetween(defaultTime,customTime);
delivery = delivery.plusHours(diffHours.getHours()  + MAX_DELIVER_TIME);
if(Integer.parseInt(opening) < delivery.getHourOfDay()){
//Normally I would retreive a value from a data store and add that here instead of the          
                          opening hours.
//In this case you can only help one customer after closing hours.
delivery = delivery.hourOfDay().setCopy(opening).minuteOfHour().setCopy(opening);
delivery = delivery.plusDays(NEXT_DAY);
}

There some points I like to highlight:

In this peace of code you create a DateTime object with the date and time you desire.
customTime =
                customTime.hourOfDay()
                .setCopy(customizedOpenHour)
                 .minuteOfHour()
                 .setCopy(opening);

In this peace of code you calculate hour difference:

Hours diffHours = Hours.hoursBetween(defaultTime,customTime);

You can do this also with days, minutes and seconds.

In this piece of code you jump to the next day:

delivery = delivery.plusDays(NEXT_DAY);

You can do this also with Hours, minutes and seconds.


Conclusion

Dealing with time is much easier when you do this with the joda-time library. There is also a Joda-money library I like to play with that the next time.


Have fun!

donderdag 28 november 2013

Hibernate annotated

Introductrion

Setting up a persistence layer with Hibernate is quit easy. Actually it even improved with the annotations. A couple of years ago, when this technique was introduced, there was quite a discussion about the fact if a bean could be self persistent or not. In my personal opinion I dont like self persistent beans. But i do like annotated beans. And I believe there is a difference.

An example

A small version of the hibernate.cfg.xml based on a postgres database:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

  <session-factory>
    <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="connection.url">jdbc:postgresql://localhost:5432/mydb</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">postgres</property>
    <property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    <property name="current_session_context_class">thread</property>
    <property name="hibernate.show_sql">false</property>
  </session-factory>
</hibernate-configuration>

In the following example I did not use this but if you have multiple databases you can create more then one configuration file and read them as followed:

SessionFactory sessionFactory = new Configuration()
.configure(<PATH>hibernate.cfg.xml).buildSessionFactory();

an examples of  a annotated hibernate beans:

package com.shops.data.layer.info;



import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "customers")
public class LoginInfo {

private String username;
private String password;
private long id;

@Column(name = "password")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "username" )
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Id
@Column(name = "id")
long getId() {
return id;
}
void setId(long id) {
this.id = id;
}

}

This bean is actually filled with data coming from a service and is used to create an Criteria.

The next piece of code is an interface that is the template for every class that is going to act as a database controller.
package com.shops.data.layer.session;


public interface ShopsPersistenceController {

/**
* This method adds a customer to the database.
* @param customer contains the data from the customer.
*/
void addData(Object customer, Class annotatedClass);
/**
* This method retreives a customer from the database.
* @param loginInfo contains the login info needed for retreival.
* @param customer the customer retreived from the database.
*/
Object getData(Object selectionData, Class returnTypeClass);
/**
* updates the customer in the database.
* @param customer contains the new data for the database.
*/
void updateData(Object updataData, Class annotatedClass);
/**
* sets the flag deleted on true.
* @param customer the data needed for the database to select the right customer.
*/
void deleteData(Object deleteData, Class annotatedClass);
}

As you can see all the databaseactions as select (get) updated and delete are in place. 

The implementation class:

package com.shops.data.layer.session;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class ShopsPersistenceControllerImpl implements ShopsPersistenceController{
private SessionFactory sessionFactory;
 
    public ShopsPersistenceControllerImpl(){
    }
/**
* {@inheritDoc}
*/
public void addData(Object addData, Class annotatedClass) {
    Configuration configuration = new AnnotationConfiguration().configure().addAnnotatedClass(annotatedClass);
    sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
session.save(addData);
close(session);
}

/**
* {@inheritDoc}
*/
public Object getData(Object selectionData, Class returnTypeClass) {
Configuration configuration = new AnnotationConfiguration().configure()
.addAnnotatedClass(returnTypeClass);
sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
SqlSelector selectUserByCredentials = new SelectUserByCredentials(session);
SqlSelector sqlSelector = selectUserByCredentials.whoami(selectionData);
Object info = sqlSelector.getData(selectionData, returnTypeClass);
close(session);
return info;
}

/**
* {@inheritDoc}
*/
public void updateData(Object selectData, Class annotatedClass) {
Configuration configuration = new AnnotationConfiguration().configure().addAnnotatedClass(annotatedClass);
    sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();
    session = sessionFactory.openSession();
session.beginTransaction().commit();
session.update(selectData.getClass());
close(session);
}

/**
* {@inheritDoc}
*/
public void deleteData(Object deleteData, Class annotatedClass) {
Configuration configuration = new AnnotationConfiguration().configure().addAnnotatedClass(annotatedClass);
    sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
session.update(deleteData.getClass());
close(session);
}

private void close(Session session){
if(session.getTransaction().isActive()){
Transaction transaction = session.getTransaction();
transaction.commit();
}
session.flush();
session.close();
sessionFactory.close();

}

}

As you can see: the parameters used in all the database action methods have two parameters. One is the bean that needs to handled by the database for example deleteData. the other is annotatedClass. This is the annotated classe that is the class file needed to build the sessionFactory. this way you dont need different methods for diffent beans. 

If you have a closer look in the getData method you find the SqlSelector. This is a separate small class that contains one particular selection. This class has a method called whoami. This method is a part of the chain of responsibility pattern. This way I can chain different selections. This way I keep my contract to the outside world sain. All the services that need this persistence layer talk to it in the same way. They dont have any knowlegde about the query that is executed. This is a good thing. They should be only interested in the results.

The sql selector example:

The interface which is a part of the pattern:

package com.shops.data.layer.session;

public abstract class SqlSelector {

abstract SqlSelector whoami(Object bean);
abstract Object getData(Object selectionData, Class returnTypeClass);
}

The implementing class:

package com.shops.data.layer.session;

import org.hibernate.criterion.Restrictions;

import com.shops.data.layer.info.LoginInfo;
import org.hibernate.classic.Session;
class SelectUserByCredentials extends SqlSelector {
private  Session session;
SelectUserByCredentials(Session session){
this.session = session;
}
/**
         * finds out which bean is needed for what selection.
       **/
SqlSelector whoami(Object bean) {
SqlSelector returnSelector = null; 
if(bean instanceof LoginInfo){
returnSelector = this;
}else{
//TODO create the next sqlSelector.
}
return returnSelector;
}

        /**
         *the actual selection
        **/
Object getData(Object selectionData, Class returnTypeClass) {
LoginInfo loginInfo = (LoginInfo)selectionData;
Object info = session.createCriteria(returnTypeClass)
.add(Restrictions.eq("username", loginInfo.getUsername()))
.add(Restrictions.eq("password", loginInfo.getPassword())).uniqueResult();
return info;
}

}

The created restrictions in the criteria are an equivalent of the where clause in SQL.
the unique result gives back only one result (which is handy when people log on to your applicaton)
The Selector classes will be scoped as package. This for the simple reason that there is no reason to make them visible for the outside world.

Conclusion:

Building a persistence tier with any ORM tool can save you a lot of work. It even can save you more work and miles of code if you take care of your design. 

Try it and Have fun!

woensdag 27 november 2013

pl sql declare and use variable while concat string

Introduction

In this case I did not do anything with java but with sql. The interesting part is that, as a java developer I do not do these things every day. So lets make it memoirable.
I needed to couple two tables by ip adress of the client. But There was no foreign key to deal with. The first table had all the parts of the ip adress as numbers addr1 would be 127 addr2 would be 0 addr3 would be 0 and addr4 would be 7. In the other table the whole ip adress would appear like '127.0.0.1'. The whole selection would have a where clause by name from another table.

Solving the problem

So the first thing I needed to do was declare a variable and add the value of the ips to it with a selection over two tables based on the name of the compagny that looks like:

set serveroutput on --makes it printable
declare
  v_line varchar2(40); -- declares the var v_line
  begin
    select TO_CHAR(addr1)|| '.' || TO_CHAR(addr2) || '.' || TO_CHAR(addr3) || '.' || TO_CHAR(addr4)into v_line from ip_adress join comp on ip_adress.comp_id = comp.id where comp.name = 'my compangy'; -- TO-CHAR converts the number into a string
   --the || are the concat commands.
 dbms_output.put_line (v_line) -- prints the ipadress;
  end;
   / -- this is like an end sign dont forget it.

So now we have variable filled with a selection from the database.
In the following line You can do  a selection based on the variable:

 select * from STAT_HOURLY_SESSIONS_COUNT where STAT_HOURLY_SESSIONS_COUNT.machine = :v_line;  -- dont forget the : before the variable.

Declare the variable, and execute the query in one run.
Conclusion

If you want to build a database read the normalisation rules by Codd. Doing it like this is not improving the simpleness and performance of your database actions.

Have fun.

maandag 11 november 2013

check webresource status

   
Introduction:

Sometimes you want to know if a service is responding correctly before you give it the actual task.
With a small piece of code you can test if the response you get is an apropriate one.

The imports are from the :

<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>

The example:

boolean isUp = false;
HttpClient client = new HttpClient();
               //********************************************************
//Optional for https sessions. You can run it through a trusted proxy
        // to get the certificates.
//client.getHostConfiguration().setProxy("MyProxy", MyProxyPort);
                //********************************************************
     GetMethod method = new GetMethod("http://www.google.nl/");
     try{
         client.executeMethod(method);
         if(method.getStatusCode()==200){
                     isUp = true;
                 }


     }catch(Exception e) {
         System.err.println(e);
     }finally {
         method.releaseConnection();
     }
return isUp;

Conclusion:

It is quiet easy to check before you send your query or data to a url to check if it will respond correctly.
So have fun!

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!