12/08/2011

Proxy Pattern Presentation

11/25/2011

Linux Crontab

Crontab is a tool for adding periodic tasks to a specific user. You can edit the crontab with the following command and add your own periodic tasks.
crontab -e
Crontab entry format is as below:
* * * * * [command to be executed]
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)
And here is a sample crontab entry:
0 * * * * /bin/ksh /opt/oracle/report/scripthourly.sh
0 * * * * /usr/bin/find /opt/oracle/report/mdsphourly/ -name "*.csv" -ctime +1 -delete

11/13/2011

GraphViz Java

I will introduce Java api for GraphViz. In order to use this api, these are the steps you have to follow:

  • You have to first download graphviz application for your OS.
    You will need dot.exe location in order to run the application correctly.
  • In the java api link, you should download the source file. (GraphViz.java)
  • Include this source to the project.
  • You should change the following variables according to your preference and installation.
    TEMP_DIR may be any folder.
    DOT is the location of the dot.exe in graphviz installation folder.
  • Write this main method in any class and test your installation and output.
    import java.io.File;
    
    public class GraphVizExample {
        public static void main(String[] args) {
            GraphViz gv = new GraphViz();
            gv.addln(gv.start_graph());
            gv.addln("A -> B;");
            gv.addln("A -> C;");
            gv.addln(gv.end_graph());
    
            String type = "gif";
            File out = new File("D:/out." + type);
            gv.writeGraphToFile(gv.getGraph(gv.getDotSource(), type), out);
        }
    }
    
  • This application will generate a graph to the file D:/out.gif
  • The output image should be:
  • You can generate more complex graphs by applying the dot language specification.
You should change some functions for example GraphViz.start_graph() function to change the graph type.

9/21/2011

Inbox Zero

I have just adopted the inbox zero. Inbox zero means nothing but anything to anyone in the world. It means that "Do something for your emails. Do not just read and let them stay in your inbox!" You can find a slide for inbox zero in the references.
One simple rule is "You have to do one of the following for your emails: Delete, delegate, respond, defer, do." Then your inbox will be your some kind of to-do list. It will be clean, it will plan your jobs and so on.
I know that there are many planning, to-do or calendar applications/web pages in action but I use this for simplicity and don't forget, it is email-related.

Ref: Inbox Zero Slide from Merlin Mann

8/25/2011

Status Change

I began PhD study in the University of Alabama in Computer Science area. From now on, I will be posting from my doctoral studies and courses. I hope it will be useful again.

7/07/2011

Chained Invocation

Chained invocation is a matter of language design actually. I first saw this type of invocation in the Rest-assured library. I will not introduce library here, maybe later.

You know java setter methods are void functions. By using chained invocation, we may use void-setters as a builder, simply returning the object (this) in every setter. Idea is simple but very useful. Also chained invocation is not for setters only, every void function can implement the logic for the readability of the code.

Below there is a simple class with some void setters.
class Simple {

    int x;
    int y;

    public void setX(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getY() {
        return y;
    }

}

This class can be instantiated in the code by this way:
Simple s = new Simple();
s.setX(4);
s.setY(5);

Instead, we can change the class to the following by just manipulating the setters. And the usage will be readable.
class Simple {

    int x;
    int y;

    public Simple setX(int x) {
        this.x = x;
        return this;
    }

    public int getX() {
        return x;
    }

    public Simple setY(int y) {
        this.y = y;
        return this;
    }

