Wednesday, August 24, 2011

Java Access Modifier

While waiting for the lunch time lets do something very basic but quiet interesting; Java access modifier.

There are four access modifiers in Java: public, protected, private, and package access. Suppose we have a project with package structure as below:



There are four classes:
1. A superclass for other classes named SuperClass
2. A subclass of class SuperClass named SubClassA which resides at the same package as its superclass.
3. A subclass of class SuperClass named SubClassB which resides at different package as its superclass.
4. Another class at different package named Main.



The SuperClass has all four different level access method. We will see which methods are visible at any of the other three classes.



We can see that the public, protected, and package access level methods are visible in class SubClassA through both inheritance and reference.



Now we can see that there are only public and protected methods visible to class SubClassB through inheritance and only public method visible through reference. This happens because package level access, as its name suggest, only applies for classes reside at same package. Whereas protected applies for all of its subclasses.

There is a note here regarding overriding protected method. As we can see in class SubClassB, we override method protectedMethod from its superclass. Therefore, all classes at the same package with class SubClassB can access SubClassB's protectedMethod through reference. However, if we didn't override the protectedMethod, all other classes at the same package wouldn't be able to access it at all because protectedMethod would become private in SubClassB.



For a class at another package, as we can see in class Main, can only access public methods.

The access levels are simple and clear, aren't they? All method modifiers also apply to instance variables as well. OK, now it's time to go out for lunch.

Monday, August 22, 2011

Cassandra Architecture

Apache Cassandra is not another relational database in market. Instead of using relational model, it uses key-value map to store its data. The structure is more or less can be explain as in the following picture:



Cluster: Cassandra is designed to be distributed over several nodes/machines. A cluster consists of several nodes. I've only ever used Cassandra in a single node which is my computer.

Keyspace: A cluster consists of several keyspaces. Keyspace is the place where our data reside. A keyspace could have several Column Family or Super Column Family.

Column Family and Super Column Family: Both Column Family and Super Column Family is a collection of rows, just like a table is a collection of rows in relational database.

Row: A row consists of columns; key-value columns for a row in Column Family, or Super Columns for a row in Super Column Family.

Super Column: It is sort of container of sub-columns (which are of type Key-value Column).

Key-value Column: The most basic data structure in Cassandra where the actual data is saved as byte. The behavior is a lot like Java Hash data type.

Here are examples of Cassandra data retention and retrieval:

COLUMN_FAMILY_NAME[ROW_KEY_NAME][COLUMN]

User['user1']['name'] = 'Rochmat Santoso';
User['user1']['address'] = 'Surabaya';
User['user2']['name'] = 'Barbie';
User['user2']['address'] = 'Malibu';

SUPER_COLUMN_FAMILY_NAME[ROW_KEY_NAME][SUPER_COLUMN_NAME][COLUMN]

Province['province1']['info']['name'] = 'East Java';
Province['province1']['info']['capital'] = 'Surabaya';
Province['province1']['city']['sby'] = 'Surabaya';
Province['province1']['city']['mlg'] = 'Malang';
Province['province1']['city']['sda'] = 'Sidoarjo';

Province['province2']['info']['name'] = 'West Java';
Province['province2']['info']['capital'] = 'Bandung';
Province['province2']['city']['bdg'] = 'Bandung';
Province['province2']['city']['tgr'] = 'Tangerang';

Wednesday, August 10, 2011

Annotation

Setelah sekian lama akhirnya punya waktu juga untuk mencoba annotation. Beberapa catatan untuk annotation ini adalah:
- Tambahkan @Documented agar annotation ini bisa di-generate saat membuat javadoc karena defaultnya sebuah annotation tidak di-generate oleh javadoc tool.
- Tambahkan @Retention(RetentionPolicy.RUNTIME) untuk menyimpan data-data annotation pada saat kompilasi sehingga bisa dibaca saat runtime. Jika tidak disimpan maka kita tidak bisa membacanya.
- Ada beberapa macam tipe annotation tergantung tempat di mana annotation itu akan ditempatkan misalnya di class, method, field, parameter, konstruktor, dll. Gunakan @Target(value = ElementType.TYPE) untuk annotation yang diletakkan di Class atau interface. Beberapa tipe yang lain adalah @Target(value = ElementType.METHOD) untuk annotation pada method, @Target(value = ElementType.FIELD) untuk annotation pada field, @Target(value = ElementType.PARAMETER) untuk annotation pada method parameter, dll.

Berikut ini adalah contoh annotation dan cara mengaksesnya

Friday, August 5, 2011

Lucene Analyzer

There are several analyzer available in Lucene:

WhitespaceAnalyzer: It splits text into tokens on whitespace characters. It doesn't normalize the tokens and doesn't lowercase each token.

SimpleAnalyzer: It splits tokens at non letter characters and lowercases each token. It discards numeric characters but keeps all other characters.

StopAnalyzer: It acts almost same as SimpleAnalyzer except it removes common words. By default, it removes common words specific to English (the, a, etc).

StandardAnalyzer: It is the most sophisticated core analyzer. It has quite a bit of logic to identify certain kinds of tokens such as company names, email addresses, and hostnames. It lowercases each token and removes stop words and punctuation.

KeywordAnalyzer: It treats entire text as a single token.

Monday, August 1, 2011

