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........ :)

KVRsir Java Notes



The Java Material which are available here of KVR Sir class notes.The Java Material is Clear and good quality.The Java Material covered by all the classes of the KVR Sir .It is complete notes for Java learners.KVR sir is expert in the Subject.KVR sir also Explain well in the class.
KVRsirJavanotes

Procedure for Creating a Web Service at Client 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 Client-side in-detail.

Creating a Client:


    1. Create a new Project. Either a normal 'Java project' or 'Web project'.

   2. Now you should create the artifacts of the Webservice, which helps for communication between the service and the client.
        This step is not related to the step 1.

           For generating artifacts, create a new 'ClientGen Web Service Client'.

   3. It will have two options for WSDL location:

  •        Local
  •        Remote

      Local :   If you select local option, then you have to browse the WSDL file which is generated from the service.
      Remote :   If you select remote option, then you have to provide the WSDL url.


         Then, click on 'Validate WSDL'. After finish button is enabled, then choose finish.
         Else, if you click on 'next' leave the default settings and click on 'finish'... ;)

     4. Then, a Jar file is generated in a 'Web service project'. It doesn't need to be a project where service is running. Actually, service not at all needed to be run on our machine.


    5. Copy the Jar file and place it in our Java project.
        Else, add that jar file in our Java project libraries.

   6. Till here the complete set-up is ready with you for communication between client and the server.
        Create a normal class and test the client.

   
      In this class, for sending request / getting response :

  • Create a Service
  • Get a port, to which you are going to communicate in that service
  • Invoke the method at that particular port
  • Collect the response and process it.
    All the class files which are needed to communicate with the service are automatically generated (i.e. at step 2, 3)

The request and response are sent and received in SOAP format. You need not to convert / write anything for SOAP. Automatically, those requests /  responses are converted.


Monday 23 July 2012

Basic Audio Player Using Java

Hi Friends,

I want to show one of the easy and interesting application using JMF.
Here is the tutorial to build an audio player using this Java Media FrameWork.

First of all, set up the environment by downloading and configuring the JMF in your system from here.

Try this simple example :



package jmf_test1; import java.io.File; import javax.media.Manager; import javax.media.Player; /** * @author naveen.k */ public class Main { static Player audioPlayer = null; public static void main(String[] args) { try { Manager.createRealizedPlayer(new File("D:\\Sample.mp3").toURL()).start(); } catch (Exception ex) { ex.printStackTrace(); } } }

Here, you are done... :)   You can able to listen to song playing.... :-)


Lets try some thing little more: 


  • Take an JFrame Java Application.
  • Create a Panel on existing JFrame.
  • Create three buttons for Play, Pause and Stop.
  • (see into image for your better understanding)





  • Add Listeners for three of the buttons:

  • Let you add the following code for the respective listeners 

  1. Play:          audioPlayer.start();
  2. Pause:         audioPlayer.stop();
  3. Stop:   audioPlayer.stop();  //stop and reset to 1st position                                                                                    audioPlayer.setMediaTime(new Time(0.0));
  • Run the application.


Then a Simple Basic Audio Player is done.......... :D


The following is my code for your reference:
(Don't be scared with the code. Very few lines code is written by me....
Total code is auto-generated.... :-)
)


package jmf_test1;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.media.CannotRealizeException;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.Time;

/**
 * @author naveen.k
 */

public class AudioPlayerTest extends javax.swing.JFrame {

    Player audioPlayer = null;
    String audioPath = "";

    /** Creates new form AudioPlayerTest */
    public AudioPlayerTest() {
        initComponents();
        audioPath = "D:\\sample.mp3";
        initAudioPlayer(audioPath);       
    }

    private void initAudioPlayer(String pathname) {
        try {
            URL url = new File(pathname).toURL();
            audioPlayer = Manager.createRealizedPlayer(url);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (NoPlayerException ex) {
            ex.printStackTrace();
        } catch (CannotRealizeException ex) {
            ex.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // 
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        PlayButton = new javax.swing.JButton();
        PauseButton = new javax.swing.JButton();
        StopButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        PlayButton.setText("Play");
        PlayButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PlayButtonActionPerformed(evt);
            }
        });

