Only my share

Java , Groovy and others

Our big Project

leave a comment »

Currently I’m working @Bakrie Telecom–a CDMA fixed wireless operator in Indonesia. My position is as an Engineer in IT Prepaid Development Department. Currently we’re running with Service Oriented Architecture Project which utilize Oracle SOA Suite as an implementation.

Seriously, it is a big project. We have to integrate all variety of systems including Telecommunication Network Element systems and then encapsulate those systems to Web Services using Service Oriented Architecture as the methodology.

I hope in this forum someone want to share his or her experiences when faced with the same kind of project.

What a big project

What a big project

The ultimate goal

The ultimate goal

Written by adpjhype

August 18, 2009 at 8:27 am

Posted in SOA

The beauty of Meta Object Programming in Groovy

with 2 comments

Hello there, see you again. In this article I will show you how MOP programming will be easy when you implement it in Groovy. This simple way is achieved by strong expressiveness of Groovy language. 

As you know, MOP or Meta Object Programming is one of good programming techniques that can change the behavior  of one object at runtime. It is very different if you are as a Java Programmer where all of object is created by static type class and the behavior of the object of this class cannot be changed at run time.

In the following code I’ll show you how MOP enable us to change the behavior (add more method) to the Class / Object at runtime.

String.metaClass.hitungPanjang = {
         ->
              delegate.size()
}

String test = “Aldry Deka Pratama”
println “The number of character in string : ” + test.hitungPanjang()

In this code I define a new method called “hitungPanjang” that will count the size of the String. This method will be attached to existing String class. After you attached the method and make a new instance of this class, then you can call the method you already defined to the class  through its object

Written by adpjhype

March 2, 2009 at 12:38 pm

What the Heck Is a File Hole?

leave a comment »

 

A file hole occurs when the space on disk allocated for a file is less than the file size. Most modern filesystems provide for sparsely populated files, allocating space on disk only for the data actually written (more properly, allocating only those filesystem pages to which data was written). If data is written to the file in noncontiguous locations, this can result in areas of the file that logically contain no data (holes). For example, the following code might produce such kind of file:

 

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.io.File;
import java.io.RandomAccessFile;
import java.io.IOException;

 

public class FileHole{
     public static void main (String [] argv) throws IOException {
             // Create a temp file, open for writing, and get      
          // a FileChannel         
         File temp = File.createTempFile(“holy”,null);
        RandomAccessFile file = new RandomAccessFile (temp, “rw”);
        FileChannel channel = file.getChannel( );
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect (100);
        putData (0, byteBuffer, channel);             
        putData (5000000, byteBuffer, channel);
        putData (50000, byteBuffer, channel); 

          // Size will report the largest position written, but

         // there are two holes in this file. This file will

         // not consume 5 MB on disk (unless the filesystem is

         // extremely brain-damaged)

         System.out.println (“Wrote temp file ‘” + temp.getPath( )
                    + “‘, size=” + channel.size( ));

         channel.close( );

        file.close( );

     }

private static void putData (int position, ByteBuffer buffer,
     FileChannel channel) throws IOException {
        
          String string = “*<– location ” + position;
          buffer.clear( );
          buffer.put (string.getBytes (“US-ASCII”));
          buffer.flip( );
          channel.position (position);
          channel.write (buffer);

      }
}

Written by adpjhype

January 27, 2009 at 5:52 am

Posted in Java

Tagged with , ,

The beauty of SwingBuilder

leave a comment »

When I was in the University (STT TELKOM / IT TELKOM), I had a favorite text book as my Java reference. The book title is Core JAVA-Volume 1 and 2 written by Cay S Horstmann and Gary Cornell. In chapter 8 about Event Handling, the authors explained to the reader about basic event handling with one code example. The example will generate a Frame that consists of three buttons with the label “Yellow”, “Blue”, and “Red”. If one of its button is pressed the event will be triggered by each button to change the background color of the Frame. The following code is taken from their book:

