Avoid direct JSP access from client browser

 
Any files inside direct context folder can be accessible through client browser, but if same files if we place under WEB-INF folder then we can't access those files from client browser. So this way we can avoid direct call or access to specific JSP files from client browser. 
To access those JSP files we need configuration in web.xml (deployment descriptor) as similar to servlet. Lets see simple deployment descriptor for configuring JSP files along with sample JSP file.

JSP File (jspinside.jsp)


<html>
 <head>
  <title>Java Discover</title>
 </head>
 <body>
  <h1>Hello Java Discover :-)</h1>
 </body>
</html>




Deployment Descriptor (web.xml)


<web-app>
 <servlet>
   <servlet-name>JSPTest</servlet-name>
   <jsp-file>/WEB-INF/jspinside.jsp</jsp-file>   
 </servlet>
  
 <servlet-mapping>
   <servlet-name>JSPTest</servlet-name>
   <url-pattern>/jsptest.do</url-pattern>
 </servlet-mapping>
</web-app>




Folder Structure:


<context_name>
      -><WEB-INF>
             -><classes>
             -><lib>
             ->jspinside.jsp
             ->web.xml


Once complete deploy and test with below url

URL : http://localhost:8080/jsptest/jsptest.do


OUTPUT:



Insertion sort in Java

As like earlier tutorial Bubble sort, in this tutorial we will see about Insertion sort in Java with simple example. Unlike the other sorting algorithm insertion sort passes through the array only once.
Basically insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain. Below sample image will explain about how Insertion sort algorithm works.
Insertion sort example in Java
Now lets see simple insertion sort in java.


public class InsertionSort {

 public static void main(String[] args) {

  int values[] = { 5, 4, 8, 6, 9, 1, 7, 3, 2 };

  System.out.print("\nBefore sort : ");
  printArray(values);

  insertionSort(values);

  System.out.print("\nAfter sort : ");
  printArray(values);
 }

 private static void insertionSort(int[] array) {
  int i;
  for (int j = 1; j < array.length; j++) {
   int key = array[j];
   for (i = j - 1; (i >= 0) && (array[i] > key); i--) {
    array[i + 1] = array[i];
   }
   array[i + 1] = key;
  }
 }

 private static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
   System.out.print(array[i] + ", ");
  }
 }
}

OUTPUT:

Before sort : 5, 4, 8, 6, 9, 1, 7, 3, 2, 
After sort : 1, 2, 3, 4, 5, 6, 7, 8, 9, 




Bubble sort in Java

Bubble sort in java

Bubble sort is the simple sorting algorithm and same time has worst-case and average complexity. Bubble sort iterating down from first element to the last element in the array by comparing each pair of elements and switching elements if they meets our sorting condition. So lets see simple example in Java by using Bubble sort algorithm.



public class BubbleSort {

 public static void main(String[] args) {

  int values[] = { 5, 4, 8, 6, 9, 1, 7, 3, 2 };

  System.out.print("\nBefore sort : ");
  printArray(values);

  bubbleSort(values);

  System.out.print("\nAfter sort : ");
  printArray(values);
 }

 private static void bubbleSort(int[] array) {
  for (int i = 0; i < array.length - 1; i++) {
   for (int j = i + 1; j < array.length; j++) {
    if (array[i] > array[j]) {
     int tmp = array[i];
     array[i] = array[j];
     array[j] = tmp;
    }
   }
  }
 }

 private static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
   System.out.print(array[i] + ", ");
  }
 }
}


OUTPUT:


Before sort : 5, 4, 8, 6, 9, 1, 7, 3, 2, 
After sort : 1, 2, 3, 4, 5, 6, 7, 8, 9, 



Increase MySql database time wait

Viewing from dev.mysql.com site

In one of our earlier tutorials we have see about basic MySql commands and MySql connection sample code. In this tutorial we will see about increasing MySql default time wait of 8 hours.
For example in a rare condition we have an application which running socket connection between 2 server and communicates each other's data. But communication times are inconsistent and it can happen once in 1 hour or 2 hour once or even after 8 hours once. Lets assume in that case we having a open MySql database connection and whenever request comes it needs to preform its appropriate database activity. 
In that case if time wait goes more than 8 hours then MySql will disconnect all those database connections. So we need of more time wait from 8 hours to 10 or 15 hours or 1 days etc.,
So lets see how to change default MySql time wait option.

Before changing default time wait in MySql lets query for the current time wait which set in server.

