AXIS 2 : java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl cannot be cast to org.apache.axiom.om.OMElement - soap

I am using AXIS2 as client for handling SOAP response. The client stubs are generated using WSDL2JAVA command. To solve an issue, I am trying to read an xml response stored in .xml file in the generated stub, and assign to SOAPEnvelope. Below is the code written to load .xml content :
InputStream is = new ByteArrayInputStream((sb.toString()).getBytes());
javax.xml.parsers.DocumentBuilderFactory factory = avax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
javax.xml.parsers.DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(is);
System.out.println("Got Document ..............");
is.close();
org.apache.axis2.saaj.util.SAAJUtil su = new org.apache.axis2.saaj.util.SAAJUtil();
org.apache.axiom.soap.SOAPEnvelope _returnEnv1 = su.getSOAPEnvelopeFromDOOMDocument(doc);
Am getting ClassCastException at the last line in the code (assigning to SOAPEnvelope).
Can someone please help me with this.

Axis2clients are used to send requests and receive response. Why are you trying to load response from a file? You should receive the response from the backend service. Check this guide to get to know about the clientapi. You can find detail guide in axis2 documentation also.

Related

mocking a request with a payload using wiremock

I'm currently trying to mock external server using Wiremock.
One of my external server endpoint takes a payload.
This endpoint is defined as follow :
def sendRequestToMockServer(payload: String) = {
for {
request_entity <- Marshal(payload).to[RequestEntity]
response <- Http().singleRequest(
HttpRequest(
method = HttpMethods.GET,
uri = "http://localhost:9090/login",
entity = request_entity
)
)
} yield {
response
}
}
To mock this endpoint using Wiremock, I have written the following code :
stubFor(
get(urlEqualTo("/login"))
.willReturn(
aResponse()
.withHeader("Content-Type","application/json")
.withBodyFile("wireMockResponse.json")
.withStatus(200)
)
.withRequestBody(matchingJsonPath("requestBody.json"))
)
where I Have defined the request body in the requestBody.json file.
But when I run tests , I keep getting an error indicating that the requested Url is not found.
I'm thinking that the error is related to this line withRequestBody(matchingJsonPath("requestBody.json")), because when I comment it the error disappear.
Any suggestions on how to work around this?
matchingJsonPath does not populate a file at a provided filepath, but instead evaluates the JsonPath provided. See documentation.
I'm not entirely sure there is a way to provide the request body as a .json file. If you copy the contents of the file into the withRequest(equalToJson(_yourJsonHere_)), does it work? If it does, you could get the file contents as a JSON string above the definition and provide it to the function (or I guess, make a function to return a JSON string from a .json file).
Additionally, you could make a custom request matcher that does the parsing for you. I think I'd recommend this only if the above does not work.

HttpWebRequest.GetRequestStream() is not working in MS Dynamics CRM Plugin

I have written a plugin wherein I am trying to get an XML response.
This is my code :
// Set the Method property of the request to POST.
string strXMLServer = "xxx";
var request = (HttpWebRequest)WebRequest.Create(strXMLServer);
request.Method = "POST";
// Set the ContentType property of the WebRequest.
request.ContentType = "xyz";
// Assuming XML is stored in strXML
byte[] byteArray = Encoding.UTF8.GetBytes(strXML);
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
//(LINE 5) Get the request stream
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
This code works fine when its written in a console application. But when I copy the same code to a class library(plugin) and tries to debug it using plugin profiler, the application gets stopped abruptly when it reaches (LINE 5)
i.e. At Stream dataStream = request.GetRequestStream();
request.GetRequestStream() function is not working with plugin, but works fine within a console.
Any help would be appreciated :)
Thanks in advance
Note: I am using Dynamics 365 online trial version
There are a couple of things to take into consideration when building a plugin with web requests. Firstly, you need to use WebClient as it's widely supported by Microsoft products.
Secondly, your URL needs to be a DNS name and not an IP address, as this is a hosted plugin in sandbox mode.
Example from Microsoft's website: https://msdn.microsoft.com/en-us/library/gg509030.aspx
Reading material: https://crmbusiness.wordpress.com/2015/02/05/understanding-plugin-sandbox-mode/

Error when uploading file with OpenMeetings' importFile REST method

