Tuesday, April 29, 2014

How to copy file from one system to another on linux/unix systems

A. Through scp

1. Copy from remote to local
      scp <username>@<remote hostname or ip address>:<path to file>/<file name> <local directory>

2. Copy from local to remote
      scp <path to file>/<file name> <username>@<remote hostname or ip address>:<remote directory>

3. Copy from one remote to another remote system
     scp <username on remote 1>@<remote hostname or ip address of remote 1>:<path to file>/<file name> <username on remote 2>@<remote hostname or ip address of remote 2>:<directory>

B. Through sftp

  1. At the command line type sftp <remote hostname or ip address>
  2. Enter your password for the remote site
  3. cd to the desired directory
  4. type get <filename> to fetch a file from remote to local; type put <filename> to transfer a file from local to remote.
--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, April 17, 2014

What is a functional interface? Features of functional interfaces

Functional Interface is a new concept introduced in java 8. Functional interfaces are particularly used for Lambda Expressions. Following are the characters of function interfaces.

1. A functional interface can have only one abstract method except those methods declared in the Object class. For example the Runable interface has only one method run(), therefore it is a functional interface. Following is another example.

     public interface Qualified {
            public Object getTheObject();
            public String toString();
            public boolean equals(Object obj);
      }
Since the toString and equals methods are methods declared in the Object class, this Qualified interface is also a functional interface.

2. A functional interface can have static and default methods.

      public interface GetIt {
            public Object getIt();

            public static boolean checkIt(Object obj) {
                  if (obj instanceof String) return true;
                  return false;
            }

            public default Integer getSum(Integer one, Integer two) {
                  return one+two;
            }
      }
The GetIt interface has only one abstract method, getIt, so it is a functional interface.

3. The abstract method of a functional interface can be inherited from another interface or overrides a method in another interface.

       //interface Face1 has two abstract methods
       interface Face1 {
          public boolean isTrue();
          public void changeIt();
      }

      //interface Face2 has one abstract method, changeIt, inherited from face1
      //therefore, interface Face2 is a functional interface
      interface Face2 extends Face1 {
          @Override
          default boolean isTrue() {return true;}
      }

      //interface Face3 has one abstract method that overrides the method in its super interface
      //therefore, interface Face3 is a functional interface
      interface Face3 extends Face2 {
            @Override
            public void changeIt();
      }

      //Since Face2 and Face3 are functional interfaces, they can be implemented with Lambda Expression
      public class TestDefautMethod {
            public void testDefault(Face2 theFace2, Face3 theFace3){
                  theFace2.changeIt();
                  theFace3.changeIt();
            }
 
            public static void main(String[] args){
                 TestDefautMethod tester = new TestDefautMethod();
                 tester.testDefault(()->System.out.println("Changed it successfully in Face2!"),
                                           ()->System.out.println("Changed it successfully in Face3!"));
           }
      }
The output of executing TestDefautMethod is the following.
      Changed it successfully in Face2!
      Changed it successfully in Face3!

4. In java 8, a functional interface is normally marked with the annotation @FunctionalInterface. However, as long as an interface has only one abstract method, it is a qualified functional interface regardless whether it has the annotation or not.

However, if an interface has the @FunctionalInterface annotation and contains more than one abstract method, the compiler will identify it as an error.

       @FunctionalInterface
       interface Face4 extends Face3 {
              public Integer sumIt(Integer one, Integer two);
       }
Face4 has two abstract methods, changeIt inherited from super interface and sumIt declared in itself. Compiling this code generates the following error.

error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
  Face4 is not a functional interface
    multiple non-overriding abstract methods found in interface Face4

References:

1. Default Methods

-----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, April 16, 2014

Java communications over network

TCP: Transmission Control Protocol, is a connection-based protocol which guarantees that data reaches its destination successfully and in the same order the data was sent.

UDP: User Datagram Protocol, sends packets of data, datagrams, from one application to another, without guarantee that the data will arrive their destination, and the datagrams may reach their destination in any order. UDP is not connection-based.

Java classes which use TCP or UDP to communicate over network are located in the java.net package. Classes such as URL, URLConnection, Socket, and ServerSocket use the TCP; and classes such as DatagramPacket, DatagramSocket, and MulticastSocket use the UDP.

