Auto boxing and Unboxing core concept in Java

Auto boxing in Java
Auto boxing and un-boxing is introduced in Java 1.5 to automatically convert primitive type into boxed primitive( Object or Wrapper class) in Java. If you have been using Collections like HashMap or ArrayList before Java 1.5 then you are familiar with the issue that you can not directly put primitives into Collections, instead you first need to convert them in to Object only then you can put them into Collections. Wrapper class like Integer, Double and Boolean helps for converting primitive to Object but that clutter the code. With the introduction of auto boxing and unboxing in Java this primitive to object conversion happens automatically by Java compiler which makes code more readable. But auto boxing and unboxing comes with certain caveats which needs to be understood before using them in production code and it becomes even more important because they are automatic and can create subtle bugs if you are not sure when auto boxing occurs and when auto unboxing happens. This is my fifth article on features introduced in Java 5 after my post on Java Enum,  How Generics works in Java and varargs example. In this Java tutorial we will see: What is auto boxing and unboxing?  When auto boxing and unboxing occurs in Java? and things to remember while dealing with primitives and objects in Java with code examples.


What is auto boxing and unboxing in Java
Auto Boxing and Un Boxing Example in Java 5When Java automatically converts a primitive type like int into corresponding wrapper class object e.g. Integer than its called auto boxing  because primitive is boxed into wrapper class while in opposite case is called auto unboxing, where an Integer object is converted into primitive int. All primitive types e.g. byte, short, char, int, long, float, double and boolean has corresponding wrapper class e.g. Byte, Short, Integer, Character etc and participate in boxing and unboxing. Since whole process happens automatically without writing any code for conversion its called auto boxing and auto unboxing.


When does auto boxing and unboxing occurs in Java
Auto boxing and unboxing can happen anywhere where an object is expected and primitive type is available for example In method arguments,  if you pass primitive, Java automatically converts primitive into equal value Object. Classic use of auto-boxing is adding primitive types into Collection like ArrayList in Java or creating instance of parameterized classes e.g. ThreadLocal which expect Type. here is some code example of auto boxing and unboxing in Java:

ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(1); //auto boxing
intList.add(2); //auto boxing
    
ThreadLocal<Integer> intLocal = new ThreadLocal<Integer>();
intLocal.set(4); //auto boxing

int number = intList.get(0); //auto unboxing
int local = intLocal.get(); //auto unboxing

You can find all places by applying some common sense as well, just see if an object needed or a primitive type and what is available there but don’t confuse between widening and boxing, where former refers to promoting small type into bigger type wherever expected e.g. converting byte to int. I have shared couple of conversion tutorial in java like String to int conversion and  Double to String conversion, if you like you also check those.
     

Things to remember while using auto boxing in Java
Every powerful feature comes with some caveats and corner cases, here are few which is worth remembering while using auto-boxing in Java:

1) Comparing Objects with equality Operator
I agree that auto boxing of primitive to Object  adds lot of convenience and reduce verbosity but there are few places where auto boxing is error prone e.g. equality operator "==". Since equality operator can be applied on both primitive and Objects it leads to confusion and can cause subtle issues. When you compare two object using "==" operator it compares object's identity and not value and also no auto boxing occur. By the way you its not best practice to use  equality operator to compare Objects, use equals method instead. here is an example which makes it clear :

Integer one = new Integer(1);
Integer anotherOne = new Integer(1);
    
if(one == anotherOne){
  System.out.println("both one are equal");
        
}else{
   System.out.println("Both one are not equal");
}

It will print "Both one are not equal" because of no auto boxing. Things gets more confusing when "==" comparison is combined with other logical operators like > and < which does auto unboxing before comparison. This one is explained beautifully with an example of Comparator in Effective Java, if you haven't read then go get a copy.

2) Mixing object and primitive in equality and relational operator
Another mistake to avoid while using auto-boxing and unboxing in Java is mixing  primitive and Object in equality or relational operator  much like mixing static and non static synchronized method. if we compare one primitive with another object than unboxing of object is occur which could throw NullPointerException if object is null e.g.

private static Integer count;

//NullPointerException on unboxing
if( count <= 0){
  System.out.println("Count is not started yet");
}

3) Cached Objects
One more caveat of boxing and unboxing is cached object, since valueOf() is used to create boxed primitive and it caches frequently used Object which may behave differently based upon there value as Java only cache integers from -128 to 128.  I have discussed this problem in detail on post What is wrong while using "==" with auto boxing in Java.