I installed 3.0.3 OpenMeetings to test access via REST interface, everything worked ok for the methods in UserService and RoomService. But, when I try to upload a pdf file by ImportFile method (FileService), OpenMeetings returns an object FileImportError stating that the file is damaged, and that this may have occurred during the file transfer via http.
When I try to import the same file using the flex application of OpenMeetings everything works right. I'm using Ruby to call the method of ImportFile OpenMeeting, and to test whether my application is wrong, I called the method using Firefox and got the same error.
I am using the following method call (sample only, not the real ruby code):
ImportFile (SID externalUserId, externalFileId, externalType, room_id, isOwner, path,
parentFolderId, fileSystemName)
SID = one string with the ID of the session
externalUserId = 'extuser' (string)
externalType = 'exttype' (string)
room_id = 2 (existing room in OpenMeetings)
isOwner = false
path = 'http://10.1.1.25/default.pdf' (The path to the file on an Apache server)
parentFolderId = 0
fileSystemName = 'default.pdf'
Also used Eclipse in remote debug to see what was happening and realized that the problem occurs in the conversion of the received file.
I would appreciate some help to solve the problem.
Thanks,
Fernando

RestSharp Usage

Recently I was using RestSharp to consume my Restful Resouce. and expected exchanging data with JSon between server and client. Below is my C# code.
var client = new RestSharp.RestClient();
var request = new RestRequest(sUrl,Method.POST);
request.RequestFormat = DataFormat.Json;
request.Timeout = TIME_OUT_MILLISECONTS ;
request.AddHeader("Content-Type", "application/json");
request.AddBody(new { appID = sAppId, loginName = sUserName, password=sPassword });
var response = client.Execute(request);
string s=response.Content;//It is always XML format.
The result is not what I expected for(Json data format), although I had set the RequestFormat Json and add Http header Content-Type. So I decided to use the .Net Reflector to found out What happened in the RestClient.Execute method. Here is the code of the method.
public RestClient()
{
...
this.AddHandler("application/json", new JsonDeserializer());
this.AddHandler("application/xml", new XmlDeserializer());
this.AddHandler("text/json", new JsonDeserializer());
this.AddHandler("text/x-json", new JsonDeserializer());
this.AddHandler("text/javascript", new JsonDeserializer());
this.AddHandler("text/xml", new XmlDeserializer());
this.AddHandler("*", new XmlDeserializer());
...
}
I have some questions about it:
As the RestClient adds many kinds of Content-Type into the HttpWebRequest. Is it right way to build a Request? And I think Maybe that is the reason why Response.Content always XML.
I don't know why the RestClient needs to build a HttpWebRequest like that. Any meaning to do that?
If we specified both JSon and XMl message format in a Http Request, which one works finally? Is it allowed?
Thanks. Have a good day.
RestSharp will use the correct handler based on the content type of the response. That's what those AddHandlers are doing; its configuring the RestClient to accept certain content types in the response and mapping those types to deserializers. Normally you would want to set an accept header for the json content type which notifies the server to send json in the response.
request.AddHeader("Accept", "application/json")
Of course, this assumes that the server you are hitting is configured to respond with json.

How to retrieve inputStream from the server using fileUploader and GWT 2.4?

I have a fileUploader widget that I'm using to select an xml file. I then have a button that calls my handler in the viewImpl class when the user submits the selected file. If I understand things correctly, from there I do a submit from the formPanel and the file is on the server.
#UiHandler("calculateComplexityButton")
void onClickCalculateComplexity(ClickEvent e){
formPanel.submit();
//How do I get the inputStream back to here????
presenter.getTask(inputStream);
}
My problem is how do I get the inputStream off the server? I tried using an RPC call for all this, but when I try to get the inputStream I'm not pulling anything off the server. I tried:
inputStream = request.getInputStream();
but it appears to be empty. Any ideas on this?
I dropped the RPC code and used a simple HTTPRequest I found here. That gets me to the servlet, but the request doesn't have the file stream. When I reach this line in the code:
FileItemIterator iter = upload.getItemIterator(request); //Nothing is here in iter.
You can not make an upload via RPC, thats why you have to submit your form to a servlet.
final FormPanel form = new FormPanel();
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
form.setAction("/upload");
So, when you do form.submit() it will send your file to the Action(Servlet). In the server side you can use the lib form apache (commons-fileupload). You have many different way to get your file, you can save on disk, read on memory....