Generate Java class (Pojo) for parameters using WSDL url - java

I have a wsdl url using which I have to create a template file which has the list of the parameters for a particular API and create a pojo file for that request. I tried using soapui-api but I was unable to do so because of unable to fulfill the dependencies (Followed all the stackoverflow help to resolve the jar issues but it did not work):
Code:
WsdlProject project = new WsdlProject();
WsdlInterface[] wsdls = WsdlImporter.importWsdl(project, "http://XXXXX?wsdl");
WsdlInterface wsdl = wsdls[0];
for (com.eviware.soapui.model.iface.Operation operation : wsdl.getOperationList()) {
WsdlOperation wsdlOperation = (WsdlOperation) operation;
System.out.println("OP:"+wsdlOperation.getName());
System.out.println("Request:");
System.out.println(wsdlOperation.createRequest(true));
System.out.println("Response:"); System.out.println(wsdlOperation.createResponse(true));
}
Another approach in which I tried to parse the wsdl url using parser and get the list of names of the possible requests. I was able to get the request list but not the parameters required to create that request.
WSDLParser parser = new WSDLParser();
Definitions wsdl = parser.parse("http://XXXX?wsdl");
String str = wsdl.getLocalBindings().toString();
for(Message msg : wsdl.getMessages()) {
for (Part part : msg.getParts()) {
System.out.println(part.getElement());
}
}
Please help me on how to get the list of parameters from a wsdl url by either of the one approach.

well there are various stranded approach available for this , try and search for WS-import tool which is one of tools to do this .
This is the simple and best example here
WS_Import_tool
one more way of doing this is -
Apache_CFX
If you want to generate them using eclipse - that is also possible .
Check it out -
How do you convert WSDLs to Java classes using Eclipse?
What errors you are facing for SOAP UI
You can reffer this link for trouble shooting
Generate_java_from_Wsdl

Related

How to conevrt soap xml to custom obect

String example =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header /><soapenv:Body><ns2:farm xmlns:ns2=\"http://adamish.com/example/farm\"><horse height=\"123\" name=\"glue factory\"/></ns2:farm></soapenv:Body></soapenv:Envelope>";
Here is my soap xml in string format how i need to form it in a Farm object .Farm is my custom class,Any library is readly available
After Using This Code m getting the exception
SOAPMessage message = MessageFactory.newInstance().createMessage(null,
new ByteArrayInputStream(example.getBytes()));
Unmarshaller unmarshaller = JAXBContext.newInstance(Farm.class).createUnmarshaller();
SubscribeProductReq farm = (Farm)unmarshaller.unmarshal(message.getSOAPBody().extractContentAsDocument());
unexpected element (uri:"http://yyyyyy.yyyyy*********", local:"farm"). Expected elements are <{}farm>
You don't need to do much:
There are two ways to generate Client side java code for SOAP:
1) You must be getting this xml from some URL. So, Maven plugin gives you control over to generate jar from URL for SOAP.
2) You can diretly place SOAP xml into a file and put that file path in maven pom. Maven will generate client jar using Apache CXF.
Visit https://www.jetbrains.com/help/idea/generate-java-code-from-wsdl-or-wadl-dialog.html
visit https://objectpartners.com/2010/11/25/leveraging-apache-cxf-and-maven-to-generate-client-side-web-service-bindings/

Get EC2 Instance XML Description using AWS Java SDK?

We have a scenario in which we need to retrieve the description info for EC2 instances running on AWS. To accomplish this, we are using the AWS Java SDK. In 90% of our use case, the com.amazonaws.services.ec2.model.Instance class is exactly what we need. However, there is also a small use-case where it would be beneficial to get the raw XML describing the instance. That is, the XML data before it is converted into the Instance object. Is there any way to obtain both the Instance object and the XML string using the AWS Java SDK? Is there a way to manually convert from one to the other? Or, would we be forced to make a separate call using HttpClient or something similar to get the XML data?
Make an EC2Client by adding request handler and override the beforeUnmarshalling() method like below
AmazonEC2ClientBuilder.standard().withRegion("us-east-1")
.withRequestHandlers(
new RequestHandler2() {
#Override
public HttpResponse beforeUnmarshalling(Request<?> request, HttpResponse httpResponse) {
// httpResponse.getContent() is the raw xml response from AWS
// you either save it to a file or to a XML document
return new HTTPResponse(...);
// if you consumed httpResponse.getContent(), you need to provide new HTTPResponse
}
}
).build():
If you have xml (e.g. from using AWS rest API directly), then you can use com.amazonaws.services.ec2.model.transform.* classes to convert xml to java objects. Unfortunately, it only provides classes required for SDK itself. So you, for example, can convert raw XML to an Instance using InstanceStaxUnmarshaller, but can't convert Instance to XML unless you write such converter.
Here is an example how to parse an Instance XML:
XMLEventReader eventReader = XMLInputFactory.newInstance().createXMLEventReader(new StringReader(instanceXml));
StaxUnmarshallerContext suc = new StaxUnmarshallerContext(eventReader, new TreeMap<>());
InstanceStaxUnmarshaller isu = new InstanceStaxUnmarshaller();
Instance i = isu.unmarshall(suc);
System.out.println(i.toString());
You probably can try to intercept raw AWS response, so that you can keep raw XML while still using SDK most of the time. But I wouldn't call that easy as it will require quite a bit of coding.
You could use JAXB.marshal like following. JAXB (Java Architecture for XML Binding) could convert Java object to / from XML file.
StringWriter sw = new StringWriter();
JAXB.marshal(instance, sw);
String xmlString = sw.toString();
You can use AWS rest API to replace Java SDK. A bonus will be slight performance gain because you'll not send statistic data to Amazon as the SDK does.