4) Unnecessary objects and GC overhead
Last but not least is cost associate on auto boxing and unboxing. Since auto-boxing creates unnecessary object and if that goes beyond a limit usually outside the range of cached value it can potentially slow your program by frequently causing garbage collection.

In Summary auto boxing and unboxing in Java are great convenience but demands care and awareness while using them. auto boxing and unboxing has several legitimate use case but should not be used with equality operator specially mixing with primitive and object is dangerous. If you like to read books check out Effective Java and Java 5.0 Tiger: A Developer's Notebook , those has some more insightful tips on boxing and unboxing in Java.

Importance of Enum Singleton in Java

Enum Singletons are new way to implement Singleton pattern in Java by using Enum with just one instance. Though Singleton pattern in Java exists from long time Enum Singletons are relatively new concept and in practice from Java 5 onwards after introduction of Enum as keyword and feature. This article is somewhat related to my earlier post on Singleton, 10 interview questions on Singleton pattern in Java where we have discussed common questions asked on interviews about Singleton pattern and 10 Java enum examples, where we have seen how versatile enum can be. This post is about why should we use Enum as Singleton in Java, What benefit it offers compared to conventional singleton methods etc.

Java Enum and Singleton Pattern
Enum Singleton pattern in JavaFollowing are some reasons which make sense to me for using Enum to implement Singleton pattern in Java. By the way If you like articles on design pattern than you can also check my post on Builder design pattern and Decorator design pattern .

1) Enum Singletons are easy to write
This is by far biggest advantage, if you have been writing Singletons prior ot Java 5 than you know that even with double checked locking you can have more than one instances. though that issue is fixed with Java memory model improvement and gurantee provided by volatile variables from Java 5 onwards but it still tricky to write for many beginners. compared to double checked locking with synchronization Enum singletons are cake walk. If you don't believe than just compare below code for conventional singleton with double checked locking and Enum Singletons:

Singleton using Enum in Java
This is the way we generally declare Enum Singleton , it may contain instace variable and instance method but for sake of simplicity I haven’t used any, just beware that if you are using any instance method than you need to ensure thread-safety of that method if at all it affect the state of object. By default creation of Enum instance is thread safe but any other method on Enum is programmers responsibility.

/**
* Singleton pattern example using Java Enumj
*/
public enum EasySingleton{
    INSTANCE;
}

You can acess it by EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.

Singleton example with double checked locking
Below code is an example of double checked locking in Singleton pattern, here getInstance() method checks two times to see whether INSTANCE is null or not and that’s why it’s called double checked locking pattern, remember that double checked locking is broker before Java 5 but with the guranteed of volatile variable in Java 5 memory model, it should work perfectly.

/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
     private volatile DoubleCheckedLockingSingleton INSTANCE;

     private DoubleCheckedLockingSingleton(){}

     public DoubleCheckedLockingSingleton getInstance(){
         if(INSTANCE == null){
            synchronized(DoubleCheckedLockingSingleton.class){
                //double checking Singleton instance
                if(INSTANCE == null){
                    INSTANCE = new DoubleCheckedLockingSingleton();
                }
            }
         }
         return INSTANCE;
     }
}

You can call DoubleCheckedLockingSingleton.getInstance() to get access of this Singleton class.

Now Just look at amount of code needed to create a lazy loaded thread-safe Singleton. With Enum Singleton pattern you can have that in one line because creation of Enum instance is thread-safe and guranteed by JVM.

People may argue that there are better way to write Singleton instead of Double checked locking approach but every approach has there own advantages and disadvantages like I mostly prefer static field Singleton intialized during classloading as shwon in below example, but keep in mind that is not a lazy loaded Singleton:

Singleton pattern with static factory method
This is one of my favorite method to impelemnt Singleton pattern in Java, Since Singleton instance is static and final variable it initialized when class is first loaded into memeory so creation of instance is inherently thread-safe.

/**
* Singleton pattern example with static factory method
*/

public class Singleton{
    //initailzed during class loading
    private static final Singleton INSTANCE = new Singleton();

    //to prevent creating another instance of Singleton
    private Singleton(){}

    public static Singleton getSingleton(){
        return INSTANCE;
    }
}

You can call Singleton.getSingleton() to get access of this class.


2) Enum Singletons handled Serialization by themselves
Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton as shwon in below example :

    //readResolve to prevent another instance of Singleton
    private Object readResolve(){
        return INSTANCE;
    }

This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but witn Enum Singleton, Serialization is guarnateed by JVM.