        PauseButton.setText("Pause");
        PauseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PauseButtonActionPerformed(evt);
            }
        });

        StopButton.setText("Stop");
        StopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StopButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
               .addComponent(PlayButton)
                .addGap(27, 27, 27)
                .addComponent(PauseButton)
                .addGap(18, 18, 18)
                .addComponent(StopButton)
                .addContainerGap(36, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(PlayButton)
                    .addComponent(PauseButton)
                    .addComponent(StopButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(69, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// 

    private void PlayButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        audioPlayer.start();
    }

    private void PauseButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        audioPlayer.stop();
    }

    private void StopButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        audioPlayer.stop();
        audioPlayer.setMediaTime(new Time(0.0));
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AudioPlayerTest().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton PauseButton;
    private javax.swing.JButton PlayButton;
    private javax.swing.JButton StopButton;
    private javax.swing.JPanel mainPanel;
    // End of variables declaration
}



There are much more interesting things that you can do with JMF framework.....
Here is the API for JMF...
Explore more and enjoy java.................










Saturday 21 July 2012

Java Mail API Tutorial

Hi Friends.....

I would like to share simple examples on using of the Java Mail Api. I think it will aid to develop very interesting and useful applications.

First of all, we should download mail.jar and activation.jar file and place it in the classpath.

I will provide you three examples that shows overview of usage of this API:

  • Sending a simple Text message.
  • Sending email with Attachments.
  • Sending HTML content Message
I. Sending a Simple Text Email :


package com.navin.emailapp;


import java.util.Properties;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
 * @author naveen.k
 */
public class EmailApplication {


    public static void main(String[] args) {
        final String fromEmailId = "sender_emailid@domain.com";
        final String password = "sender_password";
        String host = "smtp_host";
        String portNumber = "smtp_port_number";


        String toEmailId = "receiver_emailid@domain.com";
        String subject = "Testing email";
        String message = "Hi... thist is my first mail                  application";


        Properties pro=new Properties();
        pro.put("mail.smtp.user", fromEmailId);
        pro.put("mail.smtp.host", host);
        pro.put("mail.smtp.port", portNumber);
        pro.put("mail.smtp.starttls.enable", "true");
        pro.put("mail.smtp.auth", "true");
        pro.put("mail.smtp.socketfactory.port", portNumber);
        pro.put("mail.smtp.socketfactory.class","javax.net.ssl.SSLSocketFactory");
        pro.put("mail.smtp.socketfactory.callback", "false");
        try
        {
            Session session=Session.getInstance(pro, null);
            session.setDebug(true);


            MimeMessage msg=new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(fromEmailId));
            msg.addRecipient(RecipientType.TO, new InternetAddress(toEmailId));
            msg.saveChanges();


            Transport trans=session.getTransport("smtp");
            trans.connect(host, fromEmailId, password);
            trans.send(msg, msg.getAllRecipients());
            trans.close();
        }
        catch(Exception e ){e.printStackTrace(); }
    }


}

II. Sending email with Attachments :


package com.navin.emailapp;


import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


/**
 * @author naveen.k
 */
public class EmailApplication2 {


    public static void main(String[] args) {


        String fromEmailId = "sender_emailid@domain.com", password = "sender_password",
                host = "smtp_host", port = "smtp_port_number",
                toEmailId = "receiver_emailid@domain.com",
                subject = "Testing attachment email",
                message = "This is my second mail application",
                filename = "d:/test.txt"; 
        
        // if you would like to use the above mention properties, those are applicable here also
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        try {
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(true);


            MimeMessage msg = new MimeMessage(session);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(fromEmailId));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmailId));

            // create and fill first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(message);

            // create second message part
            MimeBodyPart mbp2 = new MimeBodyPart();


            // attach the file to message
            FileDataSource fds = new FileDataSource(filename);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());


            //create multipart and add contents to it
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);


            //add multipart to message
            msg.setContent(mp);


            msg.setSentDate(new Date());
            msg.saveChanges();

            Transport transport = session.getTransport("smtp");
            transport.connect(host, fromEmailId, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception ex) {ex.printStackTrace();}
    }
}


III. Sending HTML content Messages:


 This example is same as the above examples except setting "javax.mail.internet.MimeMessage" content type to "text/html".


The snippet is provided below, by skipping the entire code to avoid confusion and for making the major part clear..... :)

