Saturday, 9 March 2013

Singleton Design Pattern

Hi Friends....!!
Hi Friends....!!!                             





I would like to share some of my views about Singleton Design Pattern.


For any java class if we are allowed to create any one object, such type of class is called as ‘Singleton class’.

Example:
Runtime, ActionServlet(Struts 1.x), BussinessDeligate(EJB), ServiceLocation(EJB),…., etc.

Singleton Design pattern is mainly used to restrict the creation of instances of a class to one. This is the most common and easiest design pattern in java.

For a Singleton class,
  • There should be only one instance allowed for a class
  • That single instance should able allow global point of access

The Only Child.... :p


Example for Singleton class:

We can create our own Singleton class by providing

public class Singleton{
    private static Singleton objSingleton;
    private Singleton(){
    }
    
    // Factory Method
    public  static Singleton getInstance(){
        if(objSingleton == null)
            objSingleton = new Singleton();
        return objSingleton;
    }
    // override clone method
    public  Object clone(){
        return this;
    }
}

To be Noted In Above Singleton Class :
  • Constructor of the class is made private to restrict the direct instantiation of the object.
  • Factory method is created to get an instance of an object
  • Clone method is overridden to restrict creation of copies of the object.




Preventing Singleton Class from Multi-Threading Problems:

If you needed to prevent this Singleton from multi threading problems, it is advisable to mark the factory method as synchronized.
The snippet is provide below:
public static synchronized Singleton getInstance(){
    if(objSingleton == null)
        objSingleton = new Singleton();
    return objSingleton;
}


Wednesday, 6 March 2013

Highlights of Java Programming Language Changes in Java SE 7



1. Binary Literals
2. Strings in switch Statements
3. Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
4. Underscores in Numeric Literals
5. The try-with-resources Statement
6. Type Inference for Generic Instance Creation
7. Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods





1. Binary Literals
In Java SE 7, the integral types (byte, short, int, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. The following examples show binary literals:

// An 8-bit 'byte' value:
byte aByte = (byte)0b00100001;
// A 16-bit 'short' value:
short aShort = (short)0b1010000101000101;
// Some 32-bit 'int' values:
int anInt1 = 0b10100001010001011010000101000101;
int anInt2 = 0b101;
int anInt3 = 0B101; // The B can be upper or lower case.
// A 64-bit 'long' value. Note the "L" suffix:
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;


2. Strings in switch Statements
In the JDK 7 release, you can use a String object in the expression of a switch statement:

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}
The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.



3. Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
a. Handling More Than One Type of Exception
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.


b. Rethrowing Exceptions with More Inclusive Type Checking
The Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.

Consider the following example:

  static class FirstException extends Exception { }
  static class SecondException extends Exception { }

  public void rethrowException(String exceptionName) throws Exception {
    try {
      if (exceptionName.equals("First")) {
        throw new FirstException();
      } else {
        throw new SecondException();
      }
    } catch (Exception e) {
      throw e;
    }
  }
This examples's try block could throw either FirstException or SecondException. Suppose you want to specify these exception types in the throws clause of the rethrowException method declaration. In releases prior to Java SE 7, you cannot do so. Because the exception parameter of the catch clause, e, is type Exception, and the catch block rethrows the exception parameter e, you can only specify the exception type Exception in the throws clause of the rethrowException method declaration.

However, in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration. The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException:

  public void rethrowException(String exceptionName)
  throws FirstException, SecondException {
    try {
      // ...
    }
    catch (Exception e) {
      throw e;
    }
  }
This analysis is disabled if the catch parameter is assigned to another value in the catch block. However, if the catch parameter is assigned to another value, you must specify the exception type Exception in the throws clause of the method declaration.

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

The try block is able to throw it.
There are no other preceding catch blocks that can handle it.
It is a subtype or supertype of one of the catch clause's exception parameters.
The Java SE 7 compiler allows you to specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration because you can rethrow an exception that is a supertype of any of the types declared in the throws.

In releases prior to Java SE 7, you cannot throw an exception that is a supertype of one of the catch clause's exception parameters. A compiler from a release prior to Java SE 7 generates the error, "unreported exception Exception; must be caught or declared to be thrown" at the statement throw e. The compiler checks if the type of the exception thrown is assignable to any of the types declared in the throws clause of the rethrowException method declaration. However, the type of the catch parameter e is Exception, which is a supertype, not a subtype, of FirstException andSecondException.


4. Underscores in Numeric Literals
In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.

For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator.

The following example shows other ways you can use the underscore in numeric literals:

long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi =  3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;
You can place underscores only between digits; you cannot place underscores in the following places:

At the beginning or end of a number
Adjacent to a decimal point in a floating point literal
Prior to an F or L suffix
In positions where a string of digits is expected



5. The try-with-resources Statement
The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}
In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
    return br.readLine();
  } finally {
    if (br != null) br.close();
  }
}

NOTE:
If the try-with-resources statement contains two declarations that are separated by a semicolon, When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of corresponding objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.


6. Type Inference for Generic Instance Creation
You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.

For example, consider the following variable declaration:

Map<String, List<String>> myMap = new HashMap<String, List<String>>();
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):

Map<String, List<String>> myMap = new HashMap<>();
Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map<String, List<String>> type:

Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning
Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

List<String> list = new ArrayList<>();
list.add("A");

  // The following statement should fail since addAll expects
  // Collection<? extends String>

