Use Apache CFX in eclipse to develop and deploy WebService for File Upload

Source: Internet
Author: User

Use Apache CFX in eclipse to develop and deploy WebService for File Upload

Configuration and deployment

This example shows how to configure and develop a cxf-based Web Service Running on the server. The service uploads files submitted by the client. See the following specifications.

Tomcat web server 5.5 or later:The Tomcat Servlet Engine is an open-source package and is part of the Jakarta project of the Apache Software Foundation. It is an official reference implementation of Servlet and JSP specifications. Tomcat can be used as an independent web server or as a Servlet/JSP Engine. From
The http://tomcat.apache.org/download-60.cgi downloads the latest release of Tomcat.

Apache-cxf-2.3. or later:Apache cxf is an open-source service framework. Cxf helps you build and develop services using front-end programming APIs such as JAX-WS and JAX-RS. These services support various protocols, such as soap, XML/HTTP, restful HTTP, or CORBA, and can use multiple transmission methods, such as HTTP, JMS, or jbi. You can
Http://cxf.apache.org/download.html download the latest version.

Eclipse IDE:An integrated development environment (IDE) that integrates all the tools for writing, editing, compiling, and running computer programs. In addition, eclipse provides an excellent integrated development environment. You can

At www.eclipse.org, find the latest version of Eclipse.

SetSet Environment

  1. Install JDK 1.5 or later in the system.
  2. After downloading the Apache-cxf release, set the cxf_home environment variable.
  3. Download the latest Tomcat release and set the tomcat_home environment variable.

CreateCreate a Web Service

  1. InJavaeeIn PerspectiveStartEclipse, and select
    File> New> Other> dynamic web project, Create a file named'Cxfservice.
  2. ExpandCxfservice ProjectTab, select
    Java Resource: SRC
    And create'Com. IBM. uploadbean'Package.
  3. 'Com. IBM. uploadbeanThe 'package will contain a simple Java Bean class, which will get and set the file name, file type, and datahandler type. The bean will be passed as a parameter to call the service. Therefore, create a class under the package and name it'Fileuploader'.
package com.ibm.uploadbean;       import javax.activation.DataHandler;public class FileUploader{  private String Name;  private String FileType;  private DataHandler Dfile;  public String getName()  {    return this.Name;  }  public void setName(String Name)  {    this.Name = Name;  }  public DataHandler getDfile()  {    return this.Dfile;  }  public void setDfile(DataHandler Dfile)  {    this.Dfile = Dfile;  }public String getFileType() {    return FileType;}public void setFileType(String FileType) {    this.FileType = FileType;}}
  1. Each web service requires a service endpoint interface (SEI) through which the client can call the implementation class. Select now
    Java Resource: SRC, Create another name named'Com. IBM. uploadservice.
  2. Create a file named'Uploadsei', Including'Uploadfile'Method
package com.ibm.uploadservice;import javax.jws.WebParam;import javax.jws.WebService;import com.ibm.uploadbean.FileUploader;@WebServicepublic interface UploadSEI {        void uploadFile(@WebParam(name="Dfile") FileUploader Dfile);}

6. Create a file named'Uploadserviceimpl'Service implementation class, which is in'Com. IBM. uploadservice'Internal implementation interface of the package. This class defines the implementation method uploadfile, which uses fileuploader Bean
As its parameter.

 

package com.ibm.uploadservice;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.activation.DataHandler;import javax.jws.WebService;import com.ibm.uploadbean.FileUploader;@WebService(endpointInterface = "com.ibm.uploadservice.UploadSEI",serviceName = "UploadService")public class UploadServiceImpl implements UploadSEI{public void uploadFile(FileUploader Dfile) {DataHandler handler = Dfile.getDfile();try {    InputStream is = handler.getInputStream();    OutputStream os = new FileOutputStream(new File("E:/uploads/"    + Dfile.getName() +"."+     Dfile.getFileType()));    byte[] b = new byte[100000];    int bytesRead = 0;    while ((bytesRead = is.read(b)) != -1) {os.write(b, 0, bytesRead);    }    os.flush();    os.close();    is.close();} catch (IOException e) {    e.printStackTrace();}    }  }
  1. "OutputstreamSave the file to the specified location provided.
  2. The next step is to create the configuration file'Cxf. xml', The file will be based on the Implementation class'Uploadserviceimpl'Create a JAX-WS endpoint. Make sure the file is located in'SRC'Root folder. Otherwise, edit web. XML according to your file path.
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://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" />  <jaxws:endpoint id="uploadfile"                  implementor="com.ibm.uploadservice.UploadServiceImpl"                  address="/UploadWS">                  <jaxws:properties>      <entry key="mtom-enabled" value="true"/>    </jaxws:properties>    </jaxws:endpoint></beans>
  1. Edit'Web. xml'File.
<?xml version="1.0" encoding="UTF-8"?><Web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:Web="http://java.sun.com/xml/ns/javaee/Web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/Web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>CxfService</display-name>   <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:cxf.xml</param-value>  </context-param>  <listener>    <listener-class>      org.springframework.Web.context.ContextLoaderListener    </listener-class>  </listener>  <servlet>    <servlet-name>CXFServlet</servlet-name>    <servlet-class>        org.apache.cxf.transport.servlet.CXFServlet    </servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>CXFServlet</servlet-name>    <url-pattern>/*</url-pattern>  </servlet-mapping>  </Web-app>

 

  1. InWebcontent> Web-INFCreate a file named'Lib'Folder (see figure 5), and then include the following. jar file in the Lib folder. You can find all these jar files in the downloaded cxf distribution library.

