Friday, April 25, 2008

Send Attachment over SOAP - Passing files to WebService ( Steps for JDeveloper )

Pre-req: Create Workspace and a project inside that workspace with index.html

1. Write an implementation class with method which takes AttachmentPart as an input

public String processAttachment(int id,
AttachmentPart attachment) throws RemoteException {

try {


Object attachmentObj = attachment.getContent();

//Add code to process input attachment

} catch (Exception se) {
//Exception handling
}


return "Test";

}

2. Go to File->New->Business Tier->Web Services and select Java Web Services (J2EE 1.4 or 1.3 version) and click OK

3. Go to Next

4. Give "Web Service Name" e.g MyTestWebService

5. Select your implementation class

6. Click Next

7. Click Next

8. Click Next

9. Click Next

10. Select your method e.g processAttachment to expose as webservice.

11. Finish ( This will generate WSDL and all related classes )

12. Now go to your WebService in "System Navigator"

13. Right Click on WebService (MyTestWebService) and click on Generate WebService Proxy

14. Select "Run against a service deployed to an external server" radio button and click OK.

15. Run your project

16. Go to ....SoapHttpPortClient.java and add following method

public AttachmentPart getAttachmentPart() throws RemoteException {

AttachmentPart impl = null;
try {
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage message = factory.createMessage();
//change file://c:\\a.txt to a file you want to attach
impl =
message.createAttachmentPart(new DataHandler(new URL("file:\\C:\\a.txt")));
// add attachment to message
message.addAttachmentPart(impl);

} catch (SOAPException ex) {
return null;
} catch (Exception ex) {
return null;
}
return impl;
}

and call that method from main(). It will look like

public static void main(String[] args) {
try {
MyTestWebServiceSoapHttpPortClient myPort =
new MyTestWebServiceSoapHttpPortClient();

myPort.processAttachment(0, myPort.getAttachmentPart());
// Add your own code here

} catch (Exception ex) {
ex.printStackTrace();
}
}

17. Run Your Client to test your webservice

Note: JDeveloper is generating .wsdl and ..Stub.java with port 8888. If your embedded oc4j is running on different port then you will have to modify .wsdl and ..Stub.java

Give a try. Good Luck!

No comments: