Jax WS attachment MTOM example

Click here to download eclipse supported ZIP file



This is index.jsp JSP file and it is used display the output for the application.




<jsp:forward page="/initServlet"></jsp:forward>


This is InitServlet.java file having the source code to execute business logic.



 

    
package com.cv.servlet.init;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class InitServlet
 
 @author Chandra Vardhan
 *
 */

public class InitServlet extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(InitServlet.class);

  private static final long serialVersionUID = 1L;

  /**
   @see HttpServlet#HttpServlet()
   */
  public InitServlet() {
    super();

  }

  /**
   @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    LOGGER.info("Entered into doGet(--) of InitServlet class... ");

    response.setContentType("text/html");

    String contextPath = this.getClass().getClassLoader().getResource("/").getPath();
  
    if(contextPath != null) {
      contextPath = contextPath.substring(0, contextPath.lastIndexOf(".metadata")-1);
      if(contextPath.startsWith("\\")) {
        contextPath = contextPath.substring(1, contextPath.length());
      }
      contextPath = contextPath+request.getContextPath();
    }
    
    File file = new File(contextPath+"//input.properties");
    if (file != null && !file.exists()) {
      file.createNewFile();
    }
    LOGGER.info("created at :: "+file.getAbsolutePath());
    final PrintWriter pw = new PrintWriter(new FileOutputStream(file));
    pw.print("portNumber=" + request.getServerPort());
    PrintWriter out = response.getWriter();
    out.print("Successfully deployed...");
    pw.close();
    out.close();
  }

  /**
   @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
   *      response)
   */
  protected void doPost(HttpServletRequest request,
      HttpServletResponse responsethrows ServletException, IOException {
    LOGGER.info("Entered into doPost(--) of InitServlet class... ");
    doGet(request, response);
  }

}


This is ImageClient.java file having the source code to execute business logic.



 

    
package com.cv.webservice.client;

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;

import org.apache.log4j.Logger;

import com.cv.webservice.ws.ImageServer;

/**
 @author Chandra Vardhan
 *
 */
public class ImageClient {
  private static final Logger LOGGER = Logger.getLogger(ImageClient.class);
  private static String WS_URL = "/JaxWSAttachmentMTOM/image?wsdl";

  static {
    Properties properties = readFile();
    setValues(properties);
  }

