I am using soap service to authenticate request by sabre as in the document https://developer.sabre.com/docs/read/soap_basics/Authentication.
I generate the proxy classes using wsdl. i put authentication credential in the code. This is my Code for test purpose:
using ConsoleApplication1.SessionReference1;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
[STAThread]
static void Main(string[] args)
{
try
{
// Set user information, including security credentials and the IPCC.
string username = "my-username";
string password = "my-password";
string ipcc = "not-understand";
string domain = "EXT";
string temp = Environment.GetEnvironmentVariable("tmp"); // Get temp directory
string PropsFileName = temp + "/session.properties"; // Define dir and file name
DateTime dt = DateTime.UtcNow;
string tstamp = dt.ToString("s") + "Z";
//Create the message header and provide the conversation ID.
MessageHeader msgHeader = new MessageHeader();
msgHeader.ConversationId = "TestSession"; // Set the ConversationId
From from = new From();
PartyId fromPartyId = new PartyId();
PartyId[] fromPartyIdArr = new PartyId[1];
fromPartyId.Value = "WebServiceClient";
fromPartyIdArr[0] = fromPartyId;
from.PartyId = fromPartyIdArr;
msgHeader.From = from;
To to = new To();
PartyId toPartyId = new PartyId();
PartyId[] toPartyIdArr = new PartyId[1];
toPartyId.Value = "WebServiceSupplier";
toPartyIdArr[0] = toPartyId;
to.PartyId = toPartyIdArr;
msgHeader.To = to;
//Add the value for eb:CPAId, which is the IPCC.
//Add the value for the action code of this Web service, SessionCreateRQ.
msgHeader.CPAId = ipcc;
msgHeader.Action = "SessionCreateRQ";
Service service = new Service();
service.Value = "SessionCreate";
msgHeader.Service = service;
MessageData msgData = new MessageData();
msgData.MessageId = "mid:20001209-133003-2333#clientofsabre.com1";
msgData.Timestamp = tstamp;
msgHeader.MessageData = msgData;
Security security = new Security();
SecurityUsernameToken securityUserToken = new SecurityUsernameToken();
securityUserToken.Username = username;
securityUserToken.Password = password;
securityUserToken.Organization = ipcc;
securityUserToken.Domain = domain;
security.UsernameToken = securityUserToken;
SessionCreateRQ req = new SessionCreateRQ();
SessionCreateRQPOS pos = new SessionCreateRQPOS();
SessionCreateRQPOSSource source = new SessionCreateRQPOSSource();
source.PseudoCityCode = ipcc;
pos.Source = source;
req.POS = pos;
SessionCreatePortTypeClient s = new SessionCreatePortTypeClient();
SessionCreateRS resp = s.SessionCreateRQ(ref msgHeader, ref security, req);
//SessionCreateRQService serviceObj = new SessionCreateRQService();
//serviceObj.MessageHeaderValue = msgHeader;
//serviceObj.SecurityValue = security;
//SessionCreateRS rs = new SessionCreateRS();
//SessionCreateRS = serviceObj.SessionCreateRQ(req); // Send the request
if (resp.Errors != null && resp.Errors.Error != null)
{
Console.WriteLine("Error : " + resp.Errors.Error.ErrorInfo.Message);
}
else
{
// msgHeader = serviceObj.MessageHeaderValue;
// security = serviceObj.SecurityValue;
Console.WriteLine("**********************************************");
Console.WriteLine("Response of SessionCreateRQ service");
Console.WriteLine("BinarySecurityToken returned : " + security.BinarySecurityToken);
Console.WriteLine("**********************************************");
string ConvIdLine = "convid=" + msgHeader.ConversationId; // ConversationId to a string
string TokenLine = "securitytoken=" + security.BinarySecurityToken; // BinarySecurityToken to a string
string ipccLine = "ipcc=" + ipcc; // IPCC to a string
// File.Delete(PropsFileName); // Clean up
// TextWriter tw = new StreamWriter(PropsFileName); // Create & open the file
// tw.WriteLine(DateTime.Now); // Write the date for reference
// tw.WriteLine(TokenLine); // Write the BinarySecurityToken
// tw.WriteLine(ConvIdLine); // Write the ConversationId
// tw.WriteLine(ipccLine); // Write the IPCC
// tw.Close();
//Console.Read();
}
}
catch (Exception e)
{
Console.WriteLine("Exception Message : " + e.Message);
Console.WriteLine("Exception Stack Trace : " + e.StackTrace);
Console.Read();
}
}
}
}
Please Help me
I didn't check the sequence of the code in detail, but checking the values you set for organization and domain:
string ipcc = "not-understand";
string domain = "EXT";
Unless you did it intentionally to mask the values, you should have received your ipcc value from Sabre after getting a SOAP webservices account.
The value for SOAP APIs domain is normally "DEFAULT".
Registering on dev studio only gives you REST test credentials (not SOAP), so you can use this form to request SOAP test credentials:
https://developer.sabre.com/contact
Finally, I don't quite see the environment/target url you're using to test the SessionCreate service...CERT one is: https://sws3-crt.cert.sabre.com/
Related
I am new in AWS and Asp NetCore. Help me to find the solution.
I am using Asp NetCore, how should I use lambda function to upload clipped file in s3?
I have a IFormFile but I want to use s3 url instead of IFormFile and upload in s3 bucket. I have used ffmpeg library to cut the video and I want to send url of s3 using lambda function and upload the output of clipped video file again in s3 bucket directory that i created in s3 console.
using Abp.UI;
using FFmpeg.NET;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using Amazon.S3;
using System.Threading.Tasks;
using Amazon.S3.Transfer;
using Amazon.S3.Model;
using IdentityModel.Client;
using Amazon;
using System.Net.Http;
namespace VideoSlicer.About
{
public class AboutAppService : IAboutAppService
{
//Assigning readonly IHostingEnvironment
private readonly IHostingEnvironment _appEnvironment;
private readonly string bucketName = "videoslicerpuru";
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.Region;
/*
private const string newFile = "QQ.mp4";
private const string newFile1 = "637156754716419260QQ.mp4";
private const string filePath = #"C:\Users\Purushottam\Downloads\VideoSlicer\5.1.1\aspnet-core\src\VideoSlicer.Web.Host\wwwroot\images\";*/
private static IAmazonS3 client;
//Making Constructor and passin IHostingEnvironment
public AboutAppService(IHostingEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
//Function which upload video and slice video accordingly start time and finish time given by the user
public async Task UploadImage(IFormFile file, string Start, string Finish)
{
HttpClient cli = new HttpClient();
cli.DefaultRequestHeaders.ExpectContinue = false;
try
{
//Taking out the extension of the file
var convertedExtension = file.FileName.Substring(file.FileName.LastIndexOf("."));
//Comparing the extension whether uploaded file is video or not
if (convertedExtension != ".mp4" && convertedExtension != ".flv" && convertedExtension != ".3GP" && convertedExtension != ".OGG" && convertedExtension != ".AVI" && convertedExtension != ".WMV ")
{
throw new UserFriendlyException("Please Select Valid Video file to clip!!");
}
//Checking if the file is null or has not been selected any file
if (file == null || file.Length == 0)
{
throw new UserFriendlyException("Please Select any file.");
}
//declaring web root path
string path_Root = _appEnvironment.WebRootPath;
//setting path root and saving video to the given path
string pathOfVideo = path_Root + "\\video\\";
string path_to_Video = path_Root + "\\images\\" + file.FileName;
using (var stream = new FileStream(path_to_Video, FileMode.Create))
{
await file.CopyToAsync(stream);
}
client = new AmazonS3Client("AccessKey", "SecretKey", bucketRegion);
TransferUtility utility = new TransferUtility(client);
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
string nameOfFile = file.FileName.ToString();
string videoPath = path_to_Video.ToString();
await utility.UploadAsync(videoPath, bucketName, nameOfFile);
Console.WriteLine("Upload 2 completed");
//To cut video, using ffmpeg media file where the video is saved
var input = new MediaFile(path_to_Video);
//The output of the clipped video and saving in a different folder
string nameFile = DateTime.Now.Ticks + file.FileName;
string nameBucket = bucketName + "/videoslice/";
var output = new MediaFile(path_Root + "/video/" + nameFile);
client = new AmazonS3Client(bucketRegion);
//making the object of Engine using ffmpeg application file
var ffmpeg = new Engine("C:\\ffmpeg\\bin\\ffmpeg.exe");
//making object of Conversion Option of ffmpeg
var options = new ConversionOptions();
//Converting string to double
var startTime = Convert.ToDouble($"{Start}");
var finishTime = Convert.ToDouble($"{Finish}");
//clipping video by given user input
options.CutMedia(TimeSpan.FromSeconds(startTime), TimeSpan.FromSeconds(finishTime - startTime));
await ffmpeg.ConvertAsync(input, output, options);
string clipPath = path_Root + "\\video\\" + nameFile;
//Checking if start time is greater then finish time
if (startTime > finishTime)
{
throw new UserFriendlyException("Please Enter Valid Second to proceed");
}
//Checking if start time is equal to finish time
if (startTime == finishTime)
{
throw new UserFriendlyException("Please Enter Valid Second to proceed");
}
var a = utility.UploadAsync(clipPath, nameBucket, nameFile);
Console.WriteLine("Upload 2 completed");
}
catch (AmazonS3Exception e)
{
string err = e.Message;
throw e;
}
catch (InternalBufferOverflowException a)
{
string me = a.Message;
throw a;
}
catch (HttpRequestException c)
{
string error = c.Message;
throw c;
}
catch (DriveNotFoundException e)
{
string mes = e.Message;
throw e;
}
catch(NullReferenceException e)
{
throw new UserFriendlyException (500, "Please Select a file to proceed",e.Message);
}
}
}
}
I am using Sabre SOAP Api in C#. I got the response from session creation successfully, I added wsdl Service Reference http://webservices.sabre.com/wsdl/tpfc/OTA_AirAvailLLS2.3.0RQ.wsdl to my test project and pass required values to parameters in the request as given in the documentation https://developer.sabre.com/docs/read/soap_apis/air/search/Air_Availability.
this is my code to consume SOAP API
public OTA_AirAvailRS Method(string securitytoken, string convid, string ipcc)
{
try
{
DateTime dt = DateTime.UtcNow;
string tstamp = dt.ToString("s") + "Z";
//Create the message header. Provide the value for the conversation ID, the action code of the Web
//service being called, and the value for wsse:BinarySecurityToken that was returned with
//the SessionCreateRS message.
//This sample calls the OTA_AirAvailLLSRQ Service, and the action code that corresponds to
//this service is OTA_AirAvailLLSRQ.
MessageHeader msgHeader = new MessageHeader();
msgHeader.ConversationId = convid; // Put ConversationId in req header
From from = new From();
PartyId fromPartyId = new PartyId();
PartyId[] fromPartyIdArr = new PartyId[1];
fromPartyId.Value = "WebServiceClient";
fromPartyIdArr[0] = fromPartyId;
from.PartyId = fromPartyIdArr;
msgHeader.From = from;
To to = new To();
PartyId toPartyId = new PartyId();
PartyId[] toPartyIdArr = new PartyId[1];
toPartyId.Value = "WebServiceSupplier";
toPartyIdArr[0] = toPartyId;
to.PartyId = toPartyIdArr;
msgHeader.To = to;
msgHeader.CPAId = ipcc;
msgHeader.Action = "OTA_AirAvailLLSRQ";
Service service = new Service();
service.Value = "AirAvail";
msgHeader.Service = service;
MessageData msgData = new MessageData();
msgData.MessageId = "mid:20001209-133003-2333#clientofsabre.com1";
msgData.Timestamp = tstamp;
msgHeader.MessageData = msgData;
Security1 security = new Security1();
security.BinarySecurityToken = securitytoken; // Put BinarySecurityToken in req header
//Create the request object req and the value for the IPCC in the payload of the request.
OTA_AirAvailRQOriginDestinationInformationFlightSegment seg = new OTA_AirAvailRQOriginDestinationInformationFlightSegment()
{
ArrivalDateTime = "12-21T19:00",
DepartureDateTime = "12-21T18:00",
DestinationLocation = new OTA_AirAvailRQOriginDestinationInformationFlightSegmentDestinationLocation() { LocationCode = "DFW" },
OriginLocation = new OTA_AirAvailRQOriginDestinationInformationFlightSegmentOriginLocation() { LocationCode = "HNL" }
};
OTA_AirAvailRQ req = new OTA_AirAvailRQ();
req.OriginDestinationInformation = new OTA_AirAvailRQOriginDestinationInformation() { FlightSegment = seg };
// req.TimeStamp = tstamp;
// req.OptionalQualifiers.FlightQualifiers.
req.Version="2.3.0";
OTA_AirAvailPortTypeClient c = new OTA_AirAvailPortTypeClient();
OTA_AirAvailRS resp = c.OTA_AirAvailRQ(ref msgHeader, ref security, req);
return resp;
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine("Exception Stack Trace : " + e.StackTrace);
}
return new OTA_AirAvailRS();
}
its throws an exception Message: ERR.SWS.CLIENT.VALIDATION_FAILED
Stack:
Server stack trace:
at
System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
operation, ProxyRpc& rpc) at
System.ServiceModel.Channels.ServiceChannel.Call(String action,
Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs, TimeSpan timeout) at
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
methodCall, ProxyOperationRuntime operation) at
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
message)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg) at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type) at
ConsoleApplication1.ServiceAirAvailLLSReference1.OTA_AirAvailPortType.OTA_AirAvailRQ(OTA_AirAvailRQRequest
request) at
ConsoleApplication1.ServiceAirAvailLLSReference1.OTA_AirAvailPortTypeClient.ConsoleApplication1.ServiceAirAvailLLSReference1.OTA_AirAvailPortType.OTA_AirAvailRQ(OTA_AirAvailRQRequest
request) in e:\ConsoleApplication1\ConsoleApplication1\Service
References\ServiceAirAvailLLSReference1\Reference.cs:line 7012 at
ConsoleApplication1.ServiceAirAvailLLSReference1.OTA_AirAvailPortTypeClient.OTA_AirAvailRQ(MessageHeader&
MessageHeader, Security1& Security, OTA_AirAvailRQ OTA_AirAvailRQ1) in
e:\ConsoleApplication1\ConsoleApplication1\Service
References\ServiceAirAvailLLSReference1\Reference.cs:line 7020 at
ConsoleApplication1.SearchAirAvail.Method(String securitytoken, String
convid, String ipcc) in
e:\ConsoleApplication1\ConsoleApplication1\SearchAirAvail.cs:line 115
Please Help Me
I found the answer of this question..
Just comment
//ArrivalDateTime = "12-21T19:00"
This field is not required for request
first of all I would like to wish everyone a happy 2015 and be prosperous for all of you.
I would like to help me with a problem I have with a cookie and Winnovative, the problem is that I correctly the data in a cookie but when the process for the dll and reaches the window that gets data to the cookie comes in white with no data. not then I'm doing wrong. Annex code to Confinued:
string apo = String.Empty;
apo = Request.Cookies["dApoderados"].Value;
HttpCookie datosApoderados = new HttpCookie("datosApoderados");
string cadenaPDF = String.Empty;
string ruta = String.Empty;
ruta = ObtenerDireccionInformeSalida();
ruta = ruta.Replace("../", "");
GenerarQueryString();
Response.Cookies["datosApoderados"].Value = apo;
ruta = "http://localhost:10458/" + ruta;
byte[] bytes = ObtenerPdfBytes(ruta);
That's when I want to process, then passes through an intermediate product which is:
public byte[] ObtenerPdfBytes(string ruta)
{
string datosClientes = Request.Cookies["datosCliente"].Value;
string datosApoderados = Request.Cookies["datosApoderados"].Value;
datosClientes = "?DATOS=" + datosClientes;
ruta = ruta + datosClientes;
PdfConverter pdfConverter = new PdfConverter();
HttpCookie prueba = new HttpCookie("prueba");
Response.Cookies["prueba"].Value = datosApoderados;
if (Context.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
pdfConverter.HttpRequestHeaders = String.Format("prueba : {0}={1}",
FormsAuthentication.FormsCookieName, Request.Cookies[FormsAuthentication.FormsCookieName].Value);
}
pdfConverter.LicenseKey = ClaveGeneradorPdf;
pdfConverter.PdfDocumentOptions.ShowFooter = true;
pdfConverter.PdfFooterOptions.PageNumberText = TextoPagina;
pdfConverter.PdfFooterOptions.PageNumberTextFontType = PdfFontType.HelveticaBold;
pdfConverter.PdfFooterOptions.PageNumberTextFontSize = 8;
pdfConverter.PdfFooterOptions.ShowPageNumber = true;
pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Legal;
pdfConverter.PdfFooterOptions.FooterHeight = AltoPie;
pdfConverter.PdfDocumentOptions.LeftMargin = MargenIzquierdo;
pdfConverter.PdfDocumentOptions.RightMargin = MargenDerecho;
pdfConverter.PdfDocumentOptions.TopMargin = MargenSuperior;
pdfConverter.PdfDocumentOptions.BottomMargin = MargenInferior;
pdfConverter.PdfDocumentOptions.PdfPageOrientation = PDFPageOrientation.Portrait;
pdfConverter.PdfFooterOptions.FooterText = "texto";
pdfConverter.PdfFooterOptions.FooterTextFontType = PdfFontType.HelveticaBold;
pdfConverter.PdfFooterOptions.FooterTextFontSize = 8;
pdfConverter.PdfDocumentOptions.ShowHeader = false;
byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(ruta);
return pdfBytes;
}
when I get to the next line is where the cookie is lost:
byte [] pdfBytes = pdfConverter.GetPdfBytesFromUrl (path);
public override void Pagina_PrimeraCarga(object sender, EventArgs e)
{
string prueba = Request.Cookies["prueba"].Value;
string datosRequest = Request.QueryString["DATOS"];
char delimitadores = ';';
string[] datos = datosRequest.Split(delimitadores);
imgBanco.Attributes.Add("ImageUrl", "~/App_Themes/Imagenes/Logo.gif");
DateTime fechaHoy = DateTime.Now;
lblDia.Text = Convert.ToString(fechaHoy.Day);
lblMes.Text = Convert.ToString(fechaHoy.Month);
lblAno.Text = Convert.ToString(fechaHoy.Year);
loading data from the cookie in the latter code:
string test = Request.Cookies ["test"] Value.;
This goes empty and no data
The converter has a HttpRequestCookies collection you can use. There is a complete example for cookies in Winnovative website. Here is the relevant code copied from there:
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
// Add custom HTTP cookies
if (cookie1NameTextBox.Text.Length > 0 && cookie1ValueTextBox.Text.Length > 0)
htmlToPdfConverter.HttpRequestCookies.Add(cookie1NameTextBox.Text, cookie1ValueTextBox.Text);
if (cookie2NameTextBox.Text.Length > 0 && cookie2ValueTextBox.Text.Length > 0)
htmlToPdfConverter.HttpRequestCookies.Add(cookie2NameTextBox.Text, cookie2ValueTextBox.Text);
if (cookie3NameTextBox.Text.Length > 0 && cookie3ValueTextBox.Text.Length > 0)
htmlToPdfConverter.HttpRequestCookies.Add(cookie3NameTextBox.Text, cookie3ValueTextBox.Text);
if (cookie4NameTextBox.Text.Length > 0 && cookie4ValueTextBox.Text.Length > 0)
htmlToPdfConverter.HttpRequestCookies.Add(cookie4NameTextBox.Text, cookie4ValueTextBox.Text);
if (cookie5NameTextBox.Text.Length > 0 && cookie5ValueTextBox.Text.Length > 0)
htmlToPdfConverter.HttpRequestCookies.Add(cookie5NameTextBox.Text, cookie5ValueTextBox.Text);
// Convert the HTML page to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(urlTextBox.Text);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=HTTP_Cookies.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
I am trying to send push notification in blackberry by using C# Web
service but i am facing problem is it return exception "The remote
server returned an error: (404) Not Found.". all info is correct as
per RIM Standard so please Help me ASAP.
[WebMethod]
public bool push(string notification)
{
bool success = true;
byte[] bytes = Encoding.ASCII.GetBytes("Hello");
Stream requestStream = null;
HttpWebResponse HttpWRes = null;
HttpWebRequest HttpWReq = null;
String BESName = "cp****.pushapi.eval.blackberry.com";
try
{
//http://<BESName>:<BESPort>/push?DESTINATTION=<PIN/EMAIL>&PORT=<PushPort>&REQUESTURI=/
// Build the URL to define our connection to the BES.
string httpURL = "https://" + BESName + "/push?DESTINATION=2B838E45&PORT=32721&REQUESTURI=/";
//make the connection
HttpWReq = (HttpWebRequest)WebRequest.Create(httpURL);
HttpWReq.Method = ("POST");
//add the headers nessecary for the push
HttpWReq.ContentType = "text/plain";
HttpWReq.ContentLength = bytes.Length;
// ******* Test this *******
HttpWReq.Headers.Add("X-Rim-Push-Id", "2B838E45" + "~" + DateTime.Now); //"~" +pushedMessage +
HttpWReq.Headers.Add("X-Rim-Push-Reliability", "application-preferred");
HttpWReq.Headers.Add("X-Rim-Push-NotifyURL", ("http://" + BESName + "2B838E45~Hello~" + DateTime.Now).Replace(" ", ""));
// *************************
HttpWReq.Credentials = new NetworkCredential("Username", "Password");
requestStream = HttpWReq.GetRequestStream();
//Write the data from the source
requestStream.Write(bytes, 0, bytes.Length);
//get the response
HttpWRes = (HttpWebResponse)HttpWReq.GetResponse();
var pushStatus = HttpWRes.Headers["X-RIM-Push-Status"];
//if the MDS received the push parameters correctly it will either respond with okay or accepted
if (HttpWRes.StatusCode == HttpStatusCode.OK || HttpWRes.StatusCode == HttpStatusCode.Accepted)
{
success = true;
}
else
{
success = false;
}
//Close the streams
HttpWRes.Close();
requestStream.Close();
}
catch (System.Exception)
{
success = false;
}
return success;
}
I got the same error when I tried your code above. Replace
String BESName = "cp****.pushapi.eval.blackberry.com";
With
String BESName = "cpxxx.pushapi.eval.blackberry.com/mss/PD_pushRequest";
and make sure you provide the right username and password here:
HttpWReq.Credentials = new NetworkCredential("username", "password");
I got success = true;
However, even though the above code executed successfully, I still do not see the push message on the BlackBerry device.
I'm fairly new to webservices and working through a SAAJ example of sending and recieving attachments (binary files). I can get it to work when the client sends the file but not when it requests it. I get an exception on the client side:
ERROR: 'Content is not allowed in prolog.'
24-Oct-2012 13:59:28 com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory createEnvelope
SEVERE: SAAJ0511: Unable to create envelope from given source
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Unable to create envelope from given source
Anybody have any ideas???my client code is as follows:
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection con = scf.createConnection();
SOAPFactory soapFactory = SOAPFactory.newInstance();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
SOAPHeader header = msg.getSOAPHeader();
header.detachNode();
SOAPBody body = msg.getSOAPBody();
Name bodyName = soapFactory.createName(
"remoteOpen", "remoteOpen",
"http://schemas.remoteOpen.com/remoteOpen");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
SOAPElement projectName = bodyElement.addChildElement("projectName");
projectName.addTextNode("filename");
msg.saveChanges();
// create the endpoint and send the message
URL endpoint = new URL("http://localhost:8080/RemoteSaveProject/OpenServlet");
SOAPMessage response = con.call(msg, endpoint);
con.close();
SOAPBody responseBody = response.getSOAPBody();
SOAPElement ackElem = (SOAPElement)responseBody.getFirstChild();
String acknowledgement = ackElem.getValue();
the server code looks like this:
MimeHeaders mimeHeaders = new MimeHeaders();
Enumeration en = request.getHeaderNames();
while (en.hasMoreElements())
{
String headerName = (String)en.nextElement();
String headerVal = request.getHeader(headerName);
StringTokenizer tk = new StringTokenizer(headerVal, ",");
while (tk.hasMoreTokens()){
mimeHeaders.addHeader(headerName, tk.nextToken().trim());
}
}
SOAPMessage message = mf.createMessage(mimeHeaders, request.getInputStream());
SOAPBody body = message.getSOAPBody();
Name bodyName = soapFactory.createName(
"remoteOpen", "remoteOpen",
"http://schemas.remoteOpen.com/remoteOpen");
Iterator projects = body.getChildElements(bodyName);
SOAPElement project = (SOAPElement)projects.next();
Iterator projectNameIter = project.getChildElements(soapFactory.createName("projectName"));
SOAPElement projectNameEle = (SOAPElement)projectNameIter.next();
String projectName = projectNameEle.getValue();
File file = new File(projectName);
SOAPMessage reply = mf.createMessage();
SOAPHeader header = reply.getSOAPHeader();
header.detachNode();
SOAPBody replyBody = reply.getSOAPBody();
SOAPBodyElement bodyElement = replyBody.addBodyElement(soapFactory.createName("ack"));
bodyElement.addTextNode("OK");
DataHandler dh = new DataHandler(new FileDataSource(file));
AttachmentPart attachment = reply.createAttachmentPart(dh);
attachment.setContentId("123");
reply.addAttachmentPart(attachment);
reply.saveChanges();
response.setStatus(HttpServletResponse.SC_OK);
putHeaders(reply.getMimeHeaders(), response);
response.setContentType("text/xml");
ServletOutputStream replyOS = response.getOutputStream();
reply.writeTo(replyOS);
replyOS.flush();
replyOS.close();
putHeaders looks like:
Iterator it = headers.getAllHeaders();
while (it.hasNext())
{
MimeHeader header = (MimeHeader) it.next();
String[] values = headers.getHeader(header.getName());
if (values.length == 1)
{
res.setHeader( header.getName(), header.getValue());
}
else
{
StringBuffer concat = new StringBuffer();
int i = 0;
while (i < values.length)
{
if (i != 0)
{
concat.append(',');
}
concat.append(values[i++]);
}
res.setHeader(header.getName(), concat.toString());
}
}
If you are using Google app engine, like me, the problem is that GAE doesn't support com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParameterList which is used internally somewhere in the call chain of javax.xml.soap.SOAPConnection.call(). So you must use a workaround.
I personally did it by using java.net.HttpURLConnection instead of javax.xml.soap.SOAPConnection and manually sending and parsing SOAP messages.