/**.....  the code is totally same as I example .....**/
           
            MimeMessage msg=new MimeMessage(session);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(fromEmailId));
            msg.addRecipient(RecipientType.TO, new InternetAddress(toEmailId));
           
            msg.setContent("<h1>Test HTML content </h1>","text/html");
            msg.saveChanges();

/**.....  the code is totally same as I example .....**/

           


You can find the gmail setting at https://support.google.com/mail/bin/answer.py?hl=en&answer=13287


Download my sample application jar here. Please, maintain the same folder structure and run the 'NaveenEmailApp.jar'.

Session Problem in Google Chrome




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


  I would like to share one of my experience with Google Chrome.


In one of my project, the application was working fine in Internet Explorer and Mozilla Firefox with no issues. But it was not working fine in Chrome.


For many days the problem was existing. The actual problem we faced in it was, whenever the user is logging into the application a new session was being created instead of maintaining the same session. This was happening only in Chrome. Thus, the previous session is lost and we used to displayed the 'Session Expiry' page.


Another major thing in it was:
 The application was working fine in 'http' environment, but the problem was faced only in 'https' environment.  
It vexed us for long.............    




After many analysis, we came across the solution. The solution was very simple, silly and felt as not at all related to the problem.


The reason behind it is:


When the user is logging into the application, the details were captured and stored in a session. For the next  request, the session-id was different from the first session-id (More-over we checked even session.isNew() also, its was giving true). Thus, something was going wrong on the transition of the requests. That too in Chrome only.


On next step, we thought of the webserver (we used Apache webserver) and did many trails on the webserver configurations. But there was no use.

Later, we checked each of request's flow using Burp suite tool. In this tool, we observed the request for 'favicon'.
 In Mozilla and IE there was no effect of this 'favicon', but where as the Chrome alone is demanding for a 'favicon' (This is the unusual behaviour of the Chrome). In our application we are not using this icon.
If there is no 'favicon' in our application and if you handle the 404 status code, it will be executed.
This the reason, for the request after logging into our application a new session is created. Thus, we got a new session and data of user is lost. Hence, because of no data we displayed 'Session Expiry' page.
The problem is resolved by placing the 'favicon' at the root level of the application.


Lesson i learnt by this experience is:
  never ignore to place favicon in your application especially in https environment.... :)




I would like to share this experience hoping that some day or some time it may help somebodies precious time....

Tuesday 17 July 2012

SOAP BASED WEBSERVICES - OVERVIEW

WEBSERVICE (SOURCE WIKIPEDIA):

 A Web service is a method of communication between two electronic devices over the Web (Internet).

 The W3C defines a "Web service" as "a software system designed to support interoperable machine-to-machine interaction over a network".


 There are two major categories of web services:
  •  SOAP Web Service
  •  RESTful Web Service

 SOAP Web Service:
Simple Object Access Protocol (SOAP) is a standard protocol specification for message exchange based on XML. Communication between the web service and client happens using XML messages. SOAP defines the rules for communication like what are all the tags that should be used in XML and their meaning. 

Representational state transfer (REST):
REST attempts to describe architectures that use HTTP or similar protocols by constraining the interface to a set of well-known, standard operations (like GET, POST, PUT, DELETE for HTTP). Here, the focus is on interacting with stateless resources, rather than messages or operations. Clean URLs are tightly associated with the REST concept.

The information in this blog is only for the begginers to start-up with webservices. Recommended to explore more on each of this concepts. Lets continue with the SOAP web services


ARCHITECTURE:

Webservices follows SOA architecture

Description:

  • Service provider will implement a service and makes it ready to serve all the client requests.
  • This service is well described by the WSDL.
  • To make WSDL available to client, using UDDI it is placed in a logically centralized directory of services. The registry provides a central place where developers can publish new services or find existing ones. (This part can be skipped by providing the wsdl file directly to the clients)
  • By using this wsdl file, client will generate the artifacts and starts communicating with service using SOAP messages.



The Major Web Services Technologies:
  • Simple Object Access Protocol (SOAP)
  • Web Service Description Language (WSDL)
  • Universal Description, Discovery, and Integration (UDDI)



 UDDI:
