Below is the java program i have written in the client side to receive & encrypt part of the XML message that is sent in the SOAP interface.
SOAPBindingMessageContext soapbindingmessagecontext = (SOAPBindingMessageContext) iContext;
javax.xml.soap.SOAPMessage soapMessage = soapbindingmessagecontext.getRequestMessage();
Iterator iterator = soapMessage.getMimeHeaders().getAllHeaders();
while (iterator.hasNext()) {
MimeHeader header = (MimeHeader) iterator.next();
System.out.println(header.getName());
System.out.println(header.getValue().toString());
if (header.getName().equalsIgnoreCase("SOAPAction")) {
System.out.println("The soapAction is : " + header.toString());
operationName = header.getValue().replaceAll("\"", "");
}
}
if (debug) {
System.out.println(operationName);
}
However it looks like the operationName (soapAction in the WSDL) is null & not being extracted from the SOAP Message. I have confirmed from the logs that other MIME-headers can be extracted. Just the soapAction i am not able to extract. I have also confirmed from the soapUI that the soapAction is really sent and is not null when sending. Below is the snap of same. Could you please help me to understand where i am doing wrong ?
Related
I work on university project in java. I have to download attachments from new emails using GMAIL API.
I successfully connected to gmail account using OAuth 2.0 authorization.
private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_READONLY);
I tried to get unseen mails using
ListMessagesResponse listMessageResponse = service.users().messages().list(user).setQ("is:unseen").execute();
listMessageResponse is not null but when I call method .getResultSizeEstimate() it returns 0
also I tried to convert listMessageResponse to List < Message > (I guess this is more usable) using
List<Message> list = listMessageResponse.getMessages();
But list launches NullPointerException
Then tried to get each attachment with
for(Message m : list) {
List<MessagePart> part = m.getPayload().getParts();
for(MessagePart p: part) {
if(p.getFilename()!=null && p.getFilename().length()>0) {
System.out.println(p.getFilename()); // Just to check attachment filename
}
}
}
Is my approach correct (if not how to fix it) and how should I download those attachments.
EDIT 1:
Fixed q parameter, I mistakenly wrote is:unseen instead of is:unread.
Now app reaches unread mails successfully.
(For example there was two unread mails and both successfully reached, I can get theirs IDs easy).
Now this part trows NullPointerException
List<MessagePart> part = m.getPayload().getParts();
Both messages have attachments and m is not null (I get ID with .getID())
Any ideas how to overcome this and download attachment?
EDIT 2:
Attachments Downloading part
for(MessagePart p : parts) {
if ((p.getFilename() != null && p.getFilename().length() > 0)) {
String filename = p.getFilename();
String attId = p.getBody().getAttachmentId();
MessagePartBody attachPart;
FileOutputStream fileOutFile = null;
try {
attachPart = service.users().messages().attachments().get("me", p.getPartId(), attId).execute();
byte[] fileByteArray = Base64.decodeBase64(attachPart.getData());
fileOutFile = new FileOutputStream(filename); // Or any other dir
fileOutFile.write(fileByteArray);
fileOutFile.close();
}catch (IOException e) {
System.out.println("IO Exception processing attachment: " + filename);
} finally {
if (fileOutFile != null) {
try {
fileOutFile.close();
} catch (IOException e) {
// probably doesn't matter
}
}
}
}
}
Downloading working like charm, tested app with different type of emails.
Only thing left is to change label of unread message (that was reached by app) to read. Any tips how to do it?
And one tiny question:
I want this app to fetch mails on every 10 minutes using TimerTask abstract class. Is there need for manual "closing" of connection with gmail or that's done automatically after run() method iteration ends?
#Override
public void run(){
// Some fancy code
service.close(); // Something like that if even exists
}
I don't think ListMessagesResponse ever becomes null. Even if there are no messages that match your query, at least resultSizeEstimate will get populated in the resulting response: see Users.messages: list > Response.
I think you are using the correct approach, just that there is no message that matches your query. Actually, I never saw is:unseen before. Did you mean is:unread instead?
Update:
When using Users.messages: list only the id and the threadId of each message is populated, so you cannot access the message payload. In order to get the full message resource, you have to use Users.messages: get instead, as you can see in the referenced link:
Note that each message resource contains only an id and a threadId. Additional message details can be fetched using the messages.get method.
So in this case, after getting the list of messages, you have to iterate through the list, and do the following for each message in the list:
Get the message id via m.getId().
Once you have retrieved the message id, use it to call Gmail.Users.Messages.Get and get the full message resource. The retrieved message should have all fields populated, including payload, and you should be able to access the corresponding attachments.
Code sample:
List<Message> list = listMessageResponse.getMessages();
for(Message m : list) {
Message message = service.users().messages().get(user, m.getId()).execute();
List<MessagePart> part = message.getPayload().getParts();
// Rest of code
}
Reference:
Class ListMessagesResponse
Users.messages: list > Response
Have some legacy code that works with Java 6 but not fully with Java 8. It sends a SOAP request and reads the response. When using Java 8, the response is not correctly parsed and the code returns a failed result.
Here is a simplified version of the code, I have cut out most of the request building code and changed server names and the like. Please pardon any typos.
try {
// Init the factories
SOAPConnectionFactory SOAPConnFac = SOAPConnectionFactory.newInstance();
SOAPFactory SOAPFac = SOAPFactory.newInstance();
MessageFactory MessageFac = MessageFactory.newInstance();
// Create the SOAP Connection
SOAPConnection SOAPConn = SOAPConnFac.createConnection();
// Build the SOAP request message
SOAPMessage SOAPRequestMsg = MessageFac.createMessage();
// Add info to the MIME header for .NET compatibility
MimeHeaders hd = SOAPRequestMsg.getMimeHeaders();
hd.addHeader("SOAPAction", "http://www.mysever.com/respond");
// Remove the SOAP message header, it is not needed in this case
SOAPHeader SOAPRequestHeader = SOAPRequestMsg.getSOAPHeader();
SOAPRequestHeader.detachNode();
// Build the SOAP body main element CheckIt
SOAPBody SOAPRequestBody = SOAPRequestMsg.getSOAPBody();
javax.xml.soap.Name nameRequestBody = SOAPFac.createName("CheckIt", "", "http://www.myserver.com/");
SOAPBodyElement sbeRequestBodyEle = SOAPRequestBody.addBodyElement(nameRequestBody);
// Add all child elements to the CheckIt element
SOAPElement seNameNode = sbeRequestBodyEle.addChildElement("Name");
seNameNode.addChildElement("FirstName").addTextNode("mary");
seNameNode.addChildElement("LastName").addTextNode("smith");
sbeRequestBodyEle.addChildElement("ID").addTextNode("3423");
URL urlWebService = new URL ("http://webserver/BGC/");
// Send the SOAP request message and get back the SOAP response message
SOAPMessage SOAPResponseMsg = SOAPConn.call(SOAPRequestMsg, urlWebService);
SOAPConn.close();
// Pull out the SOAP response body
SOAPBody SOAPResponseBody = SOAPResponseMsg.getSOAPBody();
// Check for SOAP faults
if (SOAPResponseBody.hasFault()) {
SOAPFault newFault = SOAPResponseBody.getFault();
strStatus = "SOAP FAULT:<br>";
strStatus += "<br>code = " + newFault.getFaultCodeAsName();
strStatus += "<br>message = " + newFault.getFaultString();
strStatus += "<br>actor = " + newFault.getFaultActor()+"<br>";
boolOK = false;
} else {
// Pull the CheckProspectResponse element out of the SOAP response body
javax.xml.soap.Name nameResponseBody = SOAPFac.createName("CheckResponse", "", "http://www.mysever.com/");
Iterator iterElement = SOAPResponseBody.getChildElements(nameResponseBody);
if (iterElement.hasNext()){
SOAPBodyElement sbeResponseBodyEle = (SOAPBodyElement) iterElement.next();
// Check for success or failure
String strResultMsg = ((sbeResponseBodyEle.getValue() == null) ? sbeResponseBodyEle.toString() : sbeResponseBodyEle.getValue());
strStatus = "Check response came back from webserver as *" + strResultMsg + "*<br>";
boolOK = (strResultMsg.trim().toUpperCase().indexOf("SUCCESS") > 0);
} // End if (iterElement.hasNext())
} // End if (SOAPResponseBody.hasFault())
} catch(Exception e) {
strStatus = "Error : "+((e.getMessage() != null) ? e.getMessage() : e.toString());
boolOK = false;
} // End try
It seems that when pulling elements out of the response, it gets an empty set.
Iterator iterElement = SOAPResponseBody.getChildElements(nameResponseBody);
Returns a set of null elements. Not a null itself, the set has at least one member but that member is null. It should have a value of "SUCCESS" but it's null. I have looked at the full response and it looks fine, everything is there and it works with Java 6, just not with Java 8. A typical, successful response looks like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<CheckResponse xmlns="http://www.mysever.com/">
<CheckResult>SUCCESS</CheckResult>
</CheckResponse>
</soap:Body>
</soap:Envelope>
UPDATE
I have found a way around my problem, using getTextContent I get the correct data, or at least the data I expect to get. Given the above SOAP response, Java 8 returns the following for the given method call:
getValue = null
getNodeValue = null
getLocalName = CheckResponse
getNodeName = CheckResponse
getNamespaceURI = http://www.mysever.com/
getPrefix = null
getTextContent = SUCCESS
Acording to both Java 6 and Java 8 docs, the returned value for getValue should be "SUCCESS" in this case. Which is true for Java 6 but false for Java 8.
Any ideas on why this method works with Java 6 but not with Java 8? Is this a bug?
I'm using the SoapUI API as part of an existing java project.
The application should save the request and response XML in an specific report file.
I wonder if it's possible to get those requests and responses via the API.
The method invoking the TestCaseRunner looks like this
protected void checkTestCase(TestCase testCase) {
TestCaseRunner tr = testCase.run(null, false);
for (TestStepResult tcr : tr.getResults()) {
String status = tcr.getStatus();
String time = tcr.getTimeTaken() + "ms";
/* How to get XML messages?
* String request =
* String response =
*/
}
}
Depending on exactly what kind of test steps you have they might be an instance of a MessageExchange. Casting the TestStepResult to a MessageExchange and calling getRequestContent / getResponseContent might do the trick.
String request = ((MessageExchange)tcr).getRequestContent();
String response = ((MessageExchange)tcr).getResponseContent();
I have used the following way to get the response from the API CAll performed:
runner = testRunner.runTestStepByName("Your Test Case name");
// Here we take the response in ms of the API call
timeTaken = runner.response.timeTaken;
// here we get the HTTP response code.
responseCode = runner.getResponseHeaders()."#status#";
// here we get the response content
String response = runner.getResponseContent();
// here we get the API call endpoint -> in case you need to print it out.
String endPoint = runner.getEndpoint();
I want to send the data to person object. How to do it with PostMethod.
def payload ='<person><nationalId>'+1234567+'</nationalId></person>'
def method = new PostMethod(url)
def client = new HttpClient()
payload = payload.trim()
method.addRequestHeader("Content-Type","text/xml")
method.addRequestHeader("Accept","text/xml,application/xml;q=0.9")
Credentials credentials = new UsernamePasswordCredentials('simple', 'simple');
client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST,8080, AuthScope.ANY_REALM, "digest"),credentials);
method.setRequestEntity(new StringRequestEntity(payload))
def statusCode = client.executeMethod(method)
println "STATUS CODE : ${statusCode}"
def resultsString = method.getResponseBodyAsString()
method.releaseConnection()
println resultsString
I tried above coding. How to set password and username and password digest also. For that i think status code 400 is coming.Please notify where i made mistake
Try to look at REST Client Builder Plugin. See docs and I guess, you'll find more convenient way to send request
When I send a SOAP request using SAAJ API, I would receive a large SOAP response, in which I need to search for some nodes.
I am using following code but it just show the name of first node of body (HotelListResponse which has many children) and I have noticed that the loop just iterates once, (as shown in commented section).
In short: I need to know how to search for some nodes (preferably by their name) in a variable which its type is SOAPMessage. Thanks
SOAPMessage sm = response; //this is the response
sm.writeTo(System.out); //response is shown successfully in console
SOAPBody ReBody = sm.getSOAPBody();
Iterator sentIt = ReBody.getChildElements(); //create an iterator on elements
int counter=0;
while(sentIt.hasNext())
{
SOAPBodyElement sentSBE = (SOAPBodyElement)sentIt.next();
Iterator sentIt2 = sentSBE.getChildElements();
SOAPElement sentSE = (SOAPElement)sentIt2.next();
String sentID = sentSE.getNodeName(); //result is HotelListResponse
counter++;
//System.out.println("sentID:"+sentID);
}
System.out.println("counter"+counter); //result is 1