Saturday, June 18, 2016

Java 8 : Lambda Expression : Refactoring from external to internal iterator

Lambda Expression in Java 8

In this example , Refactoring from external to internal iterator by simple examples with printing values.


In order to write java code to  print array elements. in  previous versions of java.
lot of code need to write for an iterations. For example :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import java.util.Arrays;
import java.util.List;

public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  for (int i = 0; i < numbers.size(); i++) {
   System.out.println("Numbers:" + numbers.get(i));

  }
 }
}

Output:











We can may simplify the above code by using forEach Loop:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.util.Arrays;
import java.util.List;

public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*for (int i = 0; i < numbers.size(); i++) {
   System.out.println("Numbers:" + numbers.get(i));
  }*/
  for(int j : numbers){
   System.out.println(j);
  }
 }
}
Output:










The above 2 Ways are we called in Java External Iterator.

Java Divided iterators based on who controls the iterations process?
A fundamental task is deciding which party controls the iteration. the iterator or the client that uses the iterator. 
External Iterator:
When the client controls the iteration, the iterator is called an external iterator (Example: C++ and Java).
Internal Iterator :
when the iterator controls it, the iterator is an internal iterator (Example : Lisp and functional languages)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  numbers.forEach(new Consumer<Integer>() {
   @Override
   public void accept(Integer value) {
    System.out.println(value);
   }
  });
 }
}
Output:











The above one is better way to do the iteration at run time polymorphism.
But we are created unanimous inner class.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author nareshn
 *
 */
public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  /*
   * numbers.forEach(new Consumer<Integer>() {
   * 
   * @Override public void accept(Integer value) {
   * System.out.println(value); } });
   */
  numbers.forEach((Integer value) -> System.out.println(value));
 }

}
Output:











This one is called a simple Lambda function in it.
A Function should contains 4 parts: 1.Body , 2.Name, 3.Parameter List,  4.Return Type.

Here rather than accepting single abstract method , interface , now forEach method is more than willing to accept Lambda expression

In Java 1.0 , Thread Class rather than sending a new Runnable , now we can send a Lambda expression. it is very good move.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author nareshn
 *
 */
public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  /*
   * numbers.forEach(new Consumer<Integer>() {
   * 
   * @Override public void accept(Integer value) {
   * System.out.println(value); } });
   */
  /*numbers.forEach((Integer value) -> System.out.println(value));*/
  //no need to mention return type
  numbers.forEach(value -> System.out.println(value));
 }
}
Output:











Here we no need to mention return type.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author nareshn
 *
 */
public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  /*
   * numbers.forEach(new Consumer<Integer>() {
   * 
   * @Override public void accept(Integer value) {
   * System.out.println(value); } });
   */
  /* numbers.forEach((Integer value) -> System.out.println(value)); */
  // no need to mention return type
  /* numbers.forEach(value -> System.out.println(value)); */
  // perform some operations multiply, addition,substact or more for given
  // array values.
  numbers.forEach(value -> System.out.println(value * 2));
 }
}
Output:













Here we can not only a value, some mathematical operations to the array elements.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author nareshn
 *
 */
public class TestLamda {
 public static void main(String[] args) {
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
  /*
   * for (int i = 0; i < numbers.size(); i++) {
   * System.out.println("Numbers:" + numbers.get(i)); }
   */
  /*
   * for(int j : numbers){ System.out.println(j); }
   */
  /*
   * numbers.forEach(new Consumer<Integer>() {
   * 
   * @Override public void accept(Integer value) {
   * System.out.println(value); } });
   */
  /* numbers.forEach((Integer value) -> System.out.println(value)); */
  // no need to mention return type
  /* numbers.forEach(value -> System.out.println(value)); */
  // perform some operations multiply, addition,substact or more
  // for given
  // array values.
  /* numbers.forEach(value -> System.out.println(value * 2)); */

  // if we print direct value
  numbers.forEach(System.out::println);
 }
}
Output:

Tuesday, October 20, 2015

HTTP Status Codes for Java Web Applications

Error Code
Message
Details
100
Continue
Only a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request
101
Switching Protocols
The server switches protocol.
200
OK
The request is OK
201
Created
The request is complete, and a new resource is created
202
Accepted
The request is accepted for processing, but the processing is not complete.
203
Non-authoritative Information

204
No Content

205
Reset Content

206
Partial Content

300
Multiple Choices
A link list. The user can select a link and go to that location. Maximum five addresses 
301
Moved Permanently
The requested page has moved to a new url
302
Found
The requested page has moved temporarily to a new url
303
See Other
The requested page can be found under a different url
304
Not Modified

305
Use Proxy

306
Unused
This code was used in a previous version. It is no longer used, but the code is reserved.
307
Temporary Redirect
The requested page has moved temporarily to a new url.
400
Bad Request
The server did not understand the request
401
Unauthorized
The requested page needs a username and a password
402
Payment Required
You can not use this code yet
403
Forbidden
Access is forbidden to the requested page
404
Not Found
The server can not find the requested page.
405
Method Not Allowed
The method specified in the request is not allowed.
406
Not Acceptable
The server can only generate a response that is not accepted by the client.
407
Proxy Authentication Required
You must authenticate with a proxy server before this request can be served.
408
Request Timeout
The request took longer than the server was prepared to wait.
409
Conflict
The request could not be completed because of a conflict.
410
Gone
The requested page is no longer available.
411
Length Required
The "Content-Length" is not defined. The server will not accept the request without it.
412
Precondition Failed
The precondition given in the request evaluated to false by the server.
413
Request Entity Too Large
The server will not accept the request, because the request entity is too large.
414
Request-url Too Long
The server will not accept the request, because the url is too long. Occurs when you convert a "post" request to a "get" request with a long query information.
415
Unsupported Media Type
The server will not accept the request, because the media type is not supported.
417
Expectation Failed