A. Sample code using TCP to communicate over the Internet

1. Through URL and URLConnection

import java.net.*;
import java.io.*;

public class TCPWorker {
    public static void main(String[] args) throws Exception {
        //Read the www.google.com web site line by line
        URL gUrl = new URL("http://www.google.com/");
        BufferedReader in = new BufferedReader(
                    new InputStreamReader(gUrl.openStream()));

        //Or use URLConnection to read from the URL
//        URLConnection guCon = gUrl.openConnection();
//        BufferedReader in = new BufferedReader (
//                    new InputStreamReader(
//                    guCon.getInputStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }

      //Save the content of www.google.com web site to a file
      //URL gUrl = new URL("http://www.google.com/");
      InputStream is = gUrl.openStream();
     Files.copy(is, FileSystems.getDefault().getPath("<dirctory>", "<file name>"), StandardCopyOption.REPLACE_EXISTING);
}

2. Through Socket

//The server
import java.net.*;
import java.io.*;

public class TCPServer {
       public static void main(String[] args) {
             int connectionCount = 0;
              try {
                    ServerSocket serverSocket = new ServerSocket(<port number>);
                    while (connectionCount < 20) {
                           Socket clientSocket = serverSocket.accept();
                           connectionCount++;
                           new Thread() {
                                 public void run() {
                                        BufferedReader reader = new BufferedReader(
                                                                 new InputStreamReader(
                                                                 clientSocket.getInputStream()));
                                        PrintWriter writer = new PrintWriter(
                                                                 clientSocket.getOutputStream());

                                        String request = "";
                                        while ((request = reader.readLine()) != null) {
                                                writer.println("Keep searching, you will get the answer eventually!");
                                        }

                                       public void join() {
                                 }.start();
                          }
                   }
             } catch (Exception e) {
                   e.printStackTrace();
             }
       }
}


//The client
import java.net.*;
import java.io.*;

public class TCPClient {
      public static void main(String[] args) {
            try {
                  Socket clientSocket = new Socket(<host name>, <port number>);
                  PrintWriter writer = new PrintWriter(
                                                                 clientSocket.getOutputStream(), true);
                  BufferedReader reader = new BufferedReader(
                                                                 new InputStreamReader(
                                                                 clientSocket.getInputStream()));

                  writer.println("What is the status?");
               
                   String answer = "";
                   while ((answer = reader.readLine()) != null) {
                            if (answer.length() > 0) {
                                  writer.println("Got it, thanks");
                                  System.out.println("The answer is: "+answer);
                             }
                             writer.println("What is the status now?");
                   }

                   //Send the content of a file to the server
                   OutputStream os = clientSocket.getOutputStream();
               Files.copy(FileSystems.getDefault().getPath("<dirctory>", "<file name>"), os);
            }
      }
}

B. Sample code using UDP to communicate over the network

//The server
import java.net.*;
import java.io.*;

public class UDPServer extends Thread {
      private boolean keepRunning = true;

