Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Tuesday, May 22, 2012

Minimum Jars to load a Spring context

I was looking for the minimum set of jars required to load a Spring Context but could not find one on the internet. So am listing them out here:
  1. org.springframework.core
  2. org.springframework.web
  3. org.springframework.context
  4. org.springframework.context.support
  5. org.springframework.beans
  6. org.springframework.asm
  7. commons-logging

Thursday, March 15, 2012

Helloworld web service in Eclipse using Tomcat, Apache CXF and Spring

I have just started working on Spring and was required to expose an existing application as a web service. So to get started I needed to learn about how to create one in Eclipse and deploy it on tomcat. Sadly spending hours and Google and downloading dozens of samples, I was unable to get them work on Eclipse. Most worked using Maven but I wanted to build one in Eclipse from scratch. So lets get started.

Requirements:

To get started:
  1. In Eclipse : Create a New 'Dynamic Web Project'. Name it as 'HelloWS' and click Finish.


  2. Go to Build Path: Configure Build Path.
    1. Under the 'Source' tab: Change the 'Default Output Folder' from 'HelloWS/build/classes' to 'HelloWS/WebContent/WEB-INF/classes'.

    2. Under Libraries tab: Add Spring and Apache CXF libraries.
    3. Under 'Order and Export' tab: Check the chekboxes next to these libraries
    4. Under 'Deployment Assembly' (just above 'Java Build Path' in the 'Properties of HelloWS'  windows) : Click 'Add' :: Java Build Path Entries and select these 2 libraries so that they can be deployed to the Tomcat App Server.
  3. With the configuration done, lets write some code.
  4. Create an interface 'HelloService' under package 'my.service'. Annotate the class with @WebService . Add a simple sayHello method. So it looks like:

    package my.service;

    import javax.jws.WebService;

    @WebService
    public interface HelloService {

        public String sayHello(String name);
       
    }
  5. Next create the implementer class 'HelloServiceImpl' which implements 'HelloService'. Annotate the class with @Webservice and parameter endpointInterface = "my.service.HelloService" which defines the Contract for this Endpoint. So it looks like:

    package my.service;

    import javax.jws.WebService;

    @WebService(endpointInterface = "my.service.HelloService")
    public class HelloServiceImpl implements HelloService {
       
        @Override
        public String sayHello(String name) {
            return "Hello " + name + " !!";
        }
    }
  6. Coding complete. Now lets configure the Spring context which will invoke this service we just created.
  7. Update 'web.xml' under WebContent/WEB-INF folder with the following xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="...">

        <display-name>My Webservice</display-name>

        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>

        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:my/service/application-context.xml</param-value>
        </context-param>

        <servlet>
            <servlet-name>CXFServlet</servlet-name>
            <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>CXFServlet</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
      
    </web-app>

    Read this configuration file bottom up. First it instructs all requests matching the URLpattern /* (that is everything to be handled by a servlet named ' CXFServlet' which is defined just above. This is a Apache CXFservlet. Above it we provide the configuration file location which will configure this servlet (details below). Above this, it specifies the Spring Listener class which will listen to all these Http requests.
  8. Now create a 'application-context.xml' file at the same level as the 2 java files coded above with the following xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:jaxws="http://cxf.apache.org/jaxws"
        xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

        <import resource="classpath:META-INF/cxf/cxf.xml" />
        <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
        <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

        <!-- Spring manage ServiceBean -->
        <bean id="myServ" class="my.service.HelloServiceImpl" />

        <!-- JAX-WS Service Endpoint -->
        <jaxws:endpoint id="myService" implementor="#myServ"
            address="/myService" />

    </beans>

    In here, again reading from below, first we define an endpoint named 'myService which is implemented by the bean 'myServ' whose class is 'my.service.HelloServiceImpl' and its binded to the address '/myService'
  9. And we are done with coding.
  10. To deploy it, create a 'Tomcat 7 Server' under Servers in Eclipse and deploy the 'HelloWS' module to it using 'Add and Remove'
  11. Start the server
  12. To check, open your browser and type in : http://localhost:8080/HelloWS and it should open up the default page. You can also get the wsdl at : http://localhost:8080/HelloWS/myService?wsdl
  13. You can use SOAPUI to test your service too.
  14. And in 10 minutes your service is ready :)

Wednesday, February 3, 2010

Calling Hello World Webservice from Oracle 10 database



I got a problem where I was required to invoke a web service from Oracle database itself. From the net, I got multiple samples of code to do so using the UTL_HTTP package. The problem none worked for me. So I started from scratch :

  1. Created a HelloWorld web service in .NET 3.5 (VS 2008 SP1).

  2. Checked the service using the Internet Explorer browser. You should see a page similar to one below when you access the url http://localhost/myWeb/testws/Service.asmx?op=HelloWorld (the location of your service may be different):

  3. After lot of time spent on the internet, I found Oracle uses SOAP 1.1 to make web service calls. So look specifically in to the SOAP 1.1 Request format displayed on the browser.


  4. So now lets come to code:

    declare
    http_req utl_http.req;
    http_resp utl_http.resp;
    request_env varchar2(32767);
    response_env varchar2(32767);
    begin

    request_env:='<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
    <HelloWorld xmlns="http://tempuri.org/" />
    </soap:Body>
    </soap:Envelope>'

    dbms_output.put_line('Length of Request:' length(request_env));
    dbms_output.put_line ('Request: ' request_env);

    http_req := utl_http.begin_request('http://<your_url>/myWeb/testws/Service.asmx', 'POST', 'HTTP/1.1');
    utl_http.set_header(http_req, 'User-Agent', 'Mozilla/4.0');
    utl_http.set_header(http_req, 'Content-Type', 'text/xml');
    utl_http.set_header(http_req, 'Content-Length', length(request_env));
    utl_http.set_header(http_req, 'SOAPAction', '"http://tempuri.org/HelloWorld"');
    utl_http.write_text(http_req, request_env);

    http_resp := utl_http.get_response(http_req);
    utl_http.read_text(http_resp, response_env);
    utl_http.end_response(http_resp);

    dbms_output.put_line('Response Received');
    dbms_output.put_line('--------------------------');
    dbms_output.put_line ( 'Status code: ' http_resp.status_code );
    dbms_output.put_line ( 'Reason phrase: ' http_resp.reason_phrase );

    dbms_output.put_line('Response: ');
    dbms_output.put_line(response_env);

    EXCEPTION WHEN UTL_HTTP.end_of_body THEN
    utl_http.end_response(http_resp);
    END;


  5. Lets got through the code step by step:


  6. Declare some variables:

    declare
    http_req utl_http.req;
    http_resp utl_http.resp;
    request_env varchar2(32767);
    response_env varchar2(32767);
    begin


  7. Create the SOAP request. It should exactly match what is displayed on the browser. Currenly I am not passing any input parameter to the service but if you need to, just copy paste the SOAP request from the browser and replace the placeholders mentioned in there with actual values.

    request_env:='<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
    <HelloWorld xmlns="http://tempuri.org/" />
    </soap:Body>
    </soap:Envelope>';
    dbms_output.put_line('Length of Request:' length(request_env));
    dbms_output.put_line ('Request: ' request_env);

    Just some debug statements at end to check all is set correctly.


  8. Set the HTTP Request Parameters. The parameters should match the 1st statement displayed in your browser. The only difference is that the browser displays it in 2 statements : 1st with POST and second with a "Host" Soap Header Tag. For web service calls we will include the "Host" in the url itself.

    http_req := utl_http.begin_request('http://<your_url>/myWeb/testws/Service.asmx', 'POST', 'HTTP/1.1');

    Note: Please remember that your web service is on your localhost but the Oracle database is most likely not in your localhost but in some remote server. For the database server, your webservice hosted on your machine is a remote server so use the IP or hostname of your machine instead of "localhost" (spent a lot of time just solving this small issue ;)).


  9. Set the Content-Type as 'text/xml' as displayed in the browser. You can set the charset too but I did not find it mandatory, so skipping it.

    utl_http.set_header(http_req, 'Content-Type', 'text/xml');


  10. Set the Content-Length to length of the SOAP request. Luckily the length() function of Oracle does that for you. If you check in the Browser, it marks 'length' as a placeholder to be replaced by the actual value when the request is sent. So in Oracle we do so using the length function.

    utl_http.set_header(http_req, 'Content-Length', length(request_env));


  11. Set the 'SOAPAction' field in your SOAP header. This is the namespace of your method appended by the actual method name (operation name). Currently its displayed on your browser. To find it out, you can open the WSDL for your service and browse to the end of the file. In there you will notice:

    - <wsdl:binding name="ServiceSoap" type="tns:ServiceSoap">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" />
    - <wsdl:operation name="HelloWorld">
    <soap:operation soapAction="http://tempuri.org/HelloWorld" style="document" />

    Thats where the soapAction is set.

    utl_http.set_header(http_req, 'SOAPAction', '"http://tempuri.org/HelloWorld"');


  12. After setting all the SOAP Headers correctly, now write the SOAP Body for the request. As we have already written it in our 1st step, its just a copy paste function.utl_http.write_text(http_req, request_env);


  13. No request the response and read it. Finally close the http connection. I have received the response which is a UTL_HTTP Response object with all the XML DOM defined and with a lot of other functionality available to manipulate the object. To keep things simple, I have actually read the repose to a varchar object 'response_env'.

    http_resp := utl_http.get_response(http_req);
    utl_http.read_text(http_resp, response_env);
    utl_http.end_response(http_resp);


  14. Thereafter all statements are just to print out the response to the DBMS Output.


  15. I have also caught the HTTP end of reponse exception just in case something goes wrong and closed the connection.

Hope this small piece of code helps you out in your first web service call from Oracle. Gradually you can use a lot of good code available on the internet to form your request and parse the response.

Monday, July 14, 2008

Minimize App to System Tray

Recently I made a Tata Indicom web dialer. The problem I faced was that Tata Indicom (my ISP) logs me out if I dont use internet for a few hours. When back I need re login and then my internet will be up. I wished to automate it so I used the 'Axshdocvw' way to set the user name and password whenever I reached the login page. That done, the app was supposed to run as a service. I did not want to code that much so just ran the app. The problem was that it stayed in my task bar and looked odd. So I wanted it to minimize to system tray and here's how its done:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace MinimizeToTray
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

// make the icon invisible to start with
notifyIcon1.Visible = false;
}

private void Form1_Resize(object sender, EventArgs e)
{
notifyIcon1.BalloonTipTitle = "Minimize to Tray";
notifyIcon1.BalloonTipText = "You have successfully minimized your App to tray.";

if (FormWindowState.Minimized == this.WindowState)
{
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(500);
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
notifyIcon1.Visible = false;
}

}

private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;

}

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
// Create Menu here
}
}
}
}

Wednesday, May 9, 2007

Before Time Stopped

NatGeo carries out a series named 'Before Time Stopped'. It speaks about what happened before something started like one which told about how earth was formed.

Similarly in .NET, before execution starts a lot of things happen:

1) You develop something in C#
2) You compile it using the C# compiler
3) The C# compiler spits out IL code and a manifest into a read-only part of the exe that has a standard PE header.
4) The compiler also imports a function named _CorExeMain from the .NET EE
5) When you attempt to run the PE, the OS loads the PE (which loads the DLL that exports the _CorExeMain function: MSCorEE.DLL).
7) The OS loader then jumps to the entry-point inside the PE (put there by the C# compiler)
8) That code is just a small stub that jumps to the _CorExeMain function
9) _CorExeMain then starts the execution of the managed code that was placed in the PE
10) Since IL can not be executed directly, the EE compiles the IL using a JITter into native CPU instructions as it processes the IL. This part only occurs as functions are called the first time.

and hence time starts ..