3) Creation of Enum instance is thread-safe

As stated in point 1 since creatino of Enum instance is thread-safe by default you don't need to worry about double checked locking.

In summary, given the Serialzation and thraead-safety guaranteed and with couple of line of code enum Singleton pattern is best way to create Singleton in Java 5 world. you can still use other popular methods if you feel so but I still have to find a convincing reason not to use Enum as Singleton, let me know if you got any.

Java Tutorial : Convert byte array to string in java & string to byte array

The following tutorial tells about how to convert a String to byte array and byte array to String with suitable examples. Byte array may be used as buffer in many programs to store the data in byte format .The following lines of code read data from the input stream to the buffer and the buffer gets printed as readable characters until end of stream.



  InputStream in = new FileInputStream("filename");
  byte[] buf = new byte[1024];
   while ((int l = in.read(buf,0,)) !=-1) {
 System.out.println(new String(buf));
    }
Some of methods which are used to encrypt data (such as doFinal() of Cipher class , digest() method of MessageDigest class ) of JCE API accepts byte array , encrypts the data and returns the byte array as encrypted data . The following lines of code retrieve the sequence of bytes from the original string and passed to the doFinal() method which returns the encrypted sequence of bytes as byte array.

 

private static byte[] encrypt(String input)  throws Exception, InvalidKeyException, BadPaddingException,    IllegalBlockSizeException {
   ............
   ...........
   cipher.init(Cipher.ENCRYPT_MODE, key); (Assume that cipher object is already created)
   byte[] inputBytes = input.getBytes();
   return cipher.doFinal(inputBytes);
  }
The following lines of code decrypts the sequence of encrypted bytes and returns a byte array. The byte array needs to be converted to original String that can be readable .
  

 private static String decrypt(byte[] encryptionBytes) throws InvalidKeyException,    BadPaddingException,  IllegalBlockSizeException {
   cipher.init(Cipher.DECRYPT_MODE, key);
   byte[] decryptedBytes =   cipher.doFinal(encryptionBytes); (Assume that cipher object is already created)
   String originalString =    new String(decryptedBytes);
   return originalString;
    } 
So now let us see that How to convert String to byte array and vice versa.

  To convert String to byte array of non- Unicode characters , use getBytes() method of String class:
            String.getBytes() : Encodes this String into a sequence of bytes using the the character encoding (eg. ASCII , ...) used by the underlying OS , storing the result into a new byte array.

  byte[] inputBytes = input.getBytes(); where input is a string

  To convert sequence of bytes to String :

             toString() method of byte array does not help you. Converting byte array to String in Java is simple as one of the String class constructors accepts byte array as an argument. If a byte array contains non-Unicode text, you can convert the text to Unicode with one of the String constructor methods.

  String originalString = new String(decryptedBytes); where decryptedBytes is a byte array.


 Note : When we convert String to byte array , the characters of the string object is stored as 8-bit characters. The conversion of characters from Unicode to 8-bit bytes depends upon the default encoding for your system. When the string contain Unicode characters is converted to 8-bit bytes, upper byte of the Unicode character is discarded, resulting in the ASCII equivalent. In this case, the effect of the getBytes() method is unspecified.

 To convert the String object to UTF-8, invoke the getBytes method and specify the appropriate encoding identifier as a parameter.

           byte[] bytes_utf8 = input.getBytes("UTF8");


                    -  The above getBytes method returns an array of bytes in UTF-8 format.

 To create a String object from an array of non-Unicode bytes, invoke the String constructor with the encoding parameter.

                 String originalString = new String(bytes_utf8, "UTF8");

SubQuery Tutorial with example in SQL – Correlated vs Noncorrelated

SubQuery in SQL is a query inside another query. Some time to get a particular information from database you may need to fire two separate sql queries, subQuery is a way to combine or join them in single query. SQL query which is on inner part of main query is called inner query while outer part of main query is called outer query. for example in below sql query

SELECT name FROM City WHERE pincode IN (SELECT pincode FROM pin WHERE zone='west')

section not highlighted is OUTER query while section highlighted with grey is INNER query. In this SQL tutorial we will see both Correlated and non correlated sub-query and there examples, some differences between correlated and noncorrelated subqueries and finally subquery vs join which is classic debatable topic in SQL. By the way this SQL tutorial is next in series of SQL and database articles in Javarevisited like truncate vs delete and 10 examples of  SELECT queries. If you are new here then you may find those examples interesting.

