Read the Axis2 output from client (Stub) - axis2

I am getting value till toEnvelope method. when I try to read from axisclient(WS client)
am getting null value.
System.out.println("toEnvelope :"+param.getOTA_VehCancelRSSequence_type0().getVehCancelRSCore().getUniqueID().getID());
org.apache.axiom.soap.SOAPEnvelope emptyEnvelope = factory.getDefaultEnvelope();
Please help me to over come this

You can get the last OperationContext using the getLastOperationContext() method from the client.
For outgoing messages:
OperationContext operationContext = stub._getServiceClient().getLastOperationContext();
if (operationContext != null) {
MessageContext outMsgContext = operationContext.getMessageContext("Out");
if (outMsgContext != null) {
System.out.println("Out SOAP Message : "+outMsgContext.getEnvelope().toString());
}
}
For incoming messages:
OperationContext operationContext = stub._getServiceClient().getLastOperationContext();
if (operationContext != null) {
MessageContext inMsgContext = operationContext.getMessageContext("In");
if (inMsgContext != null) {
System.out.println("Received SOAP Message: "+ inMsgContext.getEnvelope().toString());
}
}

Related

Webhook Subscription for Teams Conversation not working with WCF Relay

Can someone please help me to fix this Issue. I am not able to debug from where it is going wrong. Basically I have created a WCF Rest API WebService using WCF Relay in Azure to have hybrid connection between on-premise and Azure. Also if I am ignoring any certificate validation, that endpoint is for on-premise as it is self-signed certificate but when making API call, I am using the base64 encoded public key provided by WCF Relay when publishing it in Azure.
WCF Contract And Implementation:
Contract Interface
Implementation
I am successfully able to get the "validationToken" in the WCF service and also returning the same validationToken immediately below 5 seconds. After returning, it always error out showing this message.
Postman Client For Sending HTTP Request
Error Response and no subscription created
EDIT
WCF Contract
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "webhookForConservation?validationToken={validationToken}",
BodyStyle = WebMessageBodyStyle.Bare)]
string webhookForConservation(WebhookPayload data, string validationToken);
WCF Implementation:
1st approach to return 200 OK status code:
public string webhookForConservation(WebhookPayload data, string validationToken = "")
{
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "text/plain");
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
HttpResponseMessage response = null;
WebOperationContext ctx = WebOperationContext.Current;
if (validationToken != null && validationToken != "")
{
response = client.PostAsync("http://localhost:8080/conversationWebHook/conversationSubscription?validationToken=" + validationToken, null).Result;
var apiContent = response.Content.ReadAsStringAsync().Result;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
ctx.OutgoingResponse.ContentType = "text/plain";
return apiContent;
}
else
{
StringContent strContent = new StringContent(DataContractJsonSerializerHelper.SerializeJson(data));
strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
response = client.PostAsync("http://localhost:8080/conversationWebHook/conversationSubscription", strContent).Result;
}
var result = (response != null) ? response.Content.ReadAsStringAsync().Result : "";
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
return result;
}
2nd Approach to return 200 status code:
public WebFaultException<string> webhookForConservation(WebhookPayload data, string validationToken="")
{
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Accept", "text/plain");
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
HttpResponseMessage response = null;
if (validationToken != null && validationToken != "")
{
response = client.PostAsync("http://localhost:8080/conversationWebHook/conversationSubscription?validationToken=" + validationToken, null).Result;
var apiContent = response.Content.ReadAsStringAsync().Result;
return new WebFaultException<string>(apiContent, HttpStatusCode.OK);
}
else
{
StringContent strContent = new StringContent(DataContractJsonSerializerHelper.SerializeJson(data));
strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
response = client.PostAsync("http://localhost:8080/conversationWebHook/conversationSubscription", strContent).Result;
}
var result = (response != null) ? response.Content.ReadAsStringAsync().Result : "";
return new WebFaultException<string>(result, HttpStatusCode.OK); ;
}
Same error seen after returning 200 OK response code from WCF Service
Calling Relay WCF API directly with Postman:
Headers:
Thank you in advance for all the help.
Two problems were preventing the WCF relay to work properly:
The relay wasn't setting the response content type to text/plain, this was fixed with ctx.OutgoingResponse.ContentType = "text/plain"
The relay was adding an XML wrapper to the required response body, this was addressed by changing the return value to Stream

Apache HttpClient - Default protocol

I am using Apache HttpClient to send a POST requests. How can I determine which PROTOCOL my Apache HttpClient instance is using for sending "https://" requests. I use following code block to send my POST requests.
public void sendPostURL(String url, HashMap<String, String>params, String user, String pass) {
HttpClient client = new HttpClient();
String urlContent = "";
PostMethod method = new PostMethod("https://...");
// Prepare connection information
client.getParams().setParameter("http.useragent", "MyApp");
if ( (user != null) &&(pass != null) ) {
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, (new UsernamePasswordCredentials(user, pass)));
}
// Prepare parameters
for (Map.Entry<String, String> entry : params.entrySet()) {
method.addParameter(entry.getKey(), ((entry.getValue() != null) ? entry.getValue().toString() : ""));
}
try{
// HTTP execution
int returnCode = client.executeMethod(method);
} catch (Exception e) {
// Exception
e.printStackTrace();
} finally {
method.releaseConnection();
}
}
Please guide me on how can I get the PROTOCOL that HttpClient is using to send the request. Also how can I override the PROTOCOL used. Hoping for a solution. Thanks in advance.
The protocol is HTTPS, is it not ?