  public static void main(String[] argsthrows Exception {

    URL url = new URL(WS_URL);
    LOGGER.info("URL is : : " + WS_URL);
    QName qname = new QName("http://ws.webservice.cv.com/",
        "ImageServerImplService");

    Service service = Service.create(url, qname);
    ImageServer imageServer = service.getPort(ImageServer.class);

    /************ test upload ****************/
    Image imgUpload = ImageIO.read(new File("c:/input.jpg"));

    // enable MTOM in client
    BindingProvider bp = (BindingProviderimageServer;
    SOAPBinding binding = (SOAPBindingbp.getBinding();
    binding.setMTOMEnabled(true);

    String status = imageServer.uploadImage(imgUpload);
    LOGGER.info("imageServer.uploadImage() : " + status);

    /************ test download ***************/
    /*
     * Image image = imageServer.downloadImage("rss.png");
     
     * //display it in frame JFrame frame = new JFrame(); frame.setSize(300,
     * 300); JLabel label = new JLabel(new ImageIcon(image));
     * frame.add(label); frame.setVisible(true);
     
     * System.out.println("imageServer.downloadImage() : Download Successful!"
     * );
     */

  }

  private static void setValues(Properties properties) {

    if (properties != null) {
      String port = properties.getProperty("portNumber");
      WS_URL = "http://localhost:" + port + WS_URL;
    }
  }

  private static Properties readFile() {

    File file = new File(System.getProperty("user.dir")
        "/input.properties");
    Properties prop = new Properties();
    if (file != null && file.exists()) {
      InputStream input = null;
      try {
        input = new FileInputStream(file);
        // load a properties file
        prop.load(input);
      catch (Exception e) {
        e.printStackTrace();
      }
    else {
      prop.setProperty("portNumber""8080");
    }
    return prop;
  }
}


This is ImagePublisher.java file having the source code to execute business logic.



 

    
package com.cv.webservice.endpoint;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import javax.xml.ws.Endpoint;
import org.apache.log4j.Logger;
import com.cv.webservice.ws.ImageServerImpl;

/**
 @author Chandra Vardhan
 *
 */
// Endpoint publisher
public class ImagePublisher {
  private static final Logger LOGGER = Logger.getLogger(ImagePublisher.class);
  private static String WS_URL = "/JaxWSAttachmentMTOM/image";

  static {
    Properties properties = readFile();
    setValues(properties);
  }

  public static void main(String[] args) {

    Endpoint.publish(WS_URL, new ImageServerImpl());
    LOGGER.info("Server is URL is : : " + WS_URL);
    LOGGER.info("Server is published!");

  }

  private static void setValues(Properties properties) {

    if (properties != null) {
      String port = properties.getProperty("portNumber");      
      WS_URL = "http://localhost:" + port + WS_URL;
    }
  }

  private static Properties readFile() {

    File file = new File(System.getProperty("user.dir")
        "/input.properties");
    Properties prop = new Properties();
    if (file != null && file.exists()) {
      InputStream input = null;
      try {
        input = new FileInputStream(file);
        // load a properties file
        prop.load(input);
      catch (Exception e) {
        e.printStackTrace();
      }
    else {
      prop.setProperty("portNumber""8080");
    }
    return prop;
  }
}


This is ImageServer.java file having the source code to execute business logic.



 

    
package com.cv.webservice.ws;

import java.awt.Image;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

/**
 @author Chandra Vardhan
 *
 */
//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface ImageServer{
  
  //download a image from server
  @WebMethod Image downloadImage(String name);
  
  //update image to server
  @WebMethod String uploadImage(Image data);
  
}



This is ImageServerImpl.java file having the source code to execute business logic.



 

    
package com.cv.webservice.ws;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.MTOM;

/**
 @author Chandra Vardhan
 *
 */
//Service Implementation Bean
@MTOM
@WebService(endpointInterface = "com.cv.webservice.ws.ImageServer")
public class ImageServerImpl implements ImageServer {

  @Override
  public Image downloadImage(String name) {
    try {
      File image = new File("c:\\images\\" + name);
      return ImageIO.read(image);
    catch (IOException e) {
      e.printStackTrace();
      return null;
    }

  }

  @Override
  public String uploadImage(Image data) {
    BufferedImage image = null;
    if (data != null) {
      image = (BufferedImagedata;
      try {
        File file = new File("C:\\images\\output.jpg");
        if(!file.exists()) {
          file.mkdirs();
        }
        ImageIO.write(image, "jpg", file);
      catch (IOException e) {
        e.printStackTrace();
      }
      return "Upload Successful";
    }

    throw new WebServiceException("Upload Failed!");

  }

}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.webservice</groupId> <artifactId>JaxWSAttachmentMTOM</artifactId> <version>1.0</version> <packaging>war</packaging> <name>JaxWSAttachmentMTOM</name> <properties> <springframework.version>4.1.6.RELEASE</springframework.version> <springsecurity.version>4.0.1.RELEASE</springsecurity.version> </properties> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>JaxWSAttachmentMTOM</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <finalName>JaxWSAttachmentMTOM</finalName> </build> </project>




This is web.xml deployment descriptor file and it describes how the web application should be deployed.



	
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">


<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>com.cv.servlet.init.InitServlet</servlet-class>

</servlet>
<servlet-mapping>
<servlet-name>initServlet</servlet-name>
<url-pattern>/initServlet</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>120</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

No comments:

Post a Comment