Apache camel simple http example

I am pretty new with Camel. I have been trying to fetch a data from http source.
Here's my code:
from("timer://runOnce?repeatCount=1")
.to("http4://webservice.com/example.xml")
.process(new structureXML())
.to("mock:resource")
.stop();
And:
class structureXML implements Processor {
public void process(Exchange httpExchange) throws Exception {
String httpres = httpExchange.getIn().getBody(String.class);
String[] lines = httpres.split("\n");
Pattern p = Pattern.compile("<Map Key='(.+)' Value='(.+)'/>");
HashMap<String, Integer> mapdata = new HashMap<String, Integer>();
for(String line : lines) {
Matcher m = p.matcher(line);
if(m.find())
mapdata.put(m.group(1), Integer.parseInt(m.group(2)));
}
httpExchange.getIn().setBody(mapdata);
}
}
Well the example works right but I want to know about the possible ways to further improve this situation(e.g xml processing using xpath and etc), also I want to know about the ways which I can store the java object inside the message so I can use it in another route(e.g: direct:resource instead of mock)
About java objects:
More information can be found here: http://camel.apache.org/data-format.html
JAXB
XStream
BeanIO
JiBX
XmlBeans
These data formats will be very useful for transforming XML to POJO.
I recomend you to try BeanIO (detailed documentation, many examples, etc).
About Xpath:
it's hard to tell anything specified without web-service response.
Example:
setBody().xpath("/soap:Envelope/soap:Body/s:insertResponse/s:data",
XmlNamespaces.getNamespace()).
About your example:
You usually need to set a lot of properties and header (before http request), so it worked fine. Example:
setProperty(Exchange.CONTENT_TYPE).constant("application/soap+xml").
setProperty(Exchange.CONTENT_ENCODING).constant("gzip").
setProperty(Exchange.CHARSET_NAME).constant("utf-8").
setHeader(Exchange.CONTENT_TYPE).exchangeProperty(Exchange.CONTENT_TYPE).
And I don't see creating the request to web-service. It is easy to do with the help of velocity (http://camel.apache.org/velocity.html), or, maybe, using SOAP date format (http://camel.apache.org/soap.html).
You can use jetty (http://camel.apache.org/jetty.html) instead of http4 (for me it's easier)

How to read external JSON file from JMeter

Is there a way (any jmeter plugin) by which we can have the JMeter script read all the contents(String) from external text file ?
I have a utility in java which uses Jackson ObjectMapper to convert a arraylist to string and puts it to a text file in the desktop. The file has the JSON info that i need to send in the jmeter Post Body.
I tried using ${__FileToString()} but it was unable to deserialize the instance of java.util.ArrayList. It was also not reading all the values properly.
I am looking for something like csv reader where i just give the file location. I need all the json info present in the file. Need to extract it and assign to the post body.
Thanks for your help !!!
If your question is about how to deserialize ArrayList in JMeter and dynamically build request body, you can use i.e. Beanshell PreProcessor for it.
Add a Beanshell PreProcessor as a child of your request
Put the following code into the PreProcessor's "Script" area:
FileInputStream in = new FileInputStream("/path/to/your/serialized/file.ser");
ObjectInput oin = new ObjectInputStream(in);
ArrayList list = (ArrayList) oin.readObject();
oin.close();
in.close();
for (int i = 0; i < list.size(); i++) {
sampler.addArgument("param" + i, list.get(i).toString());
}
The code will read file as ArrayList, iterate through it and add request parameter like:
param1=foo
param2=bar
etc.
This is the closest answer I'm able to provide, if you need more exact advice - please elaborate your question. In the meantime I recommend you to get familiarized with How to use BeanShell: JMeter's favorite built-in component guide to learn about scripting in JMeter and what do pre-defined variables like "sampler" in above code snippet mean.

Java soap client to wsdl url

i want to call soap function with a few parameters. I did it python but how can i do it on java ?
my code on python :
url = 'http://78.188.50.246:8086/iskultur?singleWsdl'
client = Client(url)
d = dict(UserId='a', UserPass='b', Barkod=str(value))
result = client.service.Stok(**d)
return int(result)
how can i do it on java ?
Thanks for all
First you need to generate proxy classes. You can do that using wsimport (it's a Java SE tool):
wsimport -keep http://78.188.50.246:8086/iskultur?singleWsdl
This will generate classes (in packages) and place the results in the current directory. I tested your URL and it generated two package hierarchies (one starting in 'org' and the other in 'com'). The command above will keep the source code, so you can move those directories to your Java project source path (later you should include this code generation step in your build process).
with the generated classes in your classpath, you now create a Service instance from your WSDL (passing the URL and the namespace qualified name of your service). I got that information from the WSDL.
URL wsdlLocation = new URL("http://78.188.50.246:8086/iskultur?singleWsdl");
QName serviceName = new QName("http://tempuri.org/", "EbWCFtoLogo");
Service service = Service.create(wsdlLocation, serviceName);
Then you get a proxy where you can call your SOAP methods with Service.getPort() passing the interface of the port (IEbWCFtoLogo). Now you have a reference where you can call your remote SOAP methods.
IEbWCFtoLogo proxy = service.getPort(IEbWCFtoLogo.class);
The wsimport tool generated a stok() method that receives 3 parameters. I called with some of the values you used and it returned -1.0 in the code below:
double value = proxy.stok("a", "b", "code");
System.out.println("Result: " + value);

Categories