UDDI is an XML-based standard for describing, publishing, and finding Web services.
UDDI stands for Universal Description, Discovery and Integration.
UDDI is a specification for a distributed registry of Web services.
UDDI is platform independent, open framework.
UDDI uses WSDL to describe interfaces to web services.
UDDI is seen with SOAP and WSDL as one of the three foundation standards of web services.
UDDI is an open industry initiative enabling businesses to discover each other and define how they interact over the Internet.

WSDL:
One major component of a web service is Web Services Description Language (WSDL).
WSDL is an xml file that describes the web service technically in a machine readable format.
That is, using this WSDL file we can understand things like, Port / Endpoint – URL of the web service (using which we should access it) Input message format Output message format Security protocol that needs to be followed (like https) Which protocol the web service uses WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'

The structure of WSDL looks as:
<definitions>
   <types>
        .... data type definitions ....
   </types>
   <messages>
       .... definition of the data being communicated ....
   </messages>
   <portTypes>
       .... set of operations ....
   </portTypes>
   <bindings>
        .... protocol and data format specification ....
    </bindings>
</definitions>

SOAP: 
SOAP is an XML-based protocol for exchanging information between computers.
SOAP is a communication protocol SOAP is for communication between applications
SOAP is a format for sending messages
SOAP is designed to communicate via Internet
SOAP is platform independent
SOAP is language independent
SOAP is simple and extensible
SOAP allows you to get around firewalls
SOAP will be developed as a W3C standard

example soap message:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header> </soap:Header>
<soap:Body>
<m:GetStockPrice xmlns:m="http://www.example.org/stock">
<m:StockName>IBM</m:StockName>
 </m:GetStockPrice>
</soap:Body>
</soap:Envelope>


Refer next post for SOAP based Webservices example......

SOAP based Webservices example





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




Previously we saw Overview of SOAP based Webservices. Now lets move to the Example of SOAP based webservices.


In the development of a webservice, we have two parts.
One is developing a service and another is using the developed service (i.e., creating a client for that service).

I. SERVER SIDE:

Lets Create a service named 'SayHello.java'
  • For making 'SayHello' class as a web service annotate the class with '@WebService'
  • Create a 'hello()' method in that class. Annotate it with '@WebMethod' (attributes in it are optional)
  • If needed, annotate the method params with '@WebParams'. Its is also optional.
  • If you want to return the User-defined Objects as the response, you can create and return them as same as in normal procedure.
  • For these User-defined Objects, the Complex Types are automatically generated in the 'xsd' file.
  • This 'xsd' is used in WSDL file, which describes about the service.
The Sample code for the Service is :


com.navin.SayHello.java


package com.navin;

import javax.jws.WebMethod;

import javax.jws.WebParam;
import javax.jws.WebService;
/**
 * @author navin.k
 */
@WebService()
public class SayHello {
    /**
     * Web service operation
     */
    @WebMethod(operationName = "hello")
    public HelloResponse hello(@WebParam(name = "User")
    String user) {
        HelloResponse response = new HelloResponse();
        response.setMessage("Hello " + user);
        return response;
    }
}

com.navin.HelloResponse.java  (user-defined response type for service)

package com.navin;
/**
 * @author navin.k
 */
public class HelloResponse {
    String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}


After Deploying this service, test the application by running the below url:
     url:        http://hostname:port/context-name/webservice-name?wsdl

If WSDL is generated then the service is deployed successful and running fine.



II.  CLIENT SIDE:


Lets check the above created service with a Client.

  • Create a normal Java class
  • Create a Service for the Web Service. (generally appends 'Service' for the web service name)
  • Get the port on the service
  • Call the method on the port by passing all the required parameters for the service 
  • Receive and process the response from the service
The Sample code for the client is:

package com.navin.client;
/**
 * @author navin.k
 */
public class TestClient {
    public static void main(String[] args) {
        HelloResponse response = SayHelloService().getSayHelloPort().hello("JAVA");
        String message = response.getMessage();
        System.out.println("Service response : " + message);
    }
}

The output for the above client is :

Service response : Hello JAVA


Now you are successfully able to run the Web Service........ 

 For more clear steps on creation of Webservice please look into this blog....


To know more about procedure for Creating a Web Service at Server Side check here


To know more about procedure for Creating a Web Service at Client Side check here