mysql> show variables LIKE '%timeout%';
+----------------------------------+-------+
| Variable_name                    | Value |
+----------------------------------+-------+
| connect_timeout                 | 10    |
| delayed_insert_timeout       | 300   |
| innodb_lock_wait_timeout    | 50    |
| innodb_rollback_on_timeout | OFF   |
| interactive_timeout             | 28800 |
| net_read_timeout               | 30    |
| net_write_timeout              | 60    |
| slave_net_timeout              | 3600  |
| table_lock_wait_timeout     | 50    |
| wait_timeout                     | 28800 |
+----------------------------------+-------+

By above query we can get current MySql "wait_timeout" and "interactive_timeout" values as 28800(seconds equal to 8 hrs). Next we will see about changing those values from 8 hrs to 24 hrs. 

Under /etc edit my.cnf file with below details

# vi /etc/my.cnf 

[mysqld]
wait_timeout=86400
interactive_timeout=86400

NOTE: Suppose if my.cnf file not exist please create it. 

Once changed please restart MySql and check for the parameters has been updated or not.


mysql> show variables LIKE '%timeout%';

+------------------------------------+--------+
| Variable_name                      | Value  |
+------------------------------------+--------+
| connect_timeout                    | 10     | 
| delayed_insert_timeout          | 300    | 
| innodb_lock_wait_timeout       | 50     | 
| innodb_rollback_on_timeout    | OFF    | 
| interactive_timeout                | 86400  | 
| net_read_timeout                  | 30     | 
| net_write_timeout                 | 60     | 
| slave_net_timeout                 | 3600   | 
| table_lock_wait_timeout         | 50     | 
| wait_timeout                        | 86400  | 
+------------------------------------+--------+

From above table we can see timeout value got changed from 8 hrs to 24 hrs. 





Rich Dynamic Table using JQuery DataTable

 
When we see about recent Web Developments and role of HTML 5, AJAX, jQuery UI and other plugins into the world of Web made more and more changes which brings rich UI and sophisticated enhancements for the end users. At the same time we need to know that all end user machines should be with updates and latest software versions. 

We all may know that few months back Google has enhanced all its web products and asked all users to use browsers with latest version. And also by using AJAX we can get just piece of update information from server to client instead of requesting for complete web page. So it makes response as faster and less load to the web server. 

In recent web development world we can see lot and lot of plugins and tools to develop web application. As a plugin which I have came across is DataTable plugin which gives more functionality and rich UI for the developers with just few line of code. Lets assume few years back if we need to display a table in web page with 5 to 6 columns and with 1000 rows. So developer need to keep in mind like Pagination, each column sorting, search, records editing and finally giving rich UI and they need to write code for each functionality and need to integrate with those tables. 

But DataTable is one of the plugin which makes complete work into few integration steps. Now lets see simple example code as how to use DataTable. 

In below example if we see table we have created with id "javadiscover_table" and same id has been associated with dataTable in jQuery ready function. Thats it, remaining things are related to our custom requirement and we can add multiple properties like search feature enable/ disable, page counts, custom column sorting etc., Also here we have used jQuery UI for our rich table look.

You can download complete code and supporting js and css files in below link.

DataTable Example Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">

