Tuesday, July 12, 2011

AOP - Notes on Pointcuts

A pointcut has the following syntax: [access specifier] pointcut pointcut-name([args]) : pointcut-definition.

There are five parts of a pointcut as shown above:
1. access specifier
2. pointcut keyword
3. pointcut name
4. pointcut arguments
5. pointcut definition

Pointcut definition consists of pointcut type and pointcut signature, it can be seen as defined-join-point to be captured. To keep things simple, lets list some of the most commonly used pointcut type:

1. execution(MethodSignature) : Method or constructor execution, i.e. execution(public void edu.mat.hello.MessageCommunicator.deliverGlobalMessage(String)) which means capture all join point on the execution of method deliverGlobalMessage in class MessageCommunicator.

2. call(MethodSignature) : Method or constructor call, i.e. call(public void edu.mat.hello.MessageCommunicator.deliverGlobalMessage(String)) which means capture all join points on the calling of method deliverGlobalMessage in class MessageCommunicator.

3. staticinitialization(TypeSignature) : Class initialization, i.e. staticinitialization(edu.mat.hello.MessageCommunicator) which means capture all join points on MessageCommunicator class loading.

4. get(FieldSignature) : Field read access, i.e. get(private String edu.mat.hello.MessageCommunicator.name) which means capture all join points on getter method of private variable name in class MessageCommunicator.

5. set(FieldSignature) : Field write access, i.e. set(private String edu.mat.hello.MessageCommunicator.name) which means capture all join points on setter method of private variable name in class MessageCommunicator.

6. handler(TypeSignature) : Exception handler execution.

7. initialization(ConstructorSignature) : Object initialization, i.e. initialization(public edu.mat.hello.MessageCommunicator.new()) which means capture all join points on object MessageCommunicator creation.

8. within(TypePattern) : Capture join points in a scope, i.e. !within(AccountAspect) && !within(edu.mat.hello.MessageCommunicator) && !within(MessageCommunicatorAspect) which means capture all join points outside AccountAspect aspect and MessageCommunicator class and also outside MessageCommunicatorAspect aspect.

A pointcut could have arguments as shown in the pointcut syntax above. We can capture the values of the arguments using args. For example: private pointcut sayMyName(String person) : call(* edu.mat.hello.MessageCommunicator.sayMyName(String, String)) && args(person, String); which means capture all pointcuts in sayMyName method of class MessageCommunicator and grab first argument (named person) as shown in args(person, String).

We can also capture the caller of being executed join point using target. For example we have the following pointcut private pointcut setNameField() : set(private String edu.mat.hello.MessageCommunicator.name); and private pointcut targetObject(edu.mat.hello.MessageCommunicator object) : target(object) && setNameField();.

In the first pointcut we want to capture all join points on setter method of name variable on class MessageCommunicator. In the second pointcut, we want to capture all join points on previous pointcut (when name variable is set) and grab the MessageCommunicator object which calls that setter method, that is the target.

Database Index, a little action leads to better performance

When you run a query and it happens to run very slow against a certain table, you start thinking that your fellow who created the query must have created a buggy query. Later, when you scan your database tables, you then find that the table has no index at all. Take a deep breath and start creating indexes on columns which are accessed a lot in queries, for example, primary keys, foreign keys, and columns that are used often in the where and order clauses. After that, don't forget to say sorry for blaming your fellow and start complaining your DBA :D.

Monday, July 11, 2011

Entity Object Locking

Object locking is required to avoid concurrency problem in an application. Generally speaking, there are two types of object locking: Pessimistic Locking and Optimistic Locking.

Pessimistic locking is a locking strategy where we prevent users from doing certain things. Here is an example of pessimistic locking:

User A performs update action on an entity object, then user A gets write lock on the being updated entity object. At almost concurrent time, user B performs update action on the same entity object, then user B's action is rejected since the entity object's write lock is being hold by user A.

JPA doesn't support this strategy because it has many disadvantages. It can make the application slower because certain action have to wait for entity object's lock to be released.

Optimistic locking is a locking strategy where we will use object comparison to decide whether a certain transaction will be committed or rolled back. Here is an example of optimistic locking:

When a user performs update action on an entity object, he/she will retrieve a copy of that entity object. Changes are made to the copy object, not the original. When the user is about to save it to database, application checks whether data have been updated since the user retrieved it. If no update has been made, the user gets entity object's write lock, then the data is committed. Otherwise, it is rejected.

JPA support this strategy. It is implemented by adding a column to the table for the entity to save a version number. Every time the row is updated, the version number is incremented. It is by comparing that version number the update action is committed or rejected.