      public void run() {
            //create the socket
            DatagramSocket serverSocket = new DatagramSocket(<port number>);
            while (keepRunning) {
                  try {                  
                        //receive data
                        byte[] inData = new byte[serverSocket.getReceiveBufferSize()];
                        DatagramPacket packet = new DatagramPacket(inData, inData.length);
                        serverSocket.receive(packet);

                       byte[] dataReceived = packet.getData();
                       System.out.println("The request is: "+new String(dataReceived, 0, serverSocket.getLength()));

                       //send data
                       SocketAddress address = packet.getSocketAddress();
                       String answer = "Keep searching, you will get the answer eventually";
                       byte[] outData = answer.getBytes();

                       packet = new DatagramPacket(outData, outData.length, address);
                       serverSocket.send(packet);
             } catch (Exception e) {
                    e.printStackTrace();
                    keepRunning = false;
             }
             serverSocket.close();
      }

      public static void main(String[] args) {
              new UDPServer().start();
       }
}

//The client
import java.net.*;
import java.io.*;

public class UDPClient {
      public static void main(String[] args)  throws Exception {
             //create the socket
             DatagramSocket clientSocket = new DatagramSocket();

             //send request
             String request = "What is the status?";
             byte[] outData = request.getBytes();
           
             SocketAddress serverAddress = new InetSocketAddress(<host name>, <port number>);
             DatagramPacket packet = new DatagramPacket(outData, outData.length, serverAddress);
             clientSocket.send(packet);

             //receive response
             byte[] inData = new byte[serverSocket.getReceiveBufferSize()];
             packet = new DatagramPacket(inData, inData.length);
             clientSocket.receive(packet);

             byte[] dataReceived = packet.getData();
             System.out.println("The response is: "+new String(dataReceived, 0, clientSocket.getLength()));
      }
}

References:

1. Reading from and writing to a URLConnection
2. Writing a datagram client and server

-----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.




Tuesday, April 15, 2014

CLOBs, NCLOBs and BLOBs

CLOB, NCLOB and BLOB are database data types with data size up to 128 terabytes. The data size of regular VARCHAR and VARBINARY is 32 kilobytes.

CLOB stands for character large object, which is a Unicode character string. It is appropriate for storing text-orientated information.

NCLOB stands for national character large object, which is a Unicode character string. This data type like the CLOB data type, is appropriate for storing text-orientated information.

BLOB stands for binary large object, which is a binary string. This data type is appropriate for storing images, sound, and videos.

Following is a sample code of using these data types.

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.PreparedStatement;

public class Test {
      public static void main(String[] args) {
            Connection conn = null;
            try {
                  conn = <your method of getting the database connection>;
         

               //Save data to database

                  //Create the data type objects
                  Clob theClob = conn.createClob();
                  NClob theNclob = conn.createNClob();
                  Blob theBlob = conn.createBlob();
         
                  //Add data to the data type objects
                  BufferedReader charReader = new BufferedReader(
                           new FileReader("descritpion.txt"));
                  StringBuilder file = new StringBuilder();
                  String line = "";
                  while ((line = charReader.readLine()) != null){
                         file.append(line);
                  }
         
                  theClob.setString(1, file.toString());
                  theNclob.setString(1, file.toString());
                  charReader.close();
         
                 BufferedInputStream input = new BufferedInputStream(
                          new FileInputStream("happyBird.gif"));
         
                 OutputStream byteWriter = theBlob.setBinaryStream(1);
                  int theChar = -1;
                  while ((theChar = input.read()) != -1) {
                        byteWriter.write(theChar);
                  }
                  byteWriter.flush();
                  input.close();
                  byteWriter.close();
         
                  //Insert the data into database
                  String sql = "INSERT into picture values(?, ?, ?)";
                  PreparedStatement pstmt = conn.prepareStatement(sql);
                  pstmt.setClob(1, theClob);
                  pstmt.setNClob(2, theNclob);
                  pstmt.setBlob(3, theBlob);
                  pstmt.executeUpdate();
                  pstmt.close();

              //Retrieve data from database

                  String sql2 = "SELECT title, description, image from picture";
                  pstmt = conn.prepareStatement(sql2);
                  ResultSet rs = pstmt.executeQuery();
                  while (rs.next()) {
                         Clob myClob = rs.getClob(1);
                         String title = myClob.getSubstring(1, myClob.length());

                         NClob myNclob = rs.getNClob(2);
                         String description = myNclob.getSubstring(1, myNclob.length());

                         Blob myBlob = rs.getBlob(3);
                         byte[] imageArray = myBlob.getBytes(1, myBlob.length());
                  }
                   rs.close();
                   pstmt.close();
                  conn.close();
            }catch (Exception e){
                  e.printStackTrace();
            }
      }
}

References:

1.Using Large Objects
2. 26 Oracle Data Types

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, April 14, 2014

Extract sound, music or audio from power point slide show (.pps file)

After you have saved the .pps file on your computer, make sure that your windows explorer displays file extensions. If you need information about how to make windows explorer to display file extensions, click here.

Make a copy of the .pps file before you continue.

You may use one of the following methods to extract audios from the power point show.

A. Convert to web page file

Right click on the .pps file and choose rename
Change the file extension to .ppt for microsoft office or .ppsx for LibreOffice and open it
Click on File in the top menu, choose Save As, and save the file as a .htm file. If you are not able to save the file as a .htm file, click on File in the top menu, choose Export, and export the file as a .htm file.
Go to the directory where you saved the file, you should also find a folder with the same name of your saved file in the directory. All the audio files associated with the power point show should be here. Or all the audio files should be in the directory where you saved the .htm file.

B. Convert to .zip file

Right click on the .pps file and choose rename
Change the file extension to .zip
Right click on the file and choose Extract All, and all the audio files should be in the directory where you extract the files.

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Show or hide file extensions in Windows Explorer

A file extension determines which program should open the file. It is the last part of the file name separated from the main file name by a dot.

A. Windows 8.1 has the following choices for showing or hiding file extensions

1. From the Ribbon interface