<html>

 <head>
  <link rel="stylesheet" href="dtable.css"/>
  <link rel="stylesheet" href="jquery-ui-1.8.4.custom.css"/>
  <script type="text/javascript" charset="utf-8" src="jquery.js"></script>
  <script type="text/javascript" charset="utf-8" src="jquery.dataTables.js"></script>
  
  <script type="text/javascript" charset="utf-8">   

   jQuery( document ).ready(function( jQuery ) {
     $('#javadiscover_table').dataTable( {
      "sDom": '<"top"iflp<"clear">>',
      "aaSorting": [[ 4, "desc" ]], // Column sorting
      "bJQueryUI": true

     } );    
   });
   
  </script>
  
 </head>

 <body>
  <table cellpadding='0' cellspacing='0' border='0' class='display' id='javadiscover_table'>
   <thead>
    <tr>
     <th>Source</th>
     <th>Destination</th>
     <th>Type</th>
     <th>IP Address</th>
     <th>Start Time</th>
     <th>End Time</th>
    </tr>
   </thead>
   <tfoot>
    <tr>
     <th>Source</th>
     <th>Destination</th>
     <th>Type</th>
     <th>IP Address</th>
     <th>Start Time</th>
     <th>End Time</th>
    </tr>
   </tfoot>
   <tbody>
    <tr>
     <td>Raj</td>
     <td>Sundar</td>
     <td>Audio Call</td>
     <td>10.70.54.81</td>
     <td>2013-10-29 09:10:57</td>
     <td>2013-10-29 09:11:14</td>
    </tr>
    <tr>
     <td>David</td>
     <td>Anand</td>
     <td>Audio Call</td>
     <td>10.70.54.83</td>
     <td>2013-10-29 09:46:34</td>
     <td>2013-10-29 09:46:59</td>
    </tr>
    <tr>
     <td>Rex</td>
     <td>Bill</td>
     <td>Video Call</td>
     <td>10.70.54.40</td>
     <td>2013-10-29 10:09:18</td>
     <td>2013-10-29 10:09:30</td>
    </tr>
    <tr>
    <td>Alex</td>
     <td>Gates</td>
     <td>Video Call</td>
     <td>10.70.53.123</td>
     <td>2013-10-29 10:38:14</td>
     <td>2013-10-29 10:38:17</td>
    </tr>
    <tr>
     <td>Steve</td>
     <td>Ronald</td>
     <td>Audio Call</td>
     <td>10.70.53.221</td>
     <td>2013-10-29 10:38:30</td>
     <td>2013-10-29 10:39:13</td>
    </tr>
    <tr>
     <td>Jobs</td>
     <td>Zen</td>
     <td>Video Call</td>
     <td>10.70.54.190</td>
     <td>2013-10-29 10:50:52</td>
     <td>2013-10-29 10:51:22</td>
    </tr>
    <tr>
     <td>Tim</td>
     <td>Tony</td>
     <td>Audio Call</td>
     <td>10.70.54.194</td>
     <td>2013-10-29 10:52:04</td>
     <td>2013-10-29 10:53:12</td>
    </tr>
   </tbody>
  </table>
 </body>
</html>




OUTPUT:





Java Interview Questions - 5

Java Interview Questions

In our past post we have seen lot of Java interview question like programming. In this post lets see few multiple choice questions in Java. Lets get some basic knowledge on various topics in Java 


1. Enumeration doesn't have which of the following method?

a) Hasnext()
b) Next()
c) Both a & b
d) Remove()


2. The servlet handles zero or more client’s requests through which method?

a) Init()
b) Destroy()
c) Paint()
d) Service()


3. Which is an Interface that extends Serializable Interface?
 
a) Package
b) Classes
c) Externalizable
d) Abstract

  
4. Which of the following is a software component that has been designed to be reusable in a variety of different environments?
 
a) Jar file
b) Java bean
c) JVM
d) JDK


5. Which of the following is the software component that enables java application to interact with the database?
 
a) ODBC
b) API
c) JDK
d) JDBC


6. Who control the java collector?
 
a) Class
b) Java interface
c) Applets
d) JVM


7. Which allows null key and values?
 
a) Hashtables
b) Hashkeys
c) Hash set
d) Hash map

 
8. Which of the following is the JDBC driver?
 
a) AWT driver
b) Network protocol driver
c) JVM driver
d) JAR driver


9. Which method returns -1 when it has reached the end of a file?
 
a) Write()
b) Read()
c) Lock()
d) All the above


10. Which class of interface is used, where there is a collection with no duplicates and you don’t care about order when you iterate through it?
 
a) Tree set
b) Enum set
c) Hashset
d) Linked hashset


11. Which concept of object oriented programming helps you group features of an object?
 
a) Packages
b) Inheritance
c) Data abstraction
d) Expert system


12. Write down the syntax to set null layout?

a) SetLayout(null)
b) Layout(null)
c) Layout(set null)
d) Null layout


13. What is the base class of all the classes?
 
a) Java.lang
b) Java.object
c) Java.lang.object
d) Java.lang.class



Public class test {
static class innerclass { 
Public static void innermethod() {
System.out.ptintln("static inner class!";


Public static void main(string args[]) { 
Test.innerclass.innermethod(); 


14. What will be the output of the above program?
 
a) Static inner class
b) 16
c) 14
d) None of the above


15. The <an applet> tag enables to pass an applet parameter in an applet using which of the following tag?
 
a) Alt
b) Code
c) Align
d) Param

 
16. Which frees the memory occupies by the unreachable objects during the java program by deleting these unreachable objects?
 
a) Interface
b) JVM
c) Source code
d) Garbage collector


17. Which of the following modifier makes that the programmer cannot change the value anymore?
 
a) Protected
b) Private
c) Public
d) Final

 
18. Which of the following is the correct syntax to create static variable?
 