Lucene Field Options

Field Indexing Option

Field.Index.ANALYZED : Use analyzer to break the field's value into separate tokens and make each token searchable. This option is useful for body, title, abstract text.

Field.Index.NOT_ANALYZED : Index the field but don't analyze the string value. Instead, treat the field's value as a single token and make the token searchable. This option is useful for URL, file system path, dates, personal names, card number, phone number. This option is useful for enabling "exact match" searching.

Field.Index.NO : Don't make the field's value available for searching

Field Storing Option

Field.Store.YES : Store field's value in the index. This option is useful for fields that we want to display along with the search result such as URL, title, database primary key. Without storing the field's value, we won't be able to retrieve it using document.get("fieldname") on searching.

Field.Store.NO : Don't store the field's value in the index. This option is often used along with Field.Index.ANALYZED to index large text field such as text body.

Here are some example of field indexing and field storing option:

Analyzed & Stored : title, abstract text
Analyzed & Not Stored : body
Not Analyzed & Stored : URL, file system path, dates, personal names, card number, phone number
No Index & Stored : database primary key
Not Analyzed & Not Stored : hidden keywords

Code Example:

Document document = new Document();
document.add(new Field("filename", file.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
indexWriter.addDocument(document );

Tuesday, July 19, 2011

AI and Thread Pool Code Example

Finally uploaded some examples of Breadth-first search, Depth-first search, Best-first search, Genetic Algorithm, Binary search tree, Backward and forward chaining code. Also, I tried to create simple thread pool because I found this pooling idea is very interesting and widely used.

Monday, July 18, 2011

Is it crossroad?

Recently, I have been watching Al Pacino's speech when he won the Academy Award in 1992. He said "I've been very lucky I've found desire for what I do early in my life and have people who encourage that desire."

I also kept Johnny Carson's farewell statement on final Tonight Show. He said "I am one of the lucky people in the world, I found something I always wanted to do, and I have enjoyed every single minute of it."

Steve Jobs also said the same thing. He gave a speech at Stanford Commencement, he said "I was lucky I found what I loved to do early in life... Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don't settle."

They got me thinking about my life too, about what my desire is. I have to admit that being a software engineer was not my desire (there was no kid back in 1990s in my school who wanted to be a software engineer I suppose, we usually want to be doctor, pilot, president, etc :p). Software engineering was popular when I was at high school, computers and cellphones were becoming trend back in old days (I'm feeling so old when writing this hahaha...). I then chose to enter Informatics because I want to learn more about computer science. I knew I love math and science, and because I knew that the basic of computer is math logical expression, I thought it shouldn't be a big deal. But I realize it is not my desire to be a software engineer.

I know that great people are them who always follow their hearth and do what they love because you have to love what you do to be great. I wonder if Al Pacino, Steve Jobs, or Johnny Carson ever came to this point of life, at the searching point of their desire. Anyway, what ever it is I am now, all I know is that I always have passion in learning anything new. I always do the best for my job. I learn many new Java frameworks. I love writing and sharing thought and knowledge with others, and I still hope someday I will find what my desire is, either it is in IT field or something else.

Thursday, July 14, 2011

AOP - Notes on Advice

An advice has the following syntax:
advice_type([arg]) : pointcut_name { advice_body }

There are three types of Advice
1. Before, the advice is executed right before the join point code is executed.

Example of a before advice:

/** pointcut */
private pointcut getNameField() : get(private String edu.mat.hello.MessageCommunicator.name);

/** advice */
before() : getNameField() {
System.out.println("Getter method is about to call.");
}

2. After, the advice is executed right after the join point code is executed.

/** pointcut */
private pointcut setNameField() : set(private String edu.mat.hello.MessageCommunicator.name);

/** advice: this advise is executed whether setNameField() returns normally or throwing exception */
after() : setNameField() {
System.out.println("Name has been set.");
}

/** advice: this advise is executed only when setNameField() returns successfully */
after() returning : setNameField() {
System.out.println("Name has been set.");
}

To get the returned object, we can use after() returning(Integer count) : calculateRevenue() {...}

/** advice: this advise is executed only when setNameField() throws exception */
after() throwing : setNameField() {
System.out.println("Name has not been set.");
}

To get the thrown exception, we can use after() throwing (Exception e) : calculateRevenue() {...}

3. Around, this advice is useful to intercept an execution of a join point.

Suppose we have the following pointcut:

private pointcut sayHello(edu.mat.hello.MessageCommunicator caller, String person) : call(* edu.mat.hello.MessageCommunicator.sayHello(String, String)) && args(person, String) && target(caller);

The above pointcut says that we will capture all join points in sayHello(String, String) method of class MessageCommunicator, capture the method caller (target object as shown in target(caller)) and first parameter of the method (as shown in args(person, String)) as stated in pointcut's arguments.

Then we have an advice as in:

void around(edu.mat.hello.MessageCommunicator caller, String person) : sayHello(caller, person) {
try {
proceed(caller, "Pak " + person);
} catch (Exception e) {

} finally {
System.out.println("Say hello finally finished.");
}
}

there, we execute the real join point code in proceed(caller, "Pak " + person); and surround it with try-catch block. The arguments in proceed must match arguments in around().

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.
 

©2009 Stay the Same | by TNB