  • Open windows explorer
  • Click View in the top menu
  • Check or uncheck the File name extensions checkbox according to if you would like to show or hide file extensions

2. From the Control Panel

  • Open the Control Panel
  • Click the Folder Option icon. If you could not find the Folder Options icon, type Folder Options in the search field located at the upper right corner
  • Click to open the View tab
  • Check or uncheck the Hide file extensions for known file types according to if you would like to hide or show file extensions
  • Click OK


B. Windows 7 and Vista

  • Open windows explorer
  • Click Organize on the top menu and choose Folder and search options
  • Select the View tab
  • Check or uncheck the Hide file extensions for known file types according to if you would like to hide or show file extensions
  • Click OK


C. Windows 2000 and XP

  • Open windows explorer
  • Click Tools on the top menu, choose Folder Options, and then choose Folder and search options.
  • Select the View tab
  • Check or uncheck the Hide file extensions for known file types according to if you would like to hide or show file extensions
  • Click OK


D. For all Windows

From the Registry editor, you can force windows explorer to show file extensions for a specific file type (e.g. the .exe file type)

  • Press Win+R keys on the keyboard, and type msconfig in the search field, then press Enter
  • Select the Tools tab in the pop up window
  • Select Registry Editor and then press the Launch button. (Alternatively you can launch the registry editor by typing regedit in the search field at the first step.)
  • Find the entry HKEY_CLASSWS_ROOT\.exe on the left side of the window, click on it and read on the right side of the window that it is a type of exefile, that is its ProgID is exefile
  • Find the entry HKEY_CLASSWS_ROOT\exefile on the left side of the window, click on it.
  • Right click on the right side of the window to create a new String Value, AlwaysShowExt or NeverShowExt.
  • Sign out your system and sign in again. The setting is now effective


References:

1. How to show or hide file extensions in Windows 8.1
2. How to show or hide file name extensions in Windows Explorer

----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Friday, April 11, 2014

ERROR 42Y07: java.sql.SQLException: Schema 'abc' does not exist

A. This exception throws when the schema does not exist in the database. A schema is a structure to group a set of tables, views and other data and operations.

To fix it, create the schema by executing this SQL statement:
Create SCHEMA <schema name>;

In Oracle, the above SQL does not actually create a schema. A schema is created when a user is created.
Create USER <username> IDENTIFIED BY <password>;

To create table and view within the schema in Oracle:
Create SCHEMA AUTHORIZATION <username>
      <create table statement>
      <create view statement>
      <grant statement>;

B. This type of exception may also throw when you are referring a table that is not in your default/current schema. In this case, you need to add the schema to the entity you are referring such as <schema name>.<table name>.<column name>

References:
1. CREATE SCHEMA statement
2. ERROR 42Y07: Schema 'SchemaName' does not exist.

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Working with Java DB in NetBeans

Java DB is part of the java JDK from version later than 5. To use Java DB in the NetBeans IDE, follow the steps below.

A. Create a Java DB Database in NetBeans


  1. Click Window on the top menu and choose Services. 
  2. In Services window, expand the Database node, 
  3. Right click on Java DB and choose Properties to view the installation and location of the database
  4. Right click on Java DB and choose Start Server
  5. Right click on Java DB again and choose Create Database. Enter the Database Name, User Name and Password, and click OK.


Now the database is ready to use.
Driver: org.apache.derby.jdbc.EmbeddedDriver
URL: jdbc:derby:<database name>

B. Make connection to database