Monday, July 4, 2011

Oracle Toplink + PostgreSQL = nightmare

Banyak masalah yang muncul ketika memakai Oracle Toplink sebagai persistence provider dan PostgreSQL sebagai databasenya, antara lain:
1. Tidak mau menjalankan sequence. Solusi:

package edu.mat.client;

import oracle.toplink.essentials.platform.database.PostgreSQLPlatform;
import oracle.toplink.essentials.queryframework.ValueReadQuery;
import oracle.toplink.essentials.sessions.DatabaseSession;

public class PostgreSQLPlatformSupportingSequences extends PostgreSQLPlatform {

/**
*
*/
private static final long serialVersionUID = -2637524409846222203L;

public boolean shouldNativeSequenceAcquireValueAfterInsert() {
return false;
}

public void platformSpecificSequencingInitialization(DatabaseSession session) {
}

public ValueReadQuery buildSelectQueryForNativeSequence(String seqName,
Integer size) {
ValueReadQuery selectQuery = new ValueReadQuery();
selectQuery.setSQLString("select nextval(\'" + seqName + "\')");
return selectQuery;
}

}

Terus tambahkan di persistence.xml <property name="toplink.target-database" value="edu.mat.client.PostgreSQLPlatformSupportingSequences"/>

2. Muncul error Problem with sequence setup increment does not match its pre-allocation size. Solusi: Ubah current-value di sequence menjadi 100, dan increment-value menjadi genap semisal dua.

3. Data byte dengan annotation @Lob seperti

@Column(name = "PICTURE", table = "USER_PICTURES")
@Lob
@Basic(fetch = FetchType.LAZY)
public final byte[] getPicture() {
return picture;
}

harus didefinisikan dengan tipe oid di PostgreSQL

Thursday, May 19, 2011

JAXP & JAXB

JAXP = Java API for XML Processing (SAX, DOM, StaX)

JAXP is for processing XML data using applications written in Java. JAXP leverages the parser standards Simple API for XML Parsing (SAX) and Document Object Model (DOM) so that you can choose to parse your data as a stream of events or to build an object representation of it. JAXP also implements the Streaming API for XML (StAX) standard.

SAX is a standard interface for event-based XML parsing. It reports parsing events (such as the start and end of elements) directly to the application through callbacks, the application implements handlers to deal with the different events. It supports read-only access, that is, SAX is designed only for reading XML documents. Of course, we could write a new document out as a result of event, but we cannot change the document being processed.

SAX is fast and efficient, but its event model makes it most useful for such state-independent filtering. For example, a SAX parser calls one method in your application when an element tag is encountered and calls a different method when text is found. If the processing you are doing is state-independent (meaning that it does not depend on the elements that have come before), then SAX works fine.

On the other hand, for state-dependent processing, where the program needs to do one thing with the data under element A but something different with the data under element B, then a pull parser such as the Streaming API for XML (StAX) would be a better choice.

StAX provides a streaming, event-driven, pull-parsing API for reading and writing XML documents. StAX offers a simpler programming model than SAX and more efficient memory management than DOM.

Pull Parsing versus Push Parsing

Streaming pull parsing refers to a programming model in which a client application calls methods on an XML parsing library when it needs to interact with an XML infoset—that is, the client only gets (pulls) XML data when it explicitly asks for it.

Streaming push parsing refers to a programming model in which an XML parser sends (pushes) XML data to the client as the parser encounters elements in an XML infoset—that is, the parser sends the data whether or not the client is ready to use it at that time.

Pull parsers and the SAX API both act like a serial I/O stream. You see the data as it streams in, but you cannot go back to an earlier position or leap ahead to a different position. In general, such parsers work well when you simply want to read data and have the application act on it.
But when you need to modify an XML structure - especially when you need to modify it interactively - an in-memory structure makes more sense. DOM is one such model.

Generally speaking, there are two programming models for working with XML infosets: streaming and the document object model (DOM).

The DOM model involves creating in-memory objects representing an entire document tree and the complete infoset state for an XML document. Once in memory, DOM trees can be navigated freely and parsed arbitrarily, and as such provide maximum flexibility for developers. However, the cost of this flexibility is a potentially large memory footprint and significant processor requirements, because the entire representation of the document must be held in memory as objects for the duration of the document processing. This may not be an issue when working with small documents, but memory and processor requirements can escalate quickly with document size.

