Only my share

Java , Groovy and others

Archive for January 2009

What the Heck Is a File Hole?

without comments

 

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

without comments

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