SubQuery Rules in SQL
Like any other concept in SQL, subquery also has some rules and you can only embed one query inside another by following rules :
1. subquery can be used in insert statement.
2. subquery can be used in select statement as column.
3. subquery should always return either a scaler value if used with where clause or value from a column if used with IN or NOT IN clause.

Before going to understand non-correlated  and correlated subquery, let’s see the table and data which we are going to use in this example. Until you have an understanding of how table look like and what kind of data it stores its little difficult to understand queries. In this subquery example we will use two table Stock and Market. Stock holds different stocks and Market holds all stock exchanges in the world.

mysql> select * from stock;
+---------+-------------------------+--------------------+
| RIC     | COMPANY                 | LISTED_ON_EXCHANGE |
+---------+-------------------------+--------------------+
| 6758.T  | Sony                    | T                  |
| GOOG.O  | Google Inc              | O                  |
| GS.N    | Goldman Sachs Group Inc | N                  |
| INDIGO  | INDIGO Airlines         | NULL               |
| INFY.BO | InfoSys                 | BO                 |
| VOD.L   | Vodafone Group PLC      | L                  |
+---------+-------------------------+--------------------+
6 rows in set (0.00 sec)

mysql> select  from Market;
+------+-------------------------+---------------+
| RIC  | NAME                    | COUNTRY       |
+------+-------------------------+---------------+
| T    | Tokyo Stock Exchange    | Japan         |
| O    | NASDAQ                  | United States |
| N    | New York Stock Exchange | United States |
| BO   | Bombay Stock Exchange   | India         |
+------+-------------------------+---------------+
4 rows in set (0.00 sec)


Noncorrelated subquery in SQL
There are two kind of subquery in SQL one is called non-correlated and other is called correlated subquery. In non correlated subquery, inner query doesn't depend on outer query and can run as stand alone query.Subquery used along-with IN or NOT IN sql clause is good examples of Noncorrelated subquery in SQL. Let's a noncorrelated subquery example to understand it better.

NonCorrelated Subquery Example:
Difference between correlated and noncorrelated suqueryLet’s see the query  “Find all stocks from Japan”, If we analyze this query we know that stock names are stored in Stock table while Country name is stored in Market table, so we need to fire two query first to get RIC for Japanese market and than all stocks which is listed on that Market. we can combine these two queries into one sql query by using subquery as shown in below example:

mysql> SELECT COMPANY FROM Stock WHERE LISTED_ON_EXCHANGE = (SELECT RIC FROM Market WHERE COUNTRY='Japan');
+---------+
| COMPANY |
+---------+
| Sony    |
+---------+
1 row IN SET (0.02 sec)

Here part which is inside bracket is called inner query or subquery. As you see in this example of subquery, inner query can run alone and its not depended on outer query and that's why its called NonCorrelated query.

NonCorrelated Subquery Example with IN Clause SQL
NonCorrelated subquery are used along-with IN and NOT IN clause. here is an example of subquery with IN clause in SQL.
SQL query: Find all stocks from United States and India

mysql> SELECT COMPANY FROM Stock WHERE LISTED_ON_EXCHANGE IN (SELECT RIC FROM Market WHERE COUNTRY='United States' OR COUNTRY= 'INDIA');
+-------------------------+
| COMPANY                 |
+-------------------------+
| Google Inc              |
| Goldman Sachs GROUP Inc |
| InfoSys                 |
+-------------------------+

When Subquery is used along-with IN or NOT IN Clause it returns result from one column instead of Scaler value.

Correlated SubQuery in SQL
Correlated subqueries are the one in which inner query or subquery reference outer query. Outer query needs to be executed before inner query. One of the most common example of correlated subquery is using keywords exits and not exits. An important point to note is that correlated subqueries are slower queries and one should avoid it as much as possible.

Example of Correlated Subquery in SQL
Here is an example of Correlated subquery “Return all markets which has at least one stock listed on it.”

mysql> SELECT m.NAME FROM Market m WHERE m.RIC = (SELECT s.LISTED_ON_EXCHANGE FROM Stock s WHERE s.LISTED_ON_EXCHANGE=m.RIC);

+-------------------------+
| NAME                    |
+-------------------------+
| Tokyo Stock Exchange    |
| NASDAQ                  |
| New York Stock Exchange |
| Bombay Stock Exchange   |
+-------------------------+
4 rows IN SET (0.00 sec)

Here inner query will execute for every Market as RIC will be changed for every market.

