Showing posts with label was8. Show all posts
Showing posts with label was8. Show all posts

Create Hello JAX-RS service in WAS 8.0

The WAS 8.0 is Java EE 6.0 compliant that means it allows you to deploy JAX-RS compliant service and you dont have to go through painful steps for setting up external JAXRS container such as Jersey in your web application

I wanted to figure out what it takes to create HelloREST application in WAS 8.0 so i followed this steps to create Hello JAX-RS service. You can download the source code for sample from here


  • First i used RAD 8.0 to create Servlet Technology 3.0 compliant web application( Which means no need for web.xml or no need of declaring servlets)


  • Next create a HelloRestService class that is basically a REST service and is available at /hellorest url


    package com.webspherenotes.rest;

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.QueryParam;

    @Path("/hellorest")
    public class HelloRESTService {

    @GET
    @Produces("text/html")
    public String sayHello(@QueryParam("name") String name){
    return "Hello " + name;
    }

    }




  • Next create HelloApplication class which is basically a REST servlet class like this.

    package com.webspherenotes.rest;

    import java.util.HashSet;
    import java.util.Set;

    import javax.ws.rs.ApplicationPath;
    import javax.ws.rs.core.Application;

    @ApplicationPath("/rest/")
    public class HelloApplication extends Application{

    @Override
    public Set<Class<?>> getClasses() {
    Set<Class<?>> s = new HashSet<Class<?>>();
    s.add(HelloRESTService.class);
    return s;
    }

    }

    The HelloApplication class extends javax.ws.rs.core.Application which helps you to declare the JAX-RS application, in this class i am overriding the getClasses() method which returns set of JAX-RS classes that act as JAX-RS service. In my case i do have only one HelloRESTService class so i am only adding that

  • Now deploy the application on your WAS 8.0 server, if you try accessing it by sending GET request to http://localhost:9080/HelloRESTService/rest/hellorest?name=Sunil URL and you should get Hello Sunil as response

Updating WAS 8

In the Installing WAS 8 Beta on your machine, entry i talked about how IBM has changed the way we installed WebSphere Application Server starting from V8.0. Now we have to use the IBM Installation Manager,

One advantage of using the IBM Installation manager for installing/managing the WAS 8.0 is that updating it has become very easy, I had to use simple wizard to install latest WAS 8.0 recommended fixes on my machine, no need to go through the process of finding recommended fixes, downloading them and the using update installer to install fixes.








Installing enterprise application files by adding them to a monitored directory

The WebSphere Application Server 8.0 introduces this new feature, in which you can copy enterprise application file in the monitoredDirectory and it automatically gets installed on the server. This feature is similar to concept of copying .war file in the webapps directory. I wanted to try this feature, so i followed these steps

  • The monitored directory feature is disabled by default so the first step would be to enable this feature, for that login into WAS Admin Console and go to Applications -> Global Deployment settings.


    On this page the Monitor directory to automatically deploy applications check box is unchecked by default, so check it. Then you can either use the default path for the monitored directory which is app_profile_root/monitoredDeployableApps or you can change this path to something else, save the changes and restart the server

  • Once the server is restarted you will notice that app_profile_root/monitoredDeployableApps gets created for you


  • I did export HelloMonitoredDirectoryEAR.ear into the monitoredDirectory


  • After copying the .ear into monitoredDirectory i was looking at the logs and i could notice that it is being picked up for deployment

    [7/5/11 12:32:35:944 PDT] 00000013 WatchService I CWLDD0007I: Event id 1937700630-1. Start of processing. Event type: Added, File path: C:\IBM\WebSphere\AppServer\profiles\AppSrv01\monitoredDeployableApps\servers\server1\HelloMonitoredDirectoryEAR.ear.
    [7/5/11 12:32:36:022 PDT] 00000013 ModelMgr I WSVR0801I: Initializing all server configuration models
    [7/5/11 12:32:37:303 PDT] 00000013 WorkSpaceMana A WKSP0500I: Workspace configuration consistency check is disabled.
    [7/5/11 12:32:38:475 PDT] 00000013 AppManagement I CWLDD0028I: Event id 1937700630-1. The target of the current operation is [WebSphere:cell=ascendan-ggbz6iNode01Cell,node=ascendan-ggbz6iNode01,server=server1].
    [7/5/11 12:32:38:553 PDT] 00000013 AppManagement I CWLDD0014I: Event id 1937700630-1. Installing application HelloMonitoredDirectoryEAR...
    [7/5/11 12:32:40:022 PDT] 00000013 annotations I ArchiveInputStreamData mapData Collision on [ WEB-INF/classes/com/webspherenotes/test/HelloMonitoredServlet.class ] in [ HelloMonitoredDirectory.war ]
    [7/5/11 12:32:43:631 PDT] 00000014 annotations I ArchiveInputStreamData mapData Collision on [ WEB-INF/classes/com/webspherenotes/test/HelloMonitoredServlet.class ] in [ HelloMonitoredDirectory.war ]
    [7/5/11 12:32:55:645 PDT] 00000014 webcontainer I com.ibm.ws.webcontainer.internal.WebContainer addExtensionFactory SRVE0239I: Extension Factory [class com.ibm.ws.soa.sca.web.extension.SCAWebExtensionFactory] was registered successfully.
    [7/5/11 12:32:55:676 PDT] 00000014 webcontainer I com.ibm.ws.webcontainer.internal.WebContainer addExtensionFactory SRVE0240I: Extension Factory [class com.ibm.ws.soa.sca.web.extension.SCAWebExtensionFactory] has been associated with patterns [""].
    [7/5/11 12:32:55:692 PDT] 00000014 WebSphereSCAS I Added Servlet mapping: /dojo
    [7/5/11 12:32:55:692 PDT] 00000014 WebSphereSCAS I Added Servlet mapping: /dojo
    [7/5/11 12:32:55:692 PDT] 00000014 WebSphereSCAS I Added Servlet mapping: /tuscany
    [7/5/11 12:32:55:692 PDT] 00000014 WebSphereSCAS I Added Servlet mapping: /tuscany
    [7/5/11 12:32:58:848 PDT] 00000014 annotations I ArchiveInputStreamData mapData Collision on [ WEB-INF/classes/com/webspherenotes/test/HelloMonitoredServlet.class ] in [ HelloMonitoredDirectory.war ]
    [7/5/11 12:32:58:957 PDT] 00000014 InstallSchedu I ADMA5013I: Application HelloMonitoredDirectoryEAR installed successfully.
    [7/5/11 12:33:03:223 PDT] 00000013 annotations I ArchiveInputStreamData mapData Collision on [ WEB-INF/classes/com/webspherenotes/test/HelloMonitoredServlet.class ] in [ HelloMonitoredDirectory.war ]
    [7/5/11 12:33:04:144 PDT] 00000013 annotations I ArchiveInputStreamData mapData Collision on [ WEB-INF/classes/com/webspherenotes/test/HelloMonitoredServlet.class ] in [ HelloMonitoredDirectory.war ]
    [7/5/11 12:33:04:207 PDT] 00000013 annotations E CWWAM0001E: An exception occurred during annotation processing: java.lang.IllegalArgumentException: The feature 'annotated-classes' is not a valid feature

  • I did wait for couple of minutes and then i checked the WAS Admin console and i could see newly installed application like this



  • I wanted to see where exactly the application is getting installed so i looked at the value of application binaries and i can see that it got installed in regular installedApp directory



WAS 8 is out

I saw WebSphere Application Server 8 is out press release today. It looks like bunch of other software products are also released. The main focus is on Mobile, cloud,...

Installing WAS 8 Beta on your machine