    public int getY() {
        return y;
    }

}

We can use it in the code:
Simple s = new Simple();
s.setX(4).setY(5);

We have done the following:
  • Change the return type 'void' of the setters to the class type itself
  • Add 'return this' to the last line of each setter

Maybe the example is not suitable, but the logic.

Ref: A proposal from the Matthias Ernst
Java 7 features/exclusions on Pure Danger Tech

6/04/2011

Intelligent Alarm

Yesterday while I was hanging around, I realized that the built-in alarm program of my cell phone is not enough for me to be woken up. So I started searching a new and a functional program. At last I found it from the Ovi Store. The program is SPB Time. The alarm modes of the program is crazy. It has three modes; normal alarm, paranoid alarm and bio alarm.
Here I will introduce paranoid alarm. Since the settings are exactly the same, I will pass it. You are setting the time when the alarm will be active and the show begins after it.
When the time comes, your screen will be like this:
Don't worry after seeing this screen. But you need to be smart and AWAKE enough to press the numbers in ascending order. And the alarm continues to ring and disturb you. Don't worry if you can't finish pressing the numbers. After some time (and alarm is still ringing), the program will show you an easier version to press like in this figure:
Till this point, you already tried enough to break the code (!) and to snooze or dismiss the alarm. But if you still do not manage it, the last screen will come. It's easy, I guarantee. In the following screen, I think you can solve the puzzle:
The idea is simple. You must be AWAKE enough to turn off the alarm.

Ref: SPB Time

5/27/2011

Chain of Responsibility Pattern

Chain of responsibility patterns is used when we want to divide a control logic into pieces. The most common implementation is an email handler mechanism. In this mechanism, we will have an Handler interface and some classes implementing this Handler interface.


All requests will come to the first handler. After the first handler handles the requests whose rules are defined in its class, it will pass the control (remaining requests) to second handler. This flow will continue until all requests handled.

Sort the handlers from the most used to the least. By this way, unnecessary or least used ones will not work so often.


Ref: Head First Design Patterns

5/18/2011

Logging with Spring AOP

We will simply implement three advice interfaces of aop. First, let's create a class that implements ThrowsAdvice for intercepting when an exception occurs, AfterReturningAdvice for intercepting after the method and MethodBeforeAdvice for intercepting before the method.
public class LoggingBean implements MethodBeforeAdvice,
                                    AfterReturningAdvice,
                                    ThrowsAdvice {

    public LoggingBean() { }

    public void afterThrowing(Method invokedMethod,
                              Object[] parameters,
                              Object invokedClass,
                              Exception exp) {

    // do logging here after an exception
    }
 
    @Override
    public void before(Method invokedMethod,
                       Object[] parameters,
                       Object invokedClass) throws Throwable {

    // do logging here before method

    }

    @Override
    public void afterReturning(Object returnVal,
                               Method invokedMethod,
                               Object[] parameters,
                               Object invokedClass) throws Throwable {

    // do logging here after method

    }

}
As you can see, you can use any values needed for logging from parameters of the methods (returnVal, invokedMethod, parameters, invokedClass).

Now we will introduce this bean to spring in a xml file. And we will also create a bean from BeanNameAutoProxyCreator for intercepting the requested beans with the above class.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 <bean id="logger" class="LoggingBean"/>
 
 <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
 
  <property name="beanNames">
   <list>
    <value>*Service</value>
    <value>*Client</value>
   </list> 
  </property>
  
  <property name="interceptorNames">
   <list>
    <value>logger</value>
   </list>
  </property>
 
 </bean>

</beans>
In the beanNames property, we are selecting which spring beans to apply the interceptor (in the example, we are applying the filter to the beans those names end with Service or Client) and in the interceptorNames property, we are selecting the interceptors.

That's all. You can now log your methods before and after execution, also after throwing an exception.

Ref: Spring BeanNameAutoProxyCreator JavaDoc
A Knol About Spring Aop

4/29/2011

Mapping JSON String to Bean

In this post, we will receive a json formatted string from a server or somewhere and try to map it directly to a matching java bean. For this reason, first, we have the following classes:
public class Account {

    String accountNo;
    String bankName;

    // getters and setters here!

}
public class UserInfo {

    String userID;
    String userName;
    String birthday;

    Account bankInfo;

    List<String> favoriteMovies;