list.addAll(new ArrayList<>());
Note that the diamond often works in method calls; however, it is suggested that you use the diamond primarily for variable declarations.

In comparison, the following example compiles:

// The following statements compile:

List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);

Saturday, 5 January 2013

Changing Tomcat Default Port

Generally, by default Tomcat runs on 8080 port. There are many chances of getting conflicts on port numbers for running programs. So, sometimes we need to change the port number of Tomcat.


Steps to change the port number for Tomcat:

1. Locate "%TOMCAT_FOLDER%/conf/server.xml"

2. Find the below code in the server.xml file


 
    


or


    


3. Change the Connector port=”8080" to any other port number.

    Ex:




This makes to run Tomcat on port number 9090.

4. Save the file and Restart the server.

What Is Tomcat Default Administrator Password ?

Problem:

Is there default administrator Username and Password for Tomcat?

Solution:

You can find the roles and credentials of roles in `tomcat-users.xml`.

By default the Tomcat doesn't enable admin or manager access.

Below is the code:








So, by default no roles are created by Tomcat.

You can create the roles manually. Below is the sample code to enable admin and manager roles.




  
  
  



Paste this code in "%TOMCAT_FOLDER%/conf/tomcat-users.xml" and restart the server. Now, you can access Tomcat admin or manager with username="admin" and password="admin".




Monday, 5 November 2012

Calling IPV6 Address in Browser

Q: Now, I know how to configure IPV6 environment. How to call / form a IPV6 URL in browser?

A: As IPV6 is extended to Hexa from Octa , it contains of literals (a to f). Here we can see the IPV6 support browsers, that can handle these literals in URL.

For command line or browser's IPV6 addresses, we should specify the URL in enclosed square brackets.
 Ex:    [fec0::2]

If we setup the IPV6 environment in your local machine, we may have URL as below fe80::10a1:3c91:f19c:17aa%20

If you want to access the IPV6 URL, the percent character (%) in the IPv6 literal address must be percent escaped when present in the URI.
For example, the scope ID  fe80::10a1:3c91:f19c:17aa%20, must appear in the URI as http://[ fe80::10a1:3c91:f19c:17aa%2520]/, where %25 is the hex encoded percent character (%).

In general, we can also use the URL till percent character (%).
Ex:  http://[fe80::10a1:3c91:f19c:17aa]/

Remaining part of the URL is same as IPV4 URL structure. Sample URL is given below.
   http://[fe80::10a1:3c91:f19c:17aa]:8080/index.html


Usage of DNS is preferred for resolving all IPv6 host names....

Enabling IPV6 environment in Windows


Q: How to enable IPV6 environment in Windows Operating System?

A:   We can enable the IPV6 environment along with in IPV4 environment.

In Windows Vista and Windows7, IPV6 is enabled by default. But for Window XP user has to configure or enable the IPV6 protocol to add support for the current operating system.

Preferably, test whether IPV6 is already enabled or not:
1. Press windows+R , type cmd and hit enter.
2. Type ipconfig.
It shows  IPV6 if enabled.

 There are 2 Very easy ways of enabling IPV6 environment in Windows:

Method 1:
1. Open command prompt (Press windows+R , type cmd and hit enter)
2. Enter command ipv6 install

Method 2:
1. Open Network Settings option of Control Panel
2. Right-click on the appropriate network adapter and click Properties.
3. Click install.
4. In the Select Network Component Type dialog box, click Protocol, and then click Add.
5. In the Select Network Protocol dialog box, click Microsoft TCP/IP version 6, and then click OK.
6. Click Close to save changes to your network connection.Installs the selected protocol.


After installation is completed, check whether IPV6 is installed or not as mentioned above.

Wednesday, 25 July 2012

Procedure for Creating a Web Service at Server Side



Hi Friends..........

Previously we saw Overview of SOAP based Webservices and how to write the Web Service example.


I am sharing you how to develop a SOAP based webservice in WEBLOGIC 10.3  workshop and WEBLOGIC server for deployment.
(The procedure / structure of developing or using Webservices will be identical in many of the IDEs)


Lets see step by step procedure for developing a web Service at Server-side in-detail.


Creating of a Service :
     1. Create a new Project. 
                         Select of type 'Web Service project' and Click Next.



       2. Provide the Project Name.
           In Configurations, select 'Annotated Web Services Facets JAX-WS (Recommended)' and leave
                remaining as default only.
            Click 'Finish'.     

                                   
   
       3. In the new project, create a package.
            On new package, create a new 'Weblogic Webservice' and give the Class name.
            Then click finish.
            Else you can create a new normal class and later you can add additional very few annotations, which
             is very simple.




       4. Write the service code in the classes

      Till here, you are ready with your service......
       Lets see how to deploy and check the services.....



  • Deploying and the Service :
      5. Right click on the project -->  'Run As'.
          Then click on 'Run on Server'. If you not configured the server, then you should configure the server 
           and click on Finish by leaving all the default settings.


     6. Now your service is got ready.......
         For checking whether its working or not, hit the url.
                url:        http://hostname:port/context-name/webservice-name?wsdl
         For checking xsd file, hit the below url.

                url:        http://hostname:port/context-name/webservice-name?xsd=1

         Sometimes, you need to append 'Service' for webservice-name for checking the wsdl or xsd file.

Till here now you are successfully completed with your service and its working fine........ :)