The WebSphere Application Server 8 is in Beta stage for some time now. One of the most important feature's in WAS 8 is that it supports JEE 6. I want to learn JEE 6 so i installed the WAS 8 Beta on my machine. I used these steps to install it


  • Go to the WAS 8 Beta Web Site and login using your IBM user id and password


  • Download following CD's

    1. IBM WebSphere Application Server 8.0 Beta (Part 1 of 4)

    2. IBM WebSphere Application Server 8.0 Beta (Part 2 of 4)

    3. IBM WebSphere Application Server 8.0 Beta (Part 3 of 4)

    4. IBM WebSphere Application Server 8.0 Beta (Part 4 of 4)

    5. IBM Installation Manager for Windows on Intel


    The first 4 CD's are same on all the platform's but the Installation Manager CD would depend on the platform which your using. I use a Windows 7 for trying WAS 8 so i had to install Windows on Intel Installation Manager

  • Once all the files are downloaded extract them in the same folder and you should get structure like this

  • If you look into the extracted files you will notice there is no launchpad.exe to install the WAS and the downloaded files look like Eclipse Updation archive. The reason is that we will have to use the Installation Manger(Same product that we use for installing Rational products such as RAD). If you have RAD installed on your machine you can use the Installation Manager for the RAD to install WAS 8 Beta, thats what i am going to do. If you dont have RAD install the Installation Manager first

  • Once you have Installation Manager installed on your machine, start it and then follow these steps

    Click on Install





















  • Once the installation finished you should see a screen that will launch profile management tool for you, I want to use this server for development so i am selecting create application server profile for development



  • On the next screen it will ask you to set userId and password for the admin user(You can always skip this step but i like to enable admin security at the start so i will keep it



  • After that it will show you the profile properties like WAS Server HTTP and Admin Port you might want to keep screen print of this page or note down port numbers




Now your WAS 8 is ready to use

Uploading file to particular directory

You can configure the File Upload support in servlet specification 3.0 so that it uploads files to particular directory on your server.


package com.webspherenotes.j2ee6.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
* Servlet implementation class HelloFileUploadAnnotationServlet
*/
@WebServlet("/hellofileupload")
@MultipartConfig(location="c:/temp/upload")
public class HelloFileUploadAnnotationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Entering HelloFileUploadAnnotationServlet.doPost()");
response.setContentType("text/html");
response.getWriter().println("Hello from FileUploadServlet");
Collection fileParts = request.getParts();
Iterator filePartIt = fileParts.iterator();
while(filePartIt.hasNext()){
Part filePart = filePartIt.next();
System.out.println("File Name " + filePart.getName());
System.out.println("File Size " + filePart.getSize());

System.out.println("File Content ");
BufferedReader fileReader =
new BufferedReader(new InputStreamReader(filePart.getInputStream()));
String line = null;
while(( line = fileReader.readLine()) != null){
System.out.println(line);
}
}
System.out.println("Exiting HelloFileUploadAnnotationServlet.doPost()");
}

}


In my case i am setting value of location to c:/temp/upload and then i tried uploading couple of files and now i can see that every time i upload a file a .tmp file gets created in c:/temp/upload

Setting limit on filesize to be uploaded

When your handling the file upload you might want to set limit on the file size that can be uploaded you can do that by setting value of maxFileSize. The value of maxFileSize is in bytes,

@WebServlet("/hellofileupload")
@MultipartConfig(maxFileSize=1000 )
public class HelloFileUploadAnnotationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Entering HelloFileUploadAnnotationServlet.doPost()");
response.setContentType("text/html");
response.getWriter().println("Hello from FileUploadServlet");
Collection fileParts = request.getParts();
Iterator filePartIt = fileParts.iterator();
while(filePartIt.hasNext()){
Part filePart = filePartIt.next();
System.out.println("File Name " + filePart.getName());
System.out.println("File Size " + filePart.getSize());

System.out.println("File Content ");
BufferedReader fileReader =
new BufferedReader(new InputStreamReader(filePart.getInputStream()));
String line = null;
while(( line = fileReader.readLine()) != null){
System.out.println(line);
}
}
System.out.println("Exiting HelloFileUploadAnnotationServlet.doPost()");
}

}


So in my sample application if i try to upload a file bigger than 1000 bytes it will throw a java.lang.IllegalStateException exception like this

[12/19/10 20:24:23:765 PST] 00000019 servlet E com.ibm.ws.webcontainer.servlet.ServletWrapper service
SRVE0068E: An exception was thrown by one of the service methods of the servlet [com.webspherenotes.j2ee6.servlet.HelloFileUploadAnnotationServlet]
in application [HelloServletAnnotationEAR]. Exception created : [java.lang.IllegalStateException:
SRVE8021E: The file being uploaded is too large.
at com.ibm.ws.webcontainer.srt.SRTServletRequest.parseMultipart(SRTServletRequest.java:3504)
at com.ibm.ws.webcontainer.srt.SRTServletRequest.prepareMultipart(SRTServletRequest.java:3413)
at com.ibm.ws.webcontainer.srt.SRTServletRequest.getParts(SRTServletRequest.java:3394)
at com.webspherenotes.j2ee6.servlet.HelloFileUploadAnnotationServlet.doPost(HelloFileUploadAnnotationServlet.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1133)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:708)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:435)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1012)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3598)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:303)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:950)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1624)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:197)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:445)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:504)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:301)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:275)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1618)
]

Handling file upload in Servlet 3.0

Ability to handle file upload is one of the common requirements for web application. Before Servlet Specification 3.0 if you wanted to handle file upload you would have to use external library such as Apache Commons File upload to handle the file upload.