a) Type static <var>
b) Static <identifier> type
c) Static[] type <identifier>
d) Static type <identifier>

  
19. Which is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource?
 
a) String ()
b) Finalize()
c) Math()
d) Final()


20. Which of the following code shows how to call the garbage collector?
 
a) Get.gc()
b) Garbage collector()
c) Runtime.gc()
d) System.gc()


21. Which encapsulates the state changes in the event source?
 
a) Event source
b) Event object
c) Event listener
d) Event management


22. Which is the default layout of jpanel?
 
a) Text layout
b) Label layout
c) Frame layout
d) Flow layout


23. Which is the relationship between the two classes?
 
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Association


24. Which is Set implementation to use with enum types?
 
a) Util.java.enum
b) Java.util.enumset
c) Enumset.util
d) Java.enum


25. Which method can be accessed by the classes within the same package or by the sub-classes of the class in any package?
 
a) Public
b) Protected
c) Private
d) Void


26. Which of the following view lets you navigate through the various files that make up an Eclipse project?
 
a) Problem view
b) Explorer view
c) Debug view
d) Java view


27. Which of the following is the king of bugs of java program?
 
a) Incorrect result
b) Program crashes
c) Both a & b
d) None of the above


28. Which of the following option Skips the highlighted statement and executes the next statement, and then suspends the thread?
 
a) Run to return
b) Step into
c) Step over
d) Resume

 
29. Which of the following element specified the element that can occur 1 or more times?
 
a) Element *
b) Element -
c) Element +
d) Element ?


30. Which is a control that the user can click to either check or uncheck?
 
a) Radio button
b) Check box
c) Drop down List
d) All the above



31. After you compile a Java program with no errors, you can run it by choosing which key combination?
 
a) Ctrl+f2
b) Ctrl+8
c) Ctrl+4
d) Ctrl+2


32. In Java, a _______ is a unit of code that can calculate and return a value?
 
a) Identifier
b) Method
c) Variable
d) Data



33. Which of the java compiler option specifies where to find input source files?
 
a) -d <directory>
b) -extdirs <dirs>
c) -classpath <path>
d) -sourcepath <path>

  
34. Which command is called the Java dis-assembler because it takes apart class files and tells you what’s inside them?
 
a) Javac
b) Java
c) Javap
d) Javah

  
35. Which is a name and value pair that’s written inside of the start tag for an element?
 
a) DTD
b) Script
c) Code
d) Attribute


36. Which is a read-only technique for processing XML that lets you read the elements of an XML document from a file and react to them as they come?
 
a) SAX
b) DOM
c) XML
d) HTML


37. _______spells out exactly what elements can appear in an XML document and in what order the elements can appear?
 
a) DOM
b) SAX
c) Validate form
d) DTD

  
38. Which of the following java command option displays the JRE version number, then stops?
 
a) -version
b) –verbose
c) –showversion
d) –server

 
39. Which of the following operator is used to compile all the files in a folder of java programs?
 
a) $
b) *
c) @
d) &


40. Which of the following performs calculations?
 
a) Expression statement
b) Variables
c) Keywords
d) Declaration statement



41. Which is a line in your program where you want the program to be suspended?
 
a) Breakpoint
b) Trace
c) Stepping
d) Debug



42. Which of the following is based on interfaces rather than classes?
 
a) XML
b) Javascript
c) ASP
d) DOM API


43. Which is the basic Eclipse desktop environment?
 
a) editor
b) workbench
c) applets
d) javadoc



44. The text editor you wish to create the text files that contain your Java programs is called ______?
 
a) Source file
b) Destination file
c) Application file
d) System file


45. What is the size of offline version of java?
 
a) 100 gb
b) 45 mb
c) 90 mb
d) 150 mb

 
46. In text pad which is a collection of files that you work on together?
 
a) Preference
b) Javadoc
c) Applets
d) Workspace


47. Which method of the slider control sets the tool-tip text that’s displayed if the user rests the mouse over the slider for a few moments?
 
a) void setPaintLabels
b) void setToolTipText
c) setOrientation
d) void setMinimum()


48. Which document format that can be understood by most word processing programs?
 
a) JRE
b) RTF
c) Bin
d) Demo

  
49. Which is a group of one or more statements that’s enclosed in braces?
 
a) White space
b) Variable
c) Keyword
d) Blocks


50. When debugging is executing program statements one at a time is called _____?
 
a) Threads
b) Program crashes
c) Bugs
d) Stepping