  1. Expand the Java DB node
  2. Right click on you database name and choose connect
  3. A connection node with the text "jdbc:derby://localhost:1527/<database name> [<username> on <username in upper case>]" appears under the Drivers


C. Create table, view, and execute query


  1. Expand the connection node created in B
  2. Expand the node whose text corresponds to your schema


    3. Use the Create Dialog
        1). To create a table, right click on the Tables node and choose Create Table. In the pop up window, enter your table name, and use the Add column button to add columns, then click OK.
        2). To create a view, right click on the Views node and choose Create View. In the pop up window, enter your view name and the SQL to created the view, then click OK.

     4. Use the SQL Editor
         1). Right click on the connection node, or the Tables node, or the Views node, or a table node, choose Execute Command.
         2). In the SQL editor appeared in the main pane of the NetBeans, enter your SQL statement
         3). Highlight the SQL you want to execute and click the Run SQL button (Ctrl+Shift+E)  on top of the SQL editor to execute

If you would like to know how to communicate with your Java DB database through your java code, please read my post Java DB, the Oracle open source database for sample code.

References:

1. Java DB, the Oracle open source database
2. Working with the Java DB (Derby) Database

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Thursday, April 10, 2014

Java DB, the Oracle open source database

Java DB is a full-featured, easy-to-use, open source database which is the Apache Derby open source database included in the java JDK starting version 5.

DBMS or Vendor: derby
Driver: org.apache.derby.jdbc.EmbeddedDriver
URL: when it is used before the database is created, the URL is jdbc:derby:<database name>;create=true, afterwards, the URL is simply  jdbc:derby:<database name>

You need to include the jars in the <java home>\db\lib directory in your project classpath for using the database.

Following is a sample code of using the Java DB.

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JavaDBTest {
    private Connection conn = null;
    private boolean databaseCreated = false;
 
    private void createDatabase()
            throws ClassNotFoundException, SQLException {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        conn = DriverManager.getConnection(
                        "jdbc:derby:testDB;create=true");
        databaseCreated = true;
    }
 
    public Connection getConnection()
            throws ClassNotFoundException, SQLException{
        if (conn != null) return conn;
     
        if (databaseCreated) {
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            conn = DriverManager.getConnection(
                        "jdbc:derby:testDB");
        } else {
            createDatabase();
        }
        return conn;
    }
    public static void main(String[] args){
        JavaDBTest test = new JavaDBTest();
        try {
            Connection connection = test.getConnection();
         
            DatabaseMetaData dmd = connection.getMetaData();
            System.out.println(dmd.getDriverName());
         
            Statement statement = connection.createStatement();
            statement.execute("create table fruit (name varchar(30), value varchar(20))");
            statement.executeUpdate("insert into fruit values ('Apple', '100')");

            ResultSet result = statement.executeQuery("select * from fruit");
            while(result.next()){
                System.out.println("name="+result.getString(1));
                System.out.println("value="+result.getString(2));
            }
            result.close();
            statement.close();
            connection.close();
        }catch(Exception e){
            e.printStackTrace();
        }
     
    }
}

References:
1.Java DB
2. Working with Java DB in NetBeans

-----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, April 9, 2014

Creating and converting Date and Time in Java 8

The new Date and Time API in java 8 makes it much easier to create, manipulate, and convert Date related objects. Classes in this new addition such as LocalDate, LocalDateTime, and LocalDateTimeFormatter are very convenient to use.

1. Creating a date

a). Current date without hour, minute, and second
      LocalDate date = LocalDate.now();
b). Current date with hour, minute, and second
      LocalDateTime dateTime = LocalDateTime.now();
c). A date with given year, month and dayOfMonth
      int year = 2013;
      int month = 11;
      int dayOfMonth = 22;
      LocalDate date2 = LocalDate.of (year, month, dayOfMonth);