Aopalliance-1.0.jar
Asm-2.2.3.jar
Commons-lang-2.4.jar
Commons-logging-1.1.jar
Cxf-api-2.1.5.jar
Cxf-common-schemas-2.1.5.jar
Cxf-common-utilities-2.1.5.jar
Cxf-rt-bindings-soap-2.1.5.jar
Cxf-rt-bindings-xml-2.1.5.jar
Cxf-rt-core-2.1.5.jar
Cxf-rt-databinding-jaxb-2.1.5.jar
Cxf-rt-frontend-jaxws-2.1.5.jar
Cxf-rt-frontend-simple-2.1.5.jar
Cxf-rt-transports-http-2.1.5.jar
Cxf-rt-ws-addr-2.1.5.jar
Cxf-tools-common-2.1.5.jar
FastInfoset-1.2.2.jar
Geronimo-activation_1.1_spec-1.0.2.jar
Geronimo-annotation_1.0_spec-1.1.1.jar
Geronimo-javamail_1.4_spec-1.3.jar
Geronimo-jaxws_2.1_spec-1.0.jar
Geronimo-stax-api_1.0_spec-1.0.1.jar
Geronimo-ws-metadata_2.0_spec-1.1.2.jar
Jaxb-api-2.1.jar
Jaxb-impl-2.1.9.jar
Neethi-2.0.4.jar
Saaj-api-1.3.jar
Saaj-impl-1.3.2.jar
Spring-beans-2.0.8.jar
Spring-context-2.0.8.jar
Spring-core-2.0.8.jar
Spring-Web-2.0.8.jar
Wsdl4j-1.6.2.jar
Wstx-asl-3.2.6.jar
Xml-resolver-1.2.jar
XmlSchema-1.4.5.jar

  1. Right-click a project and chooseExport> war File(See figure 7 ). Copy the war file and paste it to the webapps directory under tomcat_home. Start the Tomcat server.
  2. After the Tomcat server is started, the Web service will be deployed on the server. EnterTomcat Manager, Enter the user name and password, and then log on. You will find that the deployed name is'CxfserviceClick the service to view the available service and its WSDL location. Click the location hyperlink to view the WSDL.

Service endpoint-
Http: // localhost: 8080/cxfservice/uploadws
WSDL location-http: // localhost: 8080/cxfservice/uploadws? WSDL

 

 

GenerateStub

To call the service, the client must know
Service endpoint interface and bean file, which will be called as parameters. To obtain the content, the client can
Create stub in WSDL.

Cxf
The release provides'Wsdl2java. bat', Which can be created for a specific service
Stub, and provide some additional parameters for the WSDL position.

Access the bin directory of $ (cxf_home) from the command prompt and enter the following command.

wsdl2java client
verbose http://localhost:8080/CxfService/UploadWS?wsdl

This will run the wsdl2java. BAT file in the bin directory. '-Client'
The starting point code. '-Verbo'
Option to display comments during code generation. See figure
9.

After the command is successfully executed(Cxf_home)/binDirectory'Com. IBM. uploadservice'
Stub is created under the package.

 

CreateCreate a client

Next, we will create a client project so that you can use the web service. In this example, the client is a pojo client. You can also create a client that requires a Web container. Follow these steps to develop a client.

  1. In eclipse, selectFile> New> Other> dynamic web project, Create a file named'Cxfclient.
  2. Create a file named'Com. IBM. uploadservice', And copy and paste all generated stubs to it.
  3. Create another name'Com. IBM. Client. Create a new class named 'client' in the package. This class will call developed services through the generated stub. This class will contain the main () method, so the execution starts from here.
package com.ibm.client;import java.io.File;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import org.apache.cxf.interceptor.LoggingInInterceptor;import org.apache.cxf.interceptor.LoggingOutInterceptor;import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;import com.ibm.uploadservice.*;public final class Client {      public static void main(String args[]) throws Exception {    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();    factory.getInInterceptors().add(new LoggingInInterceptor());    factory.getOutInterceptors().add(new LoggingOutInterceptor());    factory.setServiceClass(UploadSEI.class);    factory.setAddress    ("http://localhost:8080/CxfService/UploadWS");    UploadSEI client =(UploadSEI) factory.create();    FileUploader file=new FileUploader();            file.setName("Partha");    file.setFileType("doc");        DataSource source = new FileDataSource(new File("D:/my_upload_doc.doc"));    file.setDfile(new DataHandler(source));    client.uploadFile(file);    System.exit(0);       }    }

 

  1. Do not forgetWebcontent> Web-INF> libContains the. jar file.
  2. The source code of the 'datasource 'object will contain the ideal location for uploading files. In this example'D:/my_upload_doc.doc', Which can be modified according to your file.
  3. Setname ("Partha ")Is the name of the uploaded file. Modify
    Setfiletype ("Doc ")
    You can set the file type accordingly.
  4. You may'File. setdfile'To Get A type matching error, which may be because of the generated'Fileuploade. Java'There is'Byte []'Variable, not 'datahandler' variable. Set
    Modify byte [] to datahanderYou can solve this problem. You should also import'Javax. Activation. datahandler'. Reference
    Listing 1The bean class used to create the service.
  5. To run the client, right-click the client. Java file and selectRun as> JAVA application. If no error occurs, you will find that your file is saved in the specified location by a given name.

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.