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

How to use own JavaScript file in Apache ofbiz | implement own JavaScript function call in Apache ofbiz

In my Apache ofbiz project i have implemented own JavaScript in Minilang code

1. Add below line of code to give reference of JavaScript File in ogbiz Screen


           <actions>
                <set field="titleProperty" value="ProductFindFacilities"/>
                <set field="headerItem" value="facility"/>
                <set field="layoutSettings.javaScripts[+0]" value="/images/TestJavaScript.js" global="true"/>
            </actions>

2. by using Event and Action attribute as below to call javascript function from minilang form code

<field name="submitButton" title="Get Inventory Feed" widget-style="smallSubmit" event="onclick" action="javascript:return submitFormEnableButtonByNameTest(this,submitButton)">
                                                <submit button-type="submit" />

event  > it use for write javaScript event like onClick, onMouseOver etc
action > use for call funtion name of JavaScript

How to Reboot remote computers on a domain

Below Step to reboot remote computers
arrComputer = Array("Computer1", "Computer2", "Computer3")
For Each strComputer In arrComputer
Set objWMIService = GetObject ("winmgmts:{impersonationLevel=impersonate,(Shutdown)}\\" & strComputer & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")

For Each objOperatingSystem in colOperatingSystems
objOperatingSystem.Reboot(2)
Next
Next