d). A date with given year, month, dayOfMonth, hour, minute, second, and nanosecond
      int year = 2013;
      int month = 11;
      int dayOfMonth = 22;
      int hour = 21, minute = 15, second = 50;
      LocalDateTime dateTime2 = LocalDateTime.of (year, month, dayOfMonth, hour, minute, second);

2. Finding a date

      LocalDate date = <your date>;
 To find next Saturday,
      LocalDate nextSaturday = date.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));

3. Converting a String to a date

a). String dateString = "<your date>"; //e.g "11/22/2013"
       DateTimeFormatter pattern = DateTimeFormatter.ofPattern("<pattern of your date string>"); //e.g "MM/dd/yyyy"
       LocalDate date = LocalDate.parse(dateString, pattern);
b). String dateTimeString = "<your dateTime>"; //e.g "11/22/2013 21:15:50"
      DateTimeFormatter pattern = DateTimeFormatter.ofPattern("<pattern of your date string>"); //e.g "MM/dd/yyyy HH:mm:ss"
      LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, pattern);

4. Converting date Format

a). Converting to "MM/dd/yyyy HH:mm:ss" format, e.g "11/22/2013 21:15:50"
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
      String formattedDate = formatter.format(dateTime2);
b). Converting to "MM/dd/yyyy hh:mm:ss aa" format, e.g "11/22/2013 09:15:50 PM"
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss aa");
      String formattedDate = formatter.format(dateTime2);

References:
1. Convert Date format
2. Oracle: LocalDate

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, April 8, 2014

Java Annotation

Annotation in java is used for the following purposes.
1. Add related information to what it annotates, such as author, created date, version etc.
2. Provide information for the compiler about how to handle certain situations at compiling time, such as suppress certain kind of warnings.
3.  Provide information for software tools to generate code, XML files, and other files at compiling and deployment time.
4. Provide information for program at runtime. For example when you do a class cast, (@Notnull Date)obj.

Annotation is not part of the program, so it should not affect the operation of your code.

Starting in java 8, annotations can be used anywhere a type is used such as type cast, new instance creation, throws and implements clauses. However, annotations can only be used for type, constructor, and method declarations before java 8.

Annotation type is a special type in java. Its declaration is very similar to a declaration of an interface. Its syntax is
      public @<your annotation name> {
            //fields and default values
             Object type() default Object;
             String name();
      }

To create an annotation using the NetBeans IDE. 
1. Right click on a package, choose New and then Other.
2. In the pop up window, select Java under Categories on the left side and select Java Annotation Type under the File Types on the right side. Click the Next button at the bottom.
3. Type the name of your annotation in the Class Name box, and click the Finish button.
4. Make necessary modification to the annotation, such as adding annotations and fields to it.
For example:
      @Documented //To enable the annotation to be included in javadoc
      public @interface Description {
            String author();
            String date();
            String version() default 101;
      }

To use the above annotation on the declaration of a class named BlueSky,

      @Description (author="Sarah Young", date="3/3/2013", version="102")
       public class BlueSky {
             ...............
       }

References:

1. Lesson: Annotations

------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Monday, April 7, 2014

C:\Users\\AppData\Roaming\newnext.me\nengine.dll could not be found

The nengine.dll is an adware installed automatically to your computer with the Mobogenie program which uses the OpenCandy, Quick Downloader, Conduit and other monetization programs to bundle with third party installers. Its common path is C:\Documents and Settings\user\Application data\newnext.me\nengine.dll. It is set to automatically run when a user logs on to the system and its display name in the system startup tray is "NextLive".

The nengine.dll not found message usually occurs after you deleting the nengine.dll when your security system suggests that it is a malware. The problem arises because the nengine.dll is deleted but its start-up entry is still there.

To fix this problem

  1. Click start, and type regedit to open the registry editor.
  2. Press Ctr+f on your keyboard to open the search dialog, and search for NextLive
  3. Delete the NextLive folder


To find and disable any other programs that use NextLive, do the following.

1. Download and install the Malwarebytes Anti-Malware from its official web site or other Anti-Malware.
2. Fully scan your system with the Anti-Malware
3. Disable any program found in step 2 in the system Startup tray.
    a. For window 7, click start, type msconfig in the search box and press enter; for window 8, right click on any empty space on screen and choose Task Manager.
    b. Click the Startup tab, find the program and disable it.