Difference between Correlated and NonCorrelated Subquery
Now we have seen correlated and noncorrelated subqueries and there example its much easier to understand difference between correlated vs noncorrelated queries. By the way this is also one of the popular sql interview question and its good to know few differences:

1.In case of correlated subquery inner query depends on outer query while in case of noncorrelated query inner query or subquery doesn't depends on outer query and run by its own.
2.In case of correlated subquery, outer query executed before inner query or subquery while in case of NonCorrelated subquery inner query executes before outer query.
3.Correlated Sub-queries are slower than non correlated subquery and should be avoided in favor of sql joins.
4.Common example of correlated subquery is using exits and not exists keyword while non correlated query mostly use IN or NOT IN keywords.

SubQuery vs Join in SQL
Any information which you retrieve from database using subquery can be retrieved by using different types os joins also. Since SQL is flexible and it provides different way of doing same thing. Some people find SQL Joins confusing and subquery specially noncorrelated more intuitive but in terms of performance SQL Joins are more efficient than subqueries.

Important points about SubQuery in DBMS
1.Almost whatever you want to do with subquery can also be done using join, it just matter of choice
subquery seems more intuitive to many user.
2.Subquery normally return an scaler value as result or result from one column if used along with
IN Clause.
3.You can use subqueries in four places: subquery as a column in select clause,
4.In case of correlated subquery outer query gets processed before inner query

Memory-mapped files in java tutorial with example . File I/O vs Memory-Mapped Files tutorial

The following tutorial covers about what is memory mapped files and  what are the advantages and drawbacks of using Memory-Mapped Files and also covers that how to map a  file into memory with example code.
 Any files can be accessed using  

1.  Simple  File I/O
 2.  Memory-Mapped Files

Some of  the drawbacks of Simple File I/O  (Usual  read() and write()) is as follows.

 When an  application requires to read data from outside  such as   file data  on disk (outside of virtual  / process  address space)  ,  system call to usual file I/O functions (e.g., read() and write() subroutines )  , copies the file data to intermediate buffer  . Then the data is transferred  to the physical file or the process .  This  Intermediate buffering is slow and expensive which reduces the I/O performance.
 The alternative mechanishm is Memory mapped files . Memory mapped files provide a mechanism  to map the  file data  into the area of Virtual Memory (process address space) .   This enables an application, including multiple processes, to read and write  the file data directly to the memory  without performing any explicit file read or write operations on the physical file .   When we access a  part of the file which is  not  in  memory, it will be automatically paged in  by  the  OS.  Subsequent reads / writes to / from that page are treated as ordinary memory accesses .  There is no separation between modifying the data and saving it to a disk.

Some of the benefits using  Memory mapped files ( Accessing a data directly from main memory )
 1. Eliminate intermediary buffering

2. Increases I/O performance

3. More than one processes can map the same file  i.e  pages in memory can be be shared among the processes which saves memory space and  supports inter-process communications

4. supports  lazy loading i.e   the process of allocating and loading pages in main memory  must be deferred as long as possible . The page is loaded into RAM when the page is actually needed .   You don't need to have memory for the entire file.  This helps  to read  a large file with small amount of RAM

5. File data can be accessed and modified with out having to execute any explicit I/O operations  on the file.

6. Reading / Writing  large files this is often  more efficient than invoking the usual read or write methods.

      Mapping a file into memory is implemented by a FileChannel object that  is packaged with java.nio   which is available from JDK 1.4 .   The map() method of a FileChannel object  maps to  a portion or all of channel’s file  into memory  and  returns a reference to a buffer of type MappedByteBuffer .

 Syntax for the map() method is
 public abstract MappedByteBuffer map(FileChannel.MapMode mode,      long position,  long size)       throws IOException
              - Maps a region of this channel's file directly into memory.   The map() method returns a MappedByteBuffer, which is a subclass of ByteBuffer. Methods of ByteBuffer can be used with MappedByteBuffer class . 
 A region of a file may be mapped into memory in one of the following three modes:
 1. MapMode.READ_ONLY - Can not modify the resulting buffer
 2. MapMode.READ_WRITE - Can change the resulting buffer
 3. MapMode.PRIVATE  -  creates a private copies of the modified portions of the buffer  which is  not  visible to other processes hat have mapped the same file.  Modification to the resulting buffer will not be reproduced to the file

The following line of code maps the first 1024 bytes of a file into memory in Read / write mode. 

MappedByteBuffer mbb = fc.map( FileChannel.MapMode.READ_WRITE, 0, 1024 );

To map the entire file specify the start file position as zero, and the length that is mapped as the length of the file.