    // getters and setters here!

}
Suppose you receive the following string from a server as response to some request:
{
    "accountNo" : "11833",
    "bankName" : "SopBank"
}
And you want to map this string a an already existing bean. First, we have to create a JSONObject from this string with the following line:
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(receivedJsonString);
Now we can map it to an account bean using JSONObject's toBean method:
Account newAccount = (Account) JSONObject.toBean(jsonObject,Account.class);
Now newAccount object will be:

Now we will map a class that has some other class types in it (other than primitives). Suppose you received the following json formatted string:
{
    "userID" : "HBSS234HSB",
    "userName" : "Cem Yilmaz",
    "birthday" : "01/01/1986",
    "bankInfo" : {
        "accountNo" : "11833",
        "bankName" : "SopBank"
    },
    "favoriteMovies" : [
        "Eternal Sunshine",
        "Fight Club",
        "Av Mevsimi"
    ]
}
Again we will create a JSONObject from this string:
JSONObject jsonObject2 = (JSONObject) JSONSerializer.toJSON(receivedJsonString);
This time we will introduce the non-primitive attributes of the UserInfo class to toBean method with a class map. This class map consists of attribute names and corresponding classes:
Map<String, Class> itemMap = new HashMap<String, Class>();
itemMap.put("bankInfo",Account.class);
Now we can create a UserInfo instance:
UserInfo userInfo = (UserInfo) JSONObject.toBean(jsonObject2,UserInfo.class,itemMap);
Now userInfo object will be:

Ref: http://json-lib.sourceforge.net/

4/25/2011

Creating JSON String From Bean - 2

I have to say one more thing about JsonConfig class. Suppose you have a bean with not only primitive objects (like String, int etc.), but also some other classes.

Suppose your class structure is as follows. You have a Person class:
public class Person {

    String name;
    String surname;

    // getters and setters here!

}
And you have a family class that has some persons in it:
public class Family {

    Person mother;
    Person father;
    String anniversary;

    // getters and setters here!

}
Now let's create some instances:
Person person1 = new Person();
person1.setName("Münir");
person1.setSurname("Özkul");

Person person2 = new Person();
person2.setName("Adile");
person2.setSurname("Naşit");

Family family = new Family();
family.setFather(person1);
family.setMother(person2);
family.setAnniversary("01/01/1986");
Now we want JSON String of this family class. All we have to do is create a JsonConfig instance and set its classmap.
JsonConfig jsonConfig = new JsonConfig();

jsonConfig.setRootClass(Family.class);

Map<String,Class> itemMap = new HashMap<String,Class>();
itemMap.put("mother",Person.class);
itemMap.put("father",Person.class);

jsonConfig.setClassMap(itemMap);
In this classmap, we will add each non-primitive attribute of the root class (in this case Family) to the map with its corresponding classes. In this way, JSONObject will know how to call the getter and setter of this attribute.
Now we will again pass jsonConfig instance to fromObject method:
String resultJson = JSONObject.fromObject(family,jsonConfig).toString();
resultJson will be:
{
    "anniversary" : "01/01/1986",
    "mother" : {
            "name" : "Adile",
            "surname" : "Naşit"
    },
    "father" : {
            "name" : "Münir",
            "surname" : "Özkul"
    }
}

Ref: http://json-lib.sourceforge.net/

4/22/2011

Creating JSON String From Bean

I will use net.sf.json.* package for JSON processing. You can find the documentation and library files from here: http://json-lib.sourceforge.net/

Suppose you have the following class:
public class UserInfo {               

    String id;
    String userName;
    String birthPlace;

    // getters and setters here!

}
First, let's create an instance:
UserInfo userInfo = new UserInfo();
userInfo.setId("BFASHRGHFG");
userInfo.setUserName("User1");
userInfo.setBirthPlace("Madrid");
You can create JSON formatted string from this class with the following line:
String resultJson = JSONObject.fromObject(userInfo).toString();
resultJson will be:
{ "id" : "BFASHRGHFG", "userName" : "User1", "birthPlace" : "Madrid" }
We may want some fields not to be included in resulting json string, then we will create a JsonConfig instance and set exclude list of this instance:
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[] { "id" });
Then we may use this configuration as another parameter to fromObject method:
String resultJson = JSONObject.fromObject(userInfo,jsonConfig).toString();
resultJson will be:
{ "userName" : "User1", "birthPlace" : "Madrid" }

4/20/2011

Hoşgeldim

Hemen lafa girelim. Bu blogda ara sıra karaladıklarım, J2EE hakkında gerçekte uygulanmış çözümler ve paylaşmak istediğim yeni teknolojiler ve programlama örneklerini bulacaksınız. Çoğu, işyerimde kendimin denediği örnekler olacak. Ayrıca karşılaştığım sorunları, çözüm bulduğum siteleri ve teknolojileri de gönderiyor olacağım. Umarım devamlı bir blog olur.