Or

1. Download Autoruns for Windows
2. Open the command line and type "autorunsc -s"
3. Find the program and disable/remove it accordingly

--------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
---------------------------------------------------------------------------------------------------------------------

References:

1. Microsoft Community: nengine.dll
2. HerdProtect Anti-Malware: nengine.dll

Thursday, April 3, 2014

Cause and Solution to Java OutOfMemoryError

The OutOfMemoryError is thrown when there is not enough memory available for the Java Virtual Machine to allocate an Object. Several situations can cause it to happen such as infinite loop in your program, the size of the heap space is set too small, or the program is too big to run on your machine.

1. Code has infinite loop. 

The following code will throw the OutOfMemoryError
public class MemoryTest {
      public static void main(String[] args) {
            int j = 0;
            for (int i=0; i<10; j++) {
                  System.out.println("Finished item: "+j);
                  j++;
            }
      }
}

The typo "j++" in the for loop will let the program to run continuously until it runs out of the memory. Replacing the j++ with i++ fixes the problem.

2. Heap space is too small for running a program

This can be fixed by allocating more memory for the heap space through changing the Java Virtual Machine arguments: -Xms<size> (the initial memory size) and -Xmx<size> (the maximum memory size).

A. Run program from command line
To run your MemoryTest program from command line, yo can type
java -Xmx1024M MemoryTest
or
java -Xms512M -Xmx1G MemoryTest

Many of the IDEs for java development have places for setting these configurations.
B. NetBeans
a). Click "Run" in the top menu, choose "Set Project Configuration", then choose "Customize". Or right click a project, choose "Set Configuration", then choose "Customize".
b). In the pop up window, select "Run" in the left Categories, then set your memory size in the "VM Options" on the right side of the window.

C. Eclipse
a). Click "Run" on the menu, choose "Run Configurations"
b). In the pop up window, choose the application from Java Application on the left side of the window.
c). On the right side of the window, click on the Arguments tab, and enter the -Xms<size> -Xmx<size> under the VM arguments.

3. Memory leaks

Exam your code carefully to ensure that all references to objects are set to null as soon as the objects are not needed any more. For more information on memory leaks, you can read this article from Oracle and the article from IBM. There are also many memory leak detection software available online.

If you are a NetBeans IDE user, you may use the IDE's profiler to find the code that has memory leak.

4. The program is too big to run on the machine

You need to upgrade your computer to add more memory to it.

----------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, April 2, 2014

Crystal Reports: Unexpected database connector error

When the parameters in a crystal report query are not in the form <TableName>.<ColumnName>, it sometimes throw the following exception.

 detected an exception: Unexpected database connector error
at com.crystaldecisions.reports.datafoundation.DFQuery.for(SourceFile:632)
at com.crystaldecisions.reports.datalayer.a.do(SourceFile:1621)
at com.crystaldecisions.reports.datalayer.a.a(SourceFile:1404)

To fix this exception, just add the corresponding table name following by the period to front of your parameters which are table columns in your database. For example, if you have a parameter named condition and its value is a string  value="name='apple' and location='America'", when you set it using code like the following:

ParameterFieldController pfc = <your code to get the ParameterFieldController>;
pfc.setCurrentValue("", "condition", value);

You may get the above exception.

Change the value to String value="Fruit.name='apple' and Fruit.location='America'" where Fruit is the table name in your database should fix the above exception.

--------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, April 1, 2014

Execute external shell command in java

To execute an external shell command in java, you can either call the exec method in java.lang.Runtime or create a ProcessBuilder and call its start method.

Call the exec method in java.lang.Runtime