500
Internal Server Error
The request was not completed. The server met an unexpected condition
501
Not Implemented
The request was not completed. The server did not support the functionality required.
502
Bad Gateway
The request was not completed. The server received an invalid response from the upstream server
503
Service Unavailable
The request was not completed. The server is temporarily overloading or down.
504
Gateway Timeout
The gateway has timed out.
505
HTTP Version Not Supported
The server does not support the "http protocol" version.


Wednesday, February 11, 2015

Applet Java code Database Connection display one table

DatabaseApplet.java



package abc;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;


import javax.swing.*;


public class Ab extends JApplet implements ActionListener
{
 static final long serialVersionUID = 1L;
 private JButton bttnForLogIn, bttnForTime,bttnForViewingTables;
 private String server_connect,user_name,user_pwd,oracle_driver;
 private Connection conn;
 private PreparedStatement pstmt;
 private ResultSet rs;
 
 

 private boolean getConnected=true;
 private JLabel lblTitle, lblDisplayTime; 
 private JTextArea textArea;
 public void init() {
  // TODO Auto-generated method stub

  setSize(800, 700);
  if(getConnected){
   setLayout(new BorderLayout());}

  add(new Ab(),BorderLayout.CENTER);



  System.out.println("Init");

 }


 public Ab()
 {
  if(getConnected){

   lblTitle = new JLabel("Oracle Database Table Data");
   lblTitle.setFont(new Font("Slab Serif", Font.BOLD, 18));
   lblTitle.setForeground(Color.red);
   lblTitle.setBounds(100, 11, 400, 60);

   oracle_driver = "oracle.jdbc.driver.OracleDriver";
   getConnected = true;
   JScrollPane scrollPane;
   getContentPane().add(scrollPane = new JScrollPane(this.textArea = new JTextArea()));
   textArea.setEditable(false);
   textArea.setBackground(Color.WHITE);
   scrollPane.setBounds(40,200, 200, 100);

   getContentPane().setBackground(Color.WHITE);
   bttnForLogIn = new JButton("Log In");
   bttnForLogIn.setBounds(21, 70, 150, 20);
   bttnForLogIn.addActionListener(this);





   bttnForTime = new JButton("Table:");
   bttnForTime.setBounds(51, 110, 150, 20);

   bttnForTime.addActionListener(this);


   lblDisplayTime = new JLabel("");
   lblDisplayTime.setFont(new Font("Times New Roman",30,12));
   lblDisplayTime.setForeground(Color.RED);
   lblDisplayTime.setBounds(180, 345, 400, 50);



   getContentPane().add(lblTitle);

   getContentPane().add(bttnForLogIn);  

   getContentPane().add(bttnForTime);
   //getContentPane().add(bttnForViewingTables);

   getContentPane().add(lblDisplayTime);


  }
 }

 public void setConnection(boolean getConnection)
 {
  getConnection=false;
 }

 public void buttonChanged(){

  bttnForLogIn.setText("Log Out");
 }
//main connection
 public void actionPerformed(ActionEvent e)
 {
  if(e.getSource() == bttnForLogIn)
  {
   user_name = "system";
   user_pwd = "manager";
   server_connect = "jdbc:oracle:thin:@localhost:1521:XE";
   if(getConnected)
   {
    if(testConnection() == 0)
    {

     JOptionPane.showMessageDialog(null, "Successful Completion");

     bttnForTime.setEnabled(true);

     buttonChanged();
     getConnected = false;
    } else
    {
     JOptionPane.showMessageDialog(null, "Oracle DB connection fail");
     bttnForTime.setEnabled(false);


    }
   } else 
   {
    try
    {
     conn.close();
    }
    catch(SQLException e1)
    {
     e1.printStackTrace();
    }
    bttnForLogIn.setText("Login");
    setConnection(getConnected);

    JOptionPane.showMessageDialog(null, "You have logged out! Have a good day!");
    
    
   }
  }else
   if(e.getSource() == bttnForTime)
    Table1();


   else {
    if(e.getSource() == bttnForViewingTables){

     Table1();
          
    }}




 }
 


 

 public int testConnection()
 {
  int flag = 0;
  try
  {
   Class.forName(oracle_driver);
  }
  catch(Exception e)
  {
   JOptionPane.showMessageDialog(null, e.getMessage());
  }
  try
  {
   conn = DriverManager.getConnection(server_connect, user_name, user_pwd);
  }
  catch(SQLException e)
  {
   JOptionPane.showMessageDialog(null, e.getMessage());
   flag = -1;
  }
  return flag;
 }
 

 private void Table1()  
 {
  try  
  {
   String stmtQuery = "select * from user_details";
   pstmt = conn.prepareStatement(stmtQuery);
   rs = pstmt.executeQuery();
   while(rs.next())
   {
    
    id=rs.getString(1);
     name = rs.getString(2);
     
     textArea.append("|"+id+" | "+name+"|"+"\n");
    // textArea.append("");
    
    System.out.println(name);
    
   }
   
   rs.close();
   pstmt.close();
  } catch(SQLException e2)
  {
   e2.printStackTrace();
  }
  
  
 }
 static String id;
 static String name;


 @Override
 public void destroy() {
  // TODO Auto-generated method stub
  System.out.println("destroy");
 }

 @Override
 public void start() {
  // TODO Auto-generated method stub
  System.out.println("Start");
 }

 @Override
 public void stop() {
  // TODO Auto-generated method stub
  if(!getConnected)
   System.out.println("Stop");

 }

} 

Run and execute ; change ur Oracle URL,Username, Password, Tablename