But starting from Servlet Specification 3.0 you dont need external library instead there is a native support. I wanted to try this so i followed these steps


  1. First i did create a index.jsp file like this

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%@page
    language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <html>
    <head>
    <title>index</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    </head>
    <body>
    <form action="hellofileupload" method="post" enctype="multipart/form-data" >
    <table>
    <tr>
    <td>File</td>
    <td><input type="file" name="samplefile" /></td>
    </tr>
    <tr><td><input type="submit"></td></tr>
    </table>
    </form>

    </body>
    </html>


    If you want to upload a file to the server you will have to set form encoding type to multipart/form-data. The index.jsp will submit form to the hellofileupload url and thats where our HelloFileUploadAnnotationServlet will come in

  2. Next create a HelloFileUploadAnnotationServlet like this

    package com.webspherenotes.j2ee6.servlet;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Collection;
    import java.util.Iterator;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;

    /**
    * Servlet implementation class HelloFileUploadAnnotationServlet
    */
    @WebServlet("/hellofileupload")
    @MultipartConfig
    public class HelloFileUploadAnnotationServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    System.out.println("Entering HelloFileUploadAnnotationServlet.doPost()");
    response.setContentType("text/html");
    response.getWriter().println("Hello from FileUploadServlet");
    Collection fileParts = request.getParts();
    Iterator filePartIt = fileParts.iterator();
    while(filePartIt.hasNext()){
    Part filePart = filePartIt.next();
    System.out.println("File Name " + filePart.getName());
    System.out.println("File Size " + filePart.getSize());

    System.out.println("File Content ");
    BufferedReader fileReader =
    new BufferedReader(new InputStreamReader(filePart.getInputStream()));
    String line = null;
    while(( line = fileReader.readLine()) != null){
    System.out.println(line);
    }
    }

    System.out.println("Exiting HelloFileUploadAnnotationServlet.doPost()");
    }
    }

    In order to use the file upload first you will have to mark the Servlet using MultipartConfig annotation, indicating that instances of the Servlet expect requests that conform to the multipart/form-data MIME type.
    Then inside the doPost() method you can use the method of HttpServletRequest to get access to the uploaded file.

Whats new in Servlet Specification 3.0

The Servlet Specification 3.0 has lot of new features such as


  1. Annotations

  2. Web Fragments

  3. Defining new servlet/filter using ServletContext API

  4. Async Servlet support



I want to try some of the features and i am planning to blog about them

Create profile in WAS 8 (Problem in creating profile as part of installation )

In the How to install WebSphere Application Server 8.0 Beta entry i blogged about the steps to install WebSphere Application Server 8.0 beta. On the last page of the WAS 8 installation wizard it asks you to create profile and it can launch profile creating wizard for you. I did select "Profile management tool to create an application server profile for development environment", but that profile management tool never came up. So i had to follow these steps to create application server profile



  • I went to the "\WebSphere\AppServer\bin\ProfileManagement" directory and executed the PMT.exe tool to start the profile management tool


  • On the next screen select Profile Management Tool and click on Launch tool and it will show you a profiles dialog box like this


  • On this dialog box click on Create button to get Create profile dialog box like this select Application Server as profile and click on Next button and follow next few screens to finish the creation of wizard









How to install WebSphere Application Server 8.0 Beta

It seems that there are quite a few new features in Java EE 5 and Java EE 6 and i wanted to start trying some of them. So i decided to install WebSphere Application Server 8 -Beta, which implements Java EE 6, in addition to many new IBM specific features. These are the steps that i used to install WAS 8 on my machine

  • Download WAS 8.0 Beta installable from IBM WebSite.I had to download 3 .zip from IBM website

  • After downloading the .zip file i did extract them in the same folder. I could see following folder structure


  • After unzipping the files i tried searching for launchpad.exe/setup.exe in all the three folders but i could not find it, so it took me some time to figure out that the procedure for installing the WAS 8.0 is changed. Now we have to use the Installation Manager(Same component that we use for installing Rational Application Developer) for installing the product using GUI

  • Since i use Rational Application Developer 8.0 on my machine i do have the installation manager for it. I decided to use the same installation manager. If you dont have the installation manager already on your machine, you can download it as part of WAS 8.0 installable

  • After starting the IBM Installation Manager and on the first screen click on Install button


  • Since the Installation Manager does not know about the location of your WAS 8 repository, it will open a screen like this, click on the Repository link


  • It will open a Repository preference dialog box like this


  • On this dialog box click "Add Repository" button, it will open a Add a Repository dialog box, use this to select the repository.config file that you unzipped from the WAS 8 installable like this and click Ok


  • Once the new repository is configured Installation Manager will show you WebSphere Application Server 8.0 as installation package, select it and click on Next to start the installation wizard

  • Go through the wizard and at the end select the packages that you want to install like this




The installation manager will take few minutes and once the installation is done it will show a dialog box for creating profile like this