Restlet: Get response body on failed get()

I am trying to debug a particular connection that responds with a Unauthorized (401). In Restlet this causes Respresentation.get() to throw an error.
What I want to do is get the response body as this particular api gives you greater error information in the body.
Any suggestions?
Thanks,
Luke
I would be reluctant to reccomend it for production but certainly for debugging you can override handleInbound in ClientResource to change the conditions under which an error is thrown. Restlet will then return the body, in the usual way.
ClientResource clientResource = new ClientResource("http://your.url") {
#Override
public Representation handleInbound(Response response) {
Representation result = null;
if (response.getRequest().isSynchronous()) {
if (response.getStatus().isError()
&& !Status.CLIENT_ERROR_UNAUTHORIZED.equals(response.getStatus())) {
doError(response.getStatus());
} else {
result = (response == null) ? null : response.getEntity();
}
}
return result;
}
};
Representation response = clientResource.get();
System.out.println(response.getText());

I can't send byte array as parameter in REST service ? ( code attached )

I'm using WCF to create some REST service.
One of the Rest Service method need to get byte array as parameter ( picture as byte array ) and return some object.
I run this service using IIS.
But this is not working.
The code that i wrote :
[ServiceContract]
public interface IPicService
{
[OperationContract, WebInvoke(Method="POST", UriTemplate = "GetPicReport/{imageName}")]
Report GetPicReport( string imageName, Stream image );
}
[ServiceBehavior( AddressFilterMode = AddressFilterMode.Any )]
public class PicService: IPicService
{
public Report GetPicReport( string imageName, Stream image )
{
return new Report ();
}
}
I checking this code using explorer - but i get an error about missing parameter ( the image stream )
How can i test it ?
I can't use the WCF Test Client - so i wrote simple application that create http call - and this method return error 404 ( server not found )
Can you try the below code:
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "text/xml";
request.Method = method;
}
//var objContent = HttpContentExtensions.CreateDataContract(requestBody);
if(method == "POST" && requestBody != null)
{
//byte[] requestBodyBytes = ToByteArrayUsingXmlSer(requestBody, "http://schemas.datacontract.org/2004/07/XMLService");
byte[] requestBodyBytes = ToByteArrayUsingDataContractSer(requestBody);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
//request.Timeout = 60000;
}
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
The post here shows how to implement a service just like yours, along with a test client (using HttpWebRequest). Another thing you can do is to enable tracing at the server, it may tell you why the request is being rejected.

How can I change message in DuplexSessionChannel (tcpTransport) in WCF custom channel?

I implement IDuplexSessionChannel on my Custom Channel because I use tcpTransport. In that custom channel, I cache service call response(client side caching). But it has errors. In IRequestChannel it works fine. How can I change message in TryMessage method. My code :
public Message Receive(TimeSpan timeout)
{
Message response = null;
response = CommunicationCacheManager.Get(_request.Headers.Action, _request);
if (response == null)
{
response = this.InnerChannel.Receive(timeout);
int cacheTimeout = 0;
if (response.Headers.FindHeader(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE) > -1)
{
cacheTimeout = response.Headers.GetHeader<int>(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE);
}
if (cacheTimeout > 0 && response != null &&
!response.IsFault &&
!response.IsEmpty)
{
CommunicationCacheManager.Add(_request.Headers.Action, cacheTimeout, ref response);
}
}
return response;
}
public Message Receive()
{
return this.InnerChannel.Receive();
}
public bool TryReceive(TimeSpan timeout, out Message message)
{
ThrowIfDisposedOrNotOpen();
message = null;
bool timedout = false;
try
{
message = this.Receive(timeout);
}
catch (TimeoutException)
{
timedout = true;
}
return (!timedout);
}
CacheManager works. And I get the response Cache. But tryReceive run again and when I look Message. Message is closed. How can I fix that
Problem is solved.
Tcp Binding add RelatesTo Header to Message. So code is changed to
public Message Receive(TimeSpan timeout)
{
Message response = null;
response = CommunicationCacheManager.Get(_request.Headers.Action, _request);
if (response == null)
{
response = this.InnerChannel.Receive(timeout);
int cacheTimeout = 0;
if (response.Headers.FindHeader(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE) > -1)
{
cacheTimeout = response.Headers.GetHeader<int>(Constants.CacheTimeOutHeader.NAME, Constants.CacheTimeOutHeader.NAMESPACE);
}
if (cacheTimeout > 0 && response != null &&
!response.IsFault &&
!response.IsEmpty)
{
CommunicationCacheManager.Add(_request.Headers.Action, cacheTimeout, ref response);
}
}
else
{
response.Headers.RelatesTo=_request.Header.MessageId;
}
return response;
}