1. Launch the internet explorer
      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import static java.lang.Compiler.command;

      public class RunShellCommand {
            public static void main(String[] args) {
                  Process p;
                  try {
                         p = Runtime.getRuntime().exec("\"/Program Files/Internet Explorer/iexplore.exe\" http://www.google.com");
                         p.waitFor();
                         p.destroy();
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
            }
      }

2. Get the hostname of your machine
      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import static java.lang.Compiler.command;

      public class RunShellCommand {
            public static void main(String[] args) {
                  Process p;
                  try {
                        p = Runtime.getRuntime().exec("hostname");
                        p.waitFor();
         
                        BufferedReader reader = new BufferedReader(
                                          new InputStreamReader(
                                          p.getInputStream()));
         
                        StringBuilder result = new StringBuilder();
         
                        String line = "";
                        while ((line = reader.readLine()) != null) {
                              result.append(line + "\n");
                        }
                        System.out.println(result.toString());
                         p.destroy();
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
          }
}

Create a ProcessBuilder and call its start method

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RunShellCommand {
    public static void main(String[] args) {
        Process p;
        try {
              ProcessBuilder pb = new ProcessBuilder("\"/Program Files/Internet Explorer/iexplore.exe\"", "http://www.google.com/search?q=java");
            p = pb.start();
            p.waitFor();
         
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            p.getInputStream()));
         
            StringBuilder result = new StringBuilder();
         
            String line = "";
            while ((line = reader.readLine()) != null) {
                result.append(line + "\n");
            }
            System.out.println(result.toString());
            p.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Launch Crystal Report in Java with Oracle database

1. Launch Crystal Report in JFrame

//Set report source
ReportClientDocument rcd = new ReportClientDocument();
rcd.open(reportPath + reportName + ".rpt", 0);

DatabaseController databaseController = rcd.getDatabaseController();
Tables tables = databaseController.getDatabase().getTables();

setConnectionInfo(tables, userName, password, host, port, databaseName);

//If there are subreports, need to do the above operation on subreports
IStrings subreportNames = rcd.getSubreportController().getSubreportNames();

SubreportController src = rcd.getSubreportController();

for (int s = 0; s < subreportNames.size(); s++ ) {
      ISubreportClientDocument subreportClientDoc = src.getSubreport(subreportNames.getString(s));
      DatabaseContoller dbc = subreportClientDoc.getDatabaseController();
      Tables subreportTables = dbc.getDatabase().getTables();

      setConnectionInfo(subreportTables, userName, password, host, port, databaseName);
}

//Set parameters
ParameterFieldController pfc = rcd.getDataDefController().getParameterFieldController();
pfc.setCurrentValue("", paramName, paramValue);

//Display report
ReportViewerBean rvb = new ReportViewerBean();
rvb.init();
rvb.start();
rvb.setReportSource(rcd.getReportSource());

//Add the ReportVieverBean to your JFrame content pane
getContentPane.add(rvb);
setVisible(true);

//Close report
rvb.stop();
rvb.destroy();
rcd.close();

private void setConnectionInfo(Tables tables, String userName, String password, String host, String port, String databaseName) {
      for (int i = 0; i < tables.size(); i++) {
             ITable table = tables.getTable(i);

             table.setName(table.getName());
             table.setAlias(table.getAlias());

             IConnectionInfo connInfo = table.getConnectionInfo();
             PropertyBag propertyBag = new PropertyBag();
             propertyBag.put("URI", "!oracle.jdbc.OracleDriver!jdbc:oracle:thin:{userName}/{password}@" + host + ":"+ port +":" + databaseName);
             propertyBag.put("Database DLL", "crdb_jdbc.dll");

             connInfo.setAttributes(propertyBag);
             connInfo.setUserName(userName);
             connInfo.setPassword(password);

             table.setConnectionInfo(connInfo);
             databaseController.setTableLocation(table, tables.getTable(i));
      }
}

2. Launch Crystal Report in web browser

//Construct the URL
String url = new StringBuilder();
url.append("http://)
.append(<your crystal report server>).append(":")
.appned(<your crystal report port>).append("/")
.append(<the file path of your report>)
.append("?reportname=")
.append(<your report name>).append("&")
.append(<parameter name>).append("=")
.append(<parameter value>)
.toString();

url = url.replaceAll(" ", "%20");      
url = url.replaceAll("\\$", "%24");

//Run the command to launch the browser
ProcessBuilder pb = new ProcessBuilder("\"/Program Files/Internet Explorer/iexplore.exe\"", url);
p = pb.start();
p.waitFor();
p.destroy();

---------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.