1. import java.awt.*;
2. import java.awt.event.*;
3. import javax.swing.*;
4.
5. public class ButtonTest
6. {
7.  public static void main(String[] args)
8. {
9. ButtonFrame frame = new ButtonFrame();
10. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
11. frame.show();
12. }
13. }
14.
15. /**
16. A frame with a button panel
17. */
18. class ButtonFrame extends JFrame
19. {
20. public ButtonFrame()
21. {
22. setTitle(“ButtonTest”);
23. setSize(WIDTH, HEIGHT);
24.
25. // add panel to frame
26.
27. ButtonPanel panel = new ButtonPanel();
28. Container contentPane = getContentPane();
29. contentPane.add(panel);
30. }
31.
32. public static final int WIDTH = 300;
33. public static final int HEIGHT = 200;
34. }
35.
36. /**
37. A panel with three buttons.
38. */
39. class ButtonPanel extends JPanel
40. {
41. public ButtonPanel()
42. {
43. // create buttons
44.
45. JButton yellowButton = new JButton(“Yellow”);
46. JButton blueButton = new JButton(“Blue”);
47. JButton redButton = new JButton(“Red”);
48.
49. // add buttons to panel
50.
51. add(yellowButton);
52. add(blueButton);
53. add(redButton);
54.
55. // create button actions
56.
57. ColorAction yellowAction = new ColorAction(Color.yellow);
58. ColorAction blueAction = new ColorAction(Color.blue);
59. ColorAction redAction = new ColorAction(Color.red);
60.
61. // associate actions with buttons
62.
63. yellowButton.addActionListener(yellowAction);
64. blueButton.addActionListener(blueAction);
65. redButton.addActionListener(redAction);
66. }
67.
68. /**
69. An action listener that sets the panel’s background color.
70. */
71. private class ColorAction implements ActionListener
72. {
73. public ColorAction(Color c)
74. {
75. backgroundColor = c;
76. }
77.
78. public void actionPerformed(ActionEvent event)
79. {
80. setBackground(backgroundColor);
81. repaint();
82. }
83.
84. private Color backgroundColor;
85. }
86. }

Now, I want to show you how Groovy will accomplish the same program with its SwingBuilder Power:

import groovy.swing.SwingBuilder;

swing = new SwingBuilder()
frame = swing.frame(size:[400,500], title:’Swing Demo’, defaultCloseOperation:javax.swing.JFrame.EXIT_ON_CLOSE){
panel(id:’mainPanel’){
button(‘Red’, actionPerformed : {
mainPanel.background = java.awt.Color.RED
mainPanel.repaint()
})
button(‘Yellow’,actionPerformed : {
mainPanel.background = java.awt.Color.YELLOW
mainPanel.repaint()
})
button(‘Blue’, actionPerformed : {
mainPanel.background = java.awt.Color.BLUE
mainPanel.repaint()
})
}
}
frame.show()

From this two code, we can make a conclution that groovy code especially in its Swing Framework support is more flexible and more intuitive for us to figure out the containtment structure of its GUI components. In Java languange Swing Framework code programming is very hard to be read and not easly show us the containtment structure of its GUI components.

Written by adpjhype

January 7, 2009 at 3:47 pm

Posted in Groovy

Tagged with

Closure make File Access so Easy in Groovy

with one comment

As we know in Groovy, Closure is a class that only contain a pieces of code. If you came from C/C++ Closure will be identical to function pointer, but Closure has more capability and better safety mechanism. In this article, I will show you how Closure support in groovy can make file access whether it is read or write operation so easy.

If you are a Java programmer, you will agree that this is very complex to do read or write to a File. There has to be a try-catch mechanism to catch all possible IO Exception that possibly occur in the code. In groovy, You can forget all of kind of messy mechanisms and you can only concentrate to what will you do with the file.

/*
* File Demo
*/
// writing some text to c:/mylovepoet.txt
file = new File(‘c:/mylovepoet.txt’)
file.write(“oh my darling”)

// append some text to the same file
file.append(‘oh my darling oh my darling\n’)
file.append(‘please. stay away\n’)

//Create new file and write to it using withWriter method and with closure argument
file2 = new File(‘c:/mylovepoet2.txt’)
file2.withWriter{
writer ->
writer << ‘oh my sweety\n’
writer <<  ‘please come to me’
}