MappedByteBuffer mbb= fc.map(READ_WRITE, 0L,fc.size()).load();

The buffer is created with the READ_WRITE mode, which permits the buffer to be accessed or modified and maps to the entire file.  The map() method returns a reference to the MappedByteBuffer object
 Drawbacks of  Memory mapped files

                 1.  Wastage of memory for small files .  In Memory mapped files , disk block is mapped  to a page   in memory . The size of the  page  is usually  4 KB  . To map a  file  with size of 9 KB , 3 pages are allocated with total size of 12 KB in Memory.  3 KB   memory is wasted.

                 2. When a requested page is not in the main memory , page fault occurs which reduces performance.

                3. Another limitation is Maping  of file contents in memory depends on available Virtual Address Space.   32 bit OS gets a set of virtual memory addresses from 0 to 4,294,967,295 (2*32-1 = 4 GB) .
 Now let us see the code example of Maemory Mapped Files . I have written two programs  to read a large log file  using the Standard File IO and Memory-mapped I/O  and you can run the two programs to get the time taken to read the given big log files by Standard File IO and Memory-mapped I/O . Obviously , Reading large file using Memory-mapped I/O  is faster than using Standard File IO.

Using Memory-mapped I/O
  

 

import java.io.FileInputStream;

import java.io.*;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;

public class MemoryMappedIO1 {

    public static void main(String[] args) {

        long tm = 0;


        FileInputStream fis = null;


        try {




           fis = new FileInputStream("CBS.log");


            int len=1024;


            byte[] buf = new byte[len];



            tm = System.currentTimeMillis();




            FileChannel fc = fis.getChannel();




            MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());




            while (mbb.hasRemaining()) {



 if (len>mbb.remaining())




 mbb.get(buf,0,mbb.remaining());




 else




 mbb.get(buf,0,len);



//System.out.println(new String(buf));


            }




            System.out.printf("Time to read file TestLog.log: %d ms\n", (System.currentTimeMillis()-

tm));




        }




        catch (Exception ex) {




            ex.printStackTrace(System.err);




        }




        finally {




            if (fis != null) {




                try {




                    fis.close();




                }




                catch (Exception ex) {




                }




            }




        }




    }




}



Using Standard File IO:
   

 

import java.io.BufferedReader;




import java.io.*;




public class StandardBufferedIO1 {


    public static void main(String[] args) {


        long ts, te = 0;

         InputStream in = null;


        try {


    in=new FileInputStream("CBS.log");


            ts = System.currentTimeMillis();


      byte[] buf = new byte[1024];


    int len;

    while ((len = in.read(buf)) !=-1) {


 //System.out.println(new String(buf));


      //  out.write(buf, 0, len);


    }


              te=System.currentTimeMillis();


            System.out.printf("Time taken to read log file  %d ms\n", (te-ts));


        }




        catch (Exception e) {


            e.printStackTrace(System.err);


        }


        finally {




            if (in!= null) {




                try {


                  in.close();


                }


                catch (Exception e) {e.printStackTrace(System.err);    }


            }


        }


    }


}

Apache ofbiz tutorial : how to change ofbiz's administrator login password

To change administrator login password apply below step :

If you are the OFBiz administrator and you forget this user's password, you could be out of luck
since the administrator (the "admin" user login) has all the privileges necessary to perform
any OFBiz task, including logging in and assigning the admin user a new password.
If you find yourself in this situation, there is no easy way to retrieve this password such that
you may use it to log in. The only solution to this problem is to reset the password by directly
manipulating the correct entity in the database, or let OFBiz do that for you using the
following recipe.
Getting ready
Before following this recipe, ensure these steps are performed:
1. Navigate to the OFBiz install directory.
2. Open a command line or console window.
3. If you are running OFBiz, it is best to stop it at this time.

To reset the admin password, follow these steps:
1. From the OFBiz install directory, run the following command:
ant load-admin-user-login -DuserLoginId=admin
2. Restart OFBiz.
3. Log in to OFBiz as the admin user where the login user name is "admin" and the
password is "ofbiz".
4. When prompted to change the admin user's password, enter the new password or
"ofbiz" to maintain the existing value.

How to change JavaScript fuction call name submitFormDisableSubmits in Apache ofbiz minilang form onSubmit event

When i  am using minilang form it is always call submitFormDisableSubmits() javaScript function on onSubmit event 

we can change it by following way

apache use HtmlFormMacroLibrary.ftl where you can change the function name submitFormDisableSubmits according to you