I was using Axis 1.4 on a project and I am moving to Axis2 1.6.3. I am asking this because in Axis1.4 it was quite straightforward :
myStub.addAttachment(new DataHandler(new FileDataSource("path_to_file")));
You just add a DataHandler to the Stub and then send it. But in Axis2 it seems that this method doesn't exist. So I was wondering what is the new way of attaching a DataHandler to a stub ?
As I was searching on the internet, I find out that you have to attach the DataHandler to the MessageContext (Downloading a Binary File from a Web Service using Axis2 and SOAP with Attachments).
So I did As it is said :
MessageContext messageContext = MessageContext.getCurrentMessageContext();
OperationContext operationContext = messageContext.getOperationContext();
MessageContext outMessageContext = operationContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
outMessageContext.addAttachment(new DataHandler(new FileDataSource("path_to_file")));
But the problem is that MessageContext.getCurrentMessageContext() return null. I think that it is not working because this snippet should be used on the server side. What I want is to be able to send a file to the server not retrieve one from the server.
I might be missing something. Maybe this is not the way to do it, anyway any help is appreciated. In the meantime I'll keep up searching on the internet and if I find something I'll let you know :)
So after some time I figured out how to do it on Axis2 Documentation.
Go to SOAP with Attachments (SwA) with Axis2 and on the second section named Sending SwA Type Attachments. Here you will find out how to send a file to the server.
This is the code snippet they provide :
public void uploadFileUsingSwA(String fileName) throws Exception {
Options options = new Options();
options.setTo(targetEPR);
options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
options.setTo(targetEPR);
ServiceClient sender = new ServiceClient(null,null);
sender.setOptions(options);
OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);
MessageContext mc = new MessageContext();
mc.setEnvelope(createEnvelope());
FileDataSource fileDataSource = new FileDataSource("test-resources/mtom/test.jpg");
DataHandler dataHandler = new DataHandler(fileDataSource);
mc.addAttachment("FirstAttachment",dataHandler);
mepClient.addMessageContext(mc);
mepClient.execute(true);
}
For more information go check the page of the documentation.
Cheers !
Related
I'm trying to send a file with resteasy client to an http server with some code like this:
File source = new File("test.pdf");
Client client = ClientBuilder.newClient();
MultipartFormDataOutput upload = new MultipartFormDataOutput();
upload.addFormData("source", source, MediaType.APPLICATION_OCTET_STREAM_TYPE);
Entity entity = Entity.entity(upload, MediaType.MULTIPART_FORM_DATA_TYPE)
Response response = client.target(url).request().post(entity);
What happens is that on the http server I'm not getting the usual "file" in request (with the content, the name etc..), but something like a regular POST parameter named "source" with the file content as its value.
I tried it with some different web servers, so the issue have to be in the request that RESTeasy builds.
Any help?
MultipartFormDataOutput behaves the same away as a HTML form would do. It sends key/value pairs to the server.
If you want to upload a MIME message consider using MultipartOutput.
<soapenv:Header>
<UsernameToken xmlns="http://siebel.com/webservices">uname</UsernameToken>
<PasswordText xmlns="http://siebel.com/webservices">pass</PasswordText>
<SessionType xmlns="http://siebel.com/webservices">None</SessionType>
</soapenv:Header>
I have generated client code using axis runtime and I am getting this exception:Operation 'QueryByExample' with no authentication cannot be executed in an anonymous session pool. Please associate an authentication type with the web service operation.(SBL-EAI-04552).
I looked at others answers from stackoverflow for hours and nothing worked out for me. Please guide me....
Service code:
SOAPHeaderElement wsseSecurity = new SOAPHeaderElement(new PrefixedQName("http://schemas.xmlsoap.org/ws/2002/04/secext","Security", "wsse"));
MessageElement username = new MessageElement("uname", "UsernameToken");
MessageElement password = new MessageElement("pass", "PasswordText");
username.setObjectValue("username");
password.setObjectValue("password");
wsseSecurity.addChild(username);
wsseSecurity.addChild(password);
stub.setHeader(wsseSecurity);
You need to add few more things and the main problem is how you are deifning and using your password. You are on the correct path but here is how you would make a SOAP Axis 1.4 client:
InputStream inConfig = BaseTestCase.class.getClassLoader().getResourceAsStream("axis_client_config.xml");
EngineConfiguration config = new FileProvider(inConfig);
PartnerAPILocator locator = new PartnerAPILocator(config);
inConfig.close();
stub = locator.getSoap();
Stub axisPort = (Stub) stub;
axisPort._setProperty(UsernameToken.PASSWORD_TYPE, WSConstants.PASSWORD_TEXT);
axisPort._setProperty(WSHandlerConstants.USER, "ET USERNAME");
axisPort._setProperty(WSHandlerConstants.PW_CALLBACK_REF, new PasswordTokenHandler());
here is my source and try to follow the tutorial and you can even download the code. Hope this helps you.
In SOAP UI Web service testing,
User imports the Project in to the work space and mentions the End point. Enters the required data in the Request xml and runs to get the resulting response in xml format.
Is there a way we can achieve this using Java only without using the SoapUI tool. I guess the steps should be:
Create a Wsdl Project.
Create a xml request (in the required format)
Send the request to the end point (How to do this?)
Receive response and verify it.
Please help me how to do this using Java only(without using SOAP UI tool). Any links/code will be greatly helpful.
Thanks,
Mike
Use soapUI API.
;
Here are some useful links:
http://www.soapui.org/Developers-Corner/integrating-with-soapui.html
http://pritikaur23.wordpress.com/2013/06/16/saving-a-soapui-project-and-sending-requests-using-soapui-api/
I used the following code to create a project:
File projectFile = new File(filePath);
SoapUI.setSoapUICore(new StandaloneSoapUICore(true));
WsdlProject project = new WsdlProject();
project.setName(projectName);
WsdlInterface[] wsdls = WsdlImporter.importWsdl(project, url);
for (WsdlInterface wsdl : wsdls) {
int c = wsdl.getOperationCount();
String reqContent = "";
for (int j = 0; j < c; j++) {
WsdlOperation op = wsdl.getOperationAt(j);
reqContent = op.createRequest(true);
WsdlRequest req = op.addNewRequest(requestName);
req.setRequestContent(reqContent );
}
}
project.saveIn(projectFile);
SoapUI.shutdown();
You can create client and pass in HTTP Request test request populated with needed parameter for testing purpose, below mention question has some useful insights.
Java Web service testing
I am use this class to send mail it works but now i wants to add attachment how to add it please help if u can
public static void sendMail(String subject, String body, String toEmail, String ccEmail, String fromMail)
throws IOException {
Random generator = new Random();
int r = Math.abs(generator.nextInt());
body = body.replaceAll("(\\r|\\n)", "");
body = body.replaceAll("\"", "\\\\\"");
body = body.replaceAll("&", "\\\\&");
body = body.replaceAll("©", "\\\\©");
//body = body.replaceAll("> <", ">\\\n<");
if(CommonUtils.emptyString(fromMail))
fromMail = "No Reply <iotasol#pcc.com>";
else
fromMail = "No Reply <"+fromMail+">";
ProcessBuilder processBuilder = new ProcessBuilder(
ApplicationProperties.MAIL_SENDER_SH_PATH, CommonUtils.getEmptyStringForNull(subject), CommonUtils.getEmptyStringForNull(body),
toEmail, ccEmail, String.valueOf(r), fromMail);
processBuilder.start();
}
as an idea if you need to send images: make it inline with base64.
Attachments depends on library used, mail server used and so on.
MimeBodyPart messageBodyPart = new MimeBodyPart();
File file = new File("somefile.txt");
if (file.exists()) {
DataSource source = new FileDataSource("somefile.txt");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}
From your code example, I can tell that you are using external mail program for sending emails. You create a ProcessBuilder and invoke an OS tool for sending emails.
I would not use this solution. First, it depends on the OS (on windows you don't have the mail command). Second, this is not efficient; since you create external process for this (imagine sending many emails).
Instead, try using existing mail solution in java (you will need: mail.jar and activation.jar). With it you can send emails directly from your application, not depending on external tool.
While with mail Java library you can do everything you want, you may also look at Jodd Email. This is a small, but convenient wrapper over java mail library, that can help you with sending emails and attachments. As you can see in section 'Email using fluent API', you can do the following:
Email email = Email.create()
.from("from#foo.org")
.to("to#bar.com")
.subject("test")
.addText("Hello!")
.addHtml(
"<html><body><h1>Hey!</h1>" +
"<img src='cid:c.png'><h2>Hay!</h2></body></html>")
.embed(attachment().bytes(new File("d:\\c.png")))
.attach(attachment().file("d:\\b.jpg"));
In this example you can see two ways how you can attach your files: embedding them so they appear in HTML content, or common attaching. Of course, you don't have to use fluent interface, its just one option with this library.
The below code snippet is using to call my web service using restful API.
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
String uri= "https://127.0.0.1:8443/cas-server-webapp-3.5.0/login";
WebResource resource = client.resource(URLEncoder.encode(uri));
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("username", "suresh");
queryParams.add("password", "suresh");
resource.queryParams(queryParams);
ClientResponse response = resource.type(
"application/x-www-form-urlencoded").get(ClientResponse.class);
String en = response.getEntity(String.class);
System.out.println(en);
And getting this exception while running the above code
com.sun.jersey.api.client.ClientHandlerException: java.lang.IllegalArgumentException: URI is not absolute
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:680)
I googled many articles and did'nt get where i am doing wrong .
Side note :cas-server-webapp-3.5.0 war deployed on my machine in Apache tomacat7
An absolute URI specifies a scheme; a URI that is not absolute is said to be relative.
http://docs.oracle.com/javase/8/docs/api/java/net/URI.html
So, perhaps your URLEncoder isn't working as you're expecting (the https bit)?
URLEncoder.encode(uri)
For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: #Value annotation.
The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.
Maybe the problem only in your IDE encoding settings. Try to set UTF-8 everywhere:
In an API Key Authorization Scenario...
You may be performing the 2nd REST call after getting an AUTH_TOKEN and ENDPOINT_URL from the first REST call.
Check your concatenation of "<ENDPOINT_URL> + <API_METHOD_URI>", you may be sending only the API_METHOD_URI.
This happened to me using the Streamsets integration platform trying to connect to Oracle's Responsys API.
For me, I was getting this error, when configuation in yaml files, which composed my URL was changed. oops,