// append some more text to the file using withWriter
file2.withWriterAppend{
writer ->
writer << ‘oh oh.. don\’t go’
}

// now we can read the content of the first file
file.eachLine {
line ->
println line

}

// now we will display all line started with ‘please’

print “\nLIne started with ‘please’:\n”
file.eachLine {
line ->
if(line =~ /^please/){
println line
}
}

We can make some raw conclution about File Access in groovy. It is more convenient and faster to create a code that access a file without any annoying error-handling mechanisms. All of error handling automatically handled by Groovy.

Written by adpjhype

January 5, 2009 at 4:41 pm

Posted in Groovy

Tagged with

Running Groovy script from crontab in Linux

with 2 comments

I got a task to gather some log files into one single log file. What I was thinking about when I tried to implement this task using Groovy is my previous failure experiences to run it from crontab service in Linux.

But now, I have a good steps to solve this problem.

1. Assume that our Groovy script located at : /opt/btel/script/aldry/fnflog/fnfLogForDW.groovy
2. create a bash script to be run withing crontab service:

JAVA_HOME=your-java-home-directory
GROOVY_HOME=your-groovy-home-directory
export JAVA_HOME
export GROOVY_HOME

PATH=$JAVA_HOME/bin:$GROOVY_HOME/bin:$PATH:.
export PATH

cd /opt/btel/script/aldry/fnflog
groovy -classpath /opt/btel/script/aldry/fnflog //opt/btel/script/aldry/fnflog/fnfLogForDW.groovy

 3. Assume that we saved that bash script to the file : /opt/btel/script/aldry/fnflog/fnfLogForDW
4. type the following command from the console to install your script in the crontab service
                  shell> crontab -e
5.Put the following line, assume that this script will be run every 1:00 AM :
                   0 1 * * * /opt/btel/script/aldry/fnflog/fnfLogForDW
6. Restart crond service with the following command:
                   service crond restart
7. Enjoy :)

Written by adpjhype

January 2, 2009 at 9:15 am

Posted in Groovy

Tagged with

My Groovy Vs Perl

with 5 comments

Currently I’m working at the Telecommunication Company (Bakrie Telecom). I’m a staff of IT Billing Prepaid Development Department. The main function of this department is to build a variety of interfaces between IT Application whether it is build by other IT teams or by the third party vendors, to Bakrie Telecom ‘s Network Element such as SMSC (Short Message Service Center), IN (Intelligent Network), HLR (Home Locator Register) and any others standard TELCO Network Element.

My Manager is a PERL Hacker. He can do his magic with just a few of key stroke to accomplish variety of job or script, for example to parse the large CDR files, make a network connection to the Network Elements (for provisioning process) or connect to the Database. So in my first career in this company, I have to read preexisting of codes and I’m sure I got a lot of thing from it. But I don’t know why something missing in my mine. PERL is not really comfortable to program with (for me). Maybe, this is because my strong background as a Java programmer. So after about six months working for this company, I decided to write some of my new development jobs using Java Technology.

But after some development job has been done using my favorite Java Technology, I became to realize that there are some difficulties when I had a kind of development jobs that has a lot of parsing tasks. As we know, it’s very hard or maybe complex to accomplish such a job in Java programming language because of the lack of expressiveness of this language.

But now, the situations are totally different, I got a Groovy Programming language as second standard programming language in Java platform. So with this language I can accomplish a lot of job that is hard to do with Java Programming language with more enjoyment and fun.

In this article I want to show some examples of how Groovy programming Language can be more expressive than PERL.

1. Read a text file

In this section assumed that we’re going to dump a text file located at local directory c:/mylovepoet.txt

This is my code in groovy:

/**
Reading a text file located at c:/mylovepoet.txt using Groovy
*/
new File(“c:/mylovepoet.txt”).eachLine{ line ->
println line
}

This is my code in PERL

/**

Reading a text file located at c:/mylovepoet.txt using PERL

*/
open(INPUT, “c:/mylovepoet.txt”);

while(<INPUT>) {
$line = $_;
$line =~ s/\r|\n//gi;
print “$line\n”;
}

close(INPUT);

2. List Manipulation

In this example we have the list of programming language names, from this list we want to extract the programming language name that contains special characters such as ‘+’ or ‘#’. We can accomplish this job by the following Groovy and PERL script:

/**
List usage in Groovy
*/

pl_list = [‘B’, ‘C’, ‘C++’, ‘JAVA’, ‘C#’]
pl_with_special_char_list = pl_list.grep(/^\w(\+|#)+\w*$/)

and this is my script in PERL

/**
List usage in PERL
*/

@pl_list = (‘B’, ‘C’, ‘C++’, ‘JAVA’, ‘C#’);
@pl_with_special_char_list = ();
$i = 0;

for($pl (@pl_list)) {
if($pl =~ /^\w(\+|#)+\w*$/) {

$pl_with_special_char_list[$i] = $
$i++;
}

}

This article have no intention to prove that Groovy is better than PERL, but this article just want to show us that Groovy can be more expressive than PERL.

Written by adpjhype

December 21, 2008 at 4:01 pm

Posted in Groovy

The easiest way to install JDK in Linux

with 3 comments

I have read lots of user posting at various pages and none of them would work.
Finally, I found a way to do this correctly and hope this will help to some of you.

Follow the simple steps:

1. To set the environment variables :

echo ‘export JAVA_HOME=/opt/btel/java/jdk1.5.0_16′ > /etc/profile.d/jdk.sh

echo ‘export PATH=$JAVA_HOME/bin:$PATH’ >> /etc/profile.d/jdk.sh

2. You have to source the file you just created by typing:
source /etc/profile.d/jdk.sh

3. Test if Java environment is successfully installed by typing in this in the shell:
java -version

Written by adpjhype

December 18, 2008 at 8:16 am

Posted in Java

Tagged with

The Story of Groovy

leave a comment »

James Strachan is the founder of the Groovy Project. His inspiration of this project was started when he and his wife were waiting for the late plane schedule at the airport. He decided to visit Internet Cafée at the Airport, while his wife was going for shopping. When he was browsing from one web page to the others web page he decided to visit Python official Web Site. When he learned this language, he realized that there is a large amount of beautiful language features in Python that do not exist in his beloved programming language and platform technology, Java.

James Strachan and Bob McWhirter founded the Groovy project in 2003, recognizing that application development in Java is characterized by using multiple frameworks and gluing them together to form a product. They designed Groovy to streamline exactly this kind of work. At the same time, Richard Monson-Haefel met James, who introduced him to Groovy. Richard immediately recognized Groovy’s potential and suggested the submission of a Java Specification Request (JSR-241).

But what is the reaction of Sun Microsystem about the born of this language? Do they feel it as the other Java language competitor? No Guys, They don’t see Groovy as Java’s rival but rather as a companion that attracts brilliant developers who might otherwise move to Ruby or Python and thus away from the Java platform. Since the JSR has been accepted, Groovy is the second standard language for the Java VM (besides the Java language itself).

Written by adpjhype

December 18, 2008 at 4:32 am

Posted in Groovy

Tagged with

The Story of Java

leave a comment »

Goes back to 1991, when a group of Sun engineers, led by Patrick Naughton and Sun Fellow (and all-around computer wizard) James Gosling, wanted to design a small computer language that could be used for consumer devices like cable TV switchboxes. Since these devices do not have a lot of power or memory, the language had to be small and generate very tight code. Also, because different manufacturers may choose different central processing units (CPUs), it was important not to be tied down to any single architecture. The project got the code name “Green.”

The requirements for small, tight, and platform-neutral code led the team to resurrect the model that some Pascal implementations tried in the early days of PCs. What Niklaus Wirth, the inventor of Pascal, had pioneered, and UCSD Pascal did commercially, was to design a portable language that generated intermediate code for a hypothetical machine. (These are often called virtual machines—hence, the Java Virtual Machine or JVM.) This intermediate code could then be used on any machine that had the correct interpreter. The Green project engineers used a virtual machine as well, so this solved their main problem.

The Sun people, however, come from a UNIX background, so they based their language on C++ rather than Pascal. In particular, they made the language object oriented rather than procedure oriented. But, as Gosling says in the interview, “All along, the language was a tool, not the end.” Gosling decided to call his language “Oak.” (Presumably because he liked the look of an oak tree that was right outside his window at Sun.) The people at Sun later realized that Oak was the name of an existing computer language, so they changed the name to Java. In 1992, the Green project delivered its first product, called “*7.” It was an extremely intelligent remote control. (It had the power of a SPARCstation in a box that was 6 inches by 4 inches by 4 inches.) Unfortunately, no one was interested in producing this at Sun, and the Green people had to find other ways to market their technology. However, none of the standard consumer electronics companies were interested. The group then bid on a project to design a cable TV box that could deal with new cable services such as video on demand. They did not get the contract. (Amusingly, the company that did was led by the same Jim Clark who started Netscape—a company that did much to make Java successful.)

<!–[if gte mso 9]> Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 <![endif]–><!–[if gte mso 9]> <![endif]–> The Green project (with a new name of “First Person, Inc.”) spent all of 1993 and half of 1994 looking for people to buy its technology—no one was found. (Patrick Naughton, one of the founders of the group and the person who ended up doing most of the marketing, claims to have accumulated 300,000 air miles in trying to sell the technology.) First Person was dissolved in 1994.

While all of this was going on at Sun, the World Wide Web part of the Internet was growing bigger and bigger. The key to the Web is the browser that translates the hypertext page to the screen. In 1994, most people were using Mosaic, a noncommercial Web browser that came out of the supercomputing center at the University of Illinois in 1993. (Mosaic was partially written by Marc Andreessen for $6.85 an hour as an undergraduate student on a work-study project. He moved on to fame and fortune as one of the cofounders and the chief of technology at Netscape.) In the SunWorld interview, Gosling says that in mid-1994, the language developers realized that “We could build a real cool browser. It was one of the few things in the client/server mainstream that needed some of the weird things we’d done: architecture neutral, real-time, reliable, secure—issues that weren’t terribly important in the workstation world. So we built a browser.” The actual browser was built by Patrick Naughton and Jonathan Payne and evolved into the HotJava browser that we have today. The HotJava browser was written in Java to show off the power of Java. But the builders also had in mind the power of what are now called applets, so they made the browser capable of executing code inside web pages. This “proof of technology” was shown at SunWorld ‘95 on May 23, 1995, and inspired the Java craze that continues unabated today.

The big breakthrough for widespread Java use came in the fall of 1995, when Netscape decided to make the Navigator browser Java enabled in January 1996. Other licensees include IBM, Symantec, Inprise, and many others. Even Microsoft has licensed Java. Internet Explorer is Java enabled, and Windows ships with a Java virtual machine. (Note that Microsoft does not support the most current version of Java, however, and that its implementation differs from the Java standard.) Sun released the first version of Java in early 1996. It was followed by Java 1.02 a couple of months later. People quickly realized that Java 1.02 was not going to cut it for serious application development. Sure, you could use Java 1.02 to make a nervous text applet that moves text randomly around in a canvas. But you couldn’t even print in Java 1.02. To be blunt, Java 1.02 was not ready for prime time.

The big announcements about Java’s future features trickled out over the first few months of 1996. Only at the JavaOne conference held in San Francisco in May of 1996 did the bigger picture of where Java was going become clearer. At JavaOne the people at Sun Microsystems outlined their vision of the future of Java with a seemingly endless stream of improvements and new libraries.

The big news of the 1998 JavaOne conference was the upcoming release of Java 1.2, which replaces the early toy-like GUI and graphics toolkits with sophisticated and scalable versions that come a lot closer to the promise of “Write Once, Run Anywhere”™ than their predecessors. Three days after (!) its release in December 1998, the name was changed to Java 2.

Since then, the core Java platform has stabilized. The current release, with the catchy name Java 2 Software Development Kit, Standard Edition version 1.3, is an incremental improvement over the initial Java 2 release, with a small number of new features, increased performance and, of course, quite a few bug fixes. Now that a stable foundation exists, innovation has shifted to advanced Java libraries such as the Java 2 Enterprise Edition and the Java 2 Micro Edition.

Written by adpjhype

December 18, 2008 at 4:31 am

Posted in Java

Tagged with