Streaming refers to a programming model in which XML infosets are transmitted and parsed serially at application runtime, often in real time, and often from dynamic sources whose contents are not precisely known beforehand. Moreover, stream-based parsers can start generating output immediately, and infoset elements can be discarded and garbage collected immediately after they are used. While providing a smaller memory footprint, reduced processor requirements, and higher performance in certain situations, the primary trade-off with stream processing is that you can only see the infoset state at one location at a time in the document.

Streaming models for XML processing are particularly useful when your application has strict memory limitations, as with a cellphone running the Java Platform, Micro Edition (Java ME platform), or when your application needs to process several requests simultaneously, as with an application server.

JAXB = Java API for XML Binding

JAXB provides a fast and convenient way to create a two-way mapping between XML documents and Java objects. What XML data-binding does is to create Java classes from schema definition. That is, the XML schema can be compiled to generate corresponding Java classes.And once the class is generated for the XML schema, a XML document which follows the syntax of the schema can be represented as an instance of the generated class. The process of converting XML document to a corresponding high-level Java object is called "un-marshalling" while the reverse is called "marshalling".

Here is some example I provide:

Wednesday, April 6, 2011

Encode URL and Decode Google Translate's Response in Objective C

I've been working on a project that needs to get a translation from google translate web service. There are some codes in google code that can help you doing this. However, I found some problems regarding string encoding.

I used to encode the string with NSUTF8StringEncoding, but it doesn't encode character & into %26 or + into %2B so I had to encode it manually.

NSString* urlEncodedText = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlEncodedText = [CommonUtil encodeCharacters:urlEncodedText];

+ (NSString*) encodeCharacters:(NSString*) string {
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"%26" forKey:@"&"];
[dict setObject:@"%2B" forKey:@"+"];

NSArray* keys = [dict allKeys];
for (int i = 0; i < [keys count]; i++) {
NSString* key = [keys objectAtIndex:i];
string = [string stringByReplacingOccurrencesOfString:key withString:[dict objectForKey:key]];
}

return string;
}

The same thing happens when I get the translation. I get &amp; instead of &, &quot; instead of " (double quote), etc so I had to manually decode it.

+ (NSString *) decodeCharacters:(NSString *)string {
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"&" forKey:@"&amp;"];
[dict setObject:@"\"" forKey:@"
&quot;"];
[dict setObject:@"'" forKey:@"
&#39;"];
[dict setObject:@"<" forKey:@"
&lt;"];
[dict setObject:@">" forKey:@"
&gt;"];

NSArray* keys = [dict allKeys];
for (int i = 0; i < [keys count]; i++) {
NSString* key = [keys objectAtIndex:i];
string = [string stringByReplacingOccurrencesOfString:key withString:[dict objectForKey:key]];
}

return string;
}

Wednesday, March 23, 2011

TortoiseSVN Error

I got the following notification when trying to commit my code:

Error: Commit failed (details follow):
Error: Unable to open an ra_local session to URL
Error: Unable to open repository 'file:///D:/SVN/LinkLearning/trunk'
Error: Berkeley DB error for filesystem 'D:/SVN/LinkLearning/db' while opening environment:
Error: Not enough space
Error: bdb: unable to allocate memory for mutex; resize mutex region

I googled without luck. Then I opened DB_CONFIG file located in D:/SVN/LinkLearning/db. There, I found a statement like "You must run 'svnadmin recover' whenever you modify this file, for your changes to take effect." So I frustratingly run that command as in: D:\SVN\LinkLearning>svnadmin recover d:\SVN\LinkLearning. Then I tried to commit my code again. Wolah... magically everything is OK :D.

Thursday, October 28, 2010

Insertion sort

Akhirnya sempat juga ngeblok di sela-sela ngoding iPhone ;)). Tak terasa sudah lama meninggalkan pulau Java. Sekarang ini sedang demam mempelajari kembali algoritma-algoritma yang sudah bertahun-tahun ditinggalkan. Sebagai permulaan sebaiknya mulai dari Insertion Sort. Berikut adalah implementasinya di Java:

public class Algoritma {

public static void main(String[] args) {
int[] input = new int[] {5, 2, 4, 6, 1, 3};
insertionSortIncrease(input);
System.out.println("\n");
insertionSortDecrease(input);
}

private static void insertionSortIncrease(int[] input) {
for (int j = 1; j < input.length; j++) {
int key = input[j];
int i = j - 1;
while (i >= 0 && input[i] > key) {
input[i + 1] = input[i];
i--;
}
input[i + 1] = key;
}
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + " ");
}
}

private static void insertionSortDecrease(int[] input) {
for (int j = 1; j < input.length; j++) {
int key = input[j];
int i = j - 1;
while (i >= 0 && input[i] < key) {
input[i + 1] = input[i];
i--;
}
input[i + 1] = key;
}
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + " ");
}
}

}

Monday, October 4, 2010

Pattern Builder and Factory

Builder and Factory are two different pattern, obviously. But sometimes I get confused because of their name. Both patterns act as object manager, they create object and hide the creation from user.

Factory is used to create object in an object family. Usually I pass a static number and the factory will go through if-else condition to decide what object to create.

Builder on the other hand, create an object based on some object characteristics. For example we have an xml file that holds object's state, and we want to create an object based on the file. We then pass the xml, then the Builder will create the object for us.

Sunday, October 3, 2010

Thread: synch, lock, wait, notify, join

Synchronization

Synchronization in java works with object lock. Every object in java has a built-in lock that only comes into play when the object has synchronized method code. Since there is only one lock per object, if one thread has picked up the lock, no other thread can enter the synchronized code (which means any synchronized method of that object) until the lock has been released. Typically, releasing a lock means the thread holding the lock (in other word, the thread currently in the synchronized method) exits the synchronized method. At that point, the lock is free until some other thread enters a synchronized method on that object.

An example of synchronization is on account withdrawal. Usually, before making withdrawal, we check the account balance. We must guarantee that those two actions are never split apart. We need them to always be performed as one operation.

private synchronized void makeWithdrawal(int amt) {
if (acct.getBalance() >= amt) {
System.out.println(Thread.currentThread().getName() + " is going to withdraw");
try {
Thread.sleep(500);
} catch(InterruptedException ex) { }
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName() + " completes the withdrawal");
} else {
System.out.println("Not enough in account for " + Thread.currentThread().getName() + " to withdraw " + acct.getBalance());
}
}


In previous code we simulate account checking and withdrawal as two action by making the thread to sleep. By putting those two actions in a single synchronized method, we make them as one operation.

Because each object has a built-in lock, we can synchronize a block of code instead of a method as in synchronized(obj). That means, the currently running thread is acquiring obj's lock so that no other thread can execute any synchronized method and block of code in object obj.

Thread Interaction

Consider the following scenario for thread interaction.

class Reader extends Thread {
Calculator c;

public Reader(Calculator calc) {
c = calc;
}

public void run() {
synchronized(c) {
try {
System.out.println("Waiting for calculation...");
c.wait();
} catch (InterruptedException e) {}
}
System.out.println("Total is: " + c.total);
}

public static void main(String [] args) {
Calculator calculator = new Calculator();
calculator.start();
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();
}
}

class Calculator extends Thread {
int total;

public void run() {
synchronized(this) {
for(int i=0;i<100;i++) {
total += i;
}
notifyAll();
}
}
}

The Calculator object is responsible for calculating the total value. It extends Thread, and the calculating process is wrapped inside run method. Another class is the Reader class. This class responsibility is to display the total value, calculated by Calculator before, to console. Because both classes extend Thread, they will be run on their own thread. We need some way to let Calculator finish calculating first and then display the result to console.

Java provides methods to deal with that condition. Those methods are wait(), notify(), and notifyAll(). In order to use those methods, we must have the lock on the target object, in this case is Calculator (that's why we synchronized both run method). In the code above, we have three Reader referencing to one shared Calculator. When any of the Reader object runs, it will hold the Calculator lock and make the other Reader blocked. It will then wait for the Calculator by releasing the lock (when a thread calls wait() in an object, it will release the object's lock). Once the lock is released, other Reader object go to their own run method and they all will be blocked when calling c.wait, just like the first Reader. Now calculator has it's turn to execute it's synchronized run method and notify all waiting thread.

Java specs says that there is no guarantee on thread execution order. It means that the notify call (on Calculator thread) can take place first before Reader thread calls wait method. If this happens, the thread will never wake up. To prevent this, we can use wait method that accepts a number of milisecond as max time to wait.


Another approach is to check whether the total has been calculated or not, for example:


try {

if (!c.isFinished()) { // means the calculation is not finished yet
 System.out.println("Waiting for calculation...");
 c.wait();

}
} catch (InterruptedException e) {}

Using previous approach makes the thread waiting for the notification only when the calculation is not finished, not blindly waiting the notification.

 

Join

First time I learnt about join and wait/notify, it was pretty the same. After awhile, I can see the difference on the purpose / scenario. The above calculator example is about thread communication, two or more threads are talking to each other. An example of join is if we want to have a calculator for a reader. In that situation we can join the reader to calculator to make the reader waiting the calculator to finish and dead.
 

©2009 Stay the Same | by TNB