Apache Common FileUtils Read XML file into String - xml-parsing

I have stored SOAP XML file into local machine now to validate that XML i need to load that file and extract the XML from SOAP body to validate it.
SOAP XML
<SOAP:Envelope>
<SOAP:Body>
<request>
<Login>
<Username>abc</Username>
<Password>abc</Password>
</Login>
</request>
</SOAP:Body>
</SOAP:Envelope>
I need to extract the <Login> XML from above SOAP request.
I am using FileUtils to read file into string. when i read the file using that it also read the characters like \n\t\t etc means it consider the newline and tab which is in the XML formatted file.
i extract the child node from XML as string using below code.
InputStream requestXMLInputStream = new ByteArrayInputStream(soapRequestXML.getBytes());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
String requestXMLBody = "";
Document doc = null;
try {
dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(requestXMLInputStream);
NodeList requestNodeList = doc.getElementsByTagName(parentTagName);
Node node = requestNodeList.item(0);
DOMImplementationLS domImplLS = (DOMImplementationLS) doc.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
if(node != null && node.getFirstChild() != null)
requestXMLBody = serializer.writeToString(node.getFirstChild());
} catch (SAXException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
}catch (ParserConfigurationException e) {
logger.error(e.getMessage());
}
return requestXMLBody;
How can i read an XML file in without these characters.
Please help.

Using string manipulation for reading XML documents is a well-tested recipe for headache and frustration. Use only published XML API's for that.
The general approach would be:
1) Assuming that the SOAP XML is stored in a file, use the JAXP API to parse the XML into a Document object.
2) Navigate to the Login element using XPath (use the standard Java XPath API, included in the JDK).
3) Once you have a reference to the Login element, use a JAXP Transformer to serialize the Login element into a string.
(Step (1) would change if the SOAP packet is received through usage of one of the standard web services API's. You mentioned that the SOAP packet is given as stored in a file)

Related

Generating dart code from single JSON input

I'm trying to build a dart package which generates API source code from OData JSON representation file. I tried using source_gen, but it appears to generate code based on annotations or existing source code (e.g. JSON serializer generated code for existing class).
Goal: Generate multiple dart codes based on JSON data. E.g.: Say my JSON is:
{
"user": {
"income": "Decimal", //Decimal is the type, which I translate it into dart type
}
}
and my generated code would be:
user.dart:
import "package:decimal/decimal.dart";
class User {
final Decimal age;
User(this.age);
}
What are you trying to do is already implemented, when it comes to API description.
You can generate code with classes from .proto or swagger .yaml/ .json files.
Proto file generation for gRPC API
Proto file example:
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
}
message SearchResponse {
...
}
Swagger rest api code generation from .yml/json files
Look:

HttpContent.ReadAsStringAsync throws when charset is surrounded by quotes

I am trying to POST files containing arbitrary binary data to a WebAPI 2 controller as multipart/form-data.
When trying to read the files using the following:
var provider = new MultipartFormDataStreamProvider(uploadDirectoryPath);
await Request.Content.ReadAsMultipartAsync(provider);
I get:
System.InvalidOperationException: The character set provided in ContentType is invalid.
Cannot read content as string using an invalid character set.
---> System.ArgumentException: '"utf-8"' is not a supported encoding name.
For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name
I understand that the problem is the quotes around utf-8 and it is this bug in HttpContent.ReadAsStringAsync() used internally as explained here.
The request is being sent from a Unity3D app and I am unable to change the charset in the request body.
Here is the code I am using in the Unity3D script to create the POST request.
WWW chunkFile = new WWW("file:///" + Path.Combine(tempZipFolderPath, chunkFilenames[j]));
yield return chunkFile;
if (chunkFile.error != null)
throw new Exception(string.Format("{0} error opening file {1}", chunkFile.error, chunkFilenames[j]));
//BUGFIX: Not using IMultipartFormSection because of https://fogbugz.unity3d.com/default.asp?826626_htlchp13nh8th2to
var form = new WWWForm();
form.AddField("chunkNumber", chunkNumber);
form.AddField("totalChunks", totalChunks);
form.AddField("identifier", tempZipFileName);
form.AddBinaryData("filename", chunkFile.bytes, chunkFilenames[j]);
var scanUploadPostRequest = UnityWebRequest.Post(WebApiScanUploadUrl, form);
yield return scanUploadPostRequest.Send();
//BUGBUG: charset UTF-8 wrapped in quotes causes error
Is there a workaround to this?

Dart Html - Convert Blob to File

I'm attempting to write a test for some dart:html code.
I have a method with a File parameter (html File, not io File).
testFile(File file)
I'm able to create a Blob with the needed data for the file (minus file name, date, etc.), but it appears there is no way to create File objects in dart:html, as it's reserved for internal use in html_dartium.dart.
factory File._() { throw new UnsupportedError("Not supported"); }
Is there any other way to create an HTML File object?
I've seen FileReaders mentioned, but the results from those is either a String or uint8list.
After further research, I achieved what I was looking for with the following:
List<String> file_contents = ["test\n"];
Blob blob = new Blob(file_contents, 'text/plain', 'native');
FileSystem _filesystem = await window.requestFileSystem(1024 * 1024, persistent: false);
FileEntry fileEntry = await _filesystem.root.createFile('dart_test.csv');
FileWriter fw = await fileEntry.createWriter();
fw.write(blob);
File file = await fileEntry.file();
Something like
Blob response = _downloadRequest.response;
final FileReader reader = new FileReader();
reader.onLoad.listen((e) {
_handleData(reader);
});
reader.readAsArrayBuffer(response);
See Downloading a file using Dart GDrive api with authorized GET request

ASP.NET Web API, unexpected end of MIME multi-part stream when uploading from Flex FileReference

Following the tutorial found on ASP.NET, implemented a Web API controller method for doing asynchronous file uploads that looks like this:
public Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
Uploading a file via a standard multipart HTML form works perfectly. However, when another developer attempts to upload a file via multipart form constructed by Flex's FileReference class, an error is thrown:
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
I have no idea if the problem lies in Web API or Flex. I've found some sort of related fixes that had no affect (Multipart form POST using ASP.Net Web API), and more recently this one ("MIME multipart stream. MIME multipart message is not complete" error on webapi upload). If the second link holds true, does anyone know if it's out in the current release of Web API available via Nuget? The discussion was in May, the most recent release from Nuget was August, so I assume this fix was deployed already, and is not the root cause of my issue.
I had the same problem with MVC4, but Will is correct, add a name to your input.....
<input type="file" id="fileInput" name="fileInput"/>
and all the magic is back up and working!
I had the same problem with flex. And below is the code that solved it. Basically I used a custom stream to append the newline that asp.net web api is expecting.
Stream reqStream = Request.Content.ReadAsStreamAsync().Result;
MemoryStream tempStream = new MemoryStream();
reqStream.CopyTo(tempStream);
tempStream.Seek(0, SeekOrigin.End);
StreamWriter writer = new StreamWriter(tempStream);
writer.WriteLine();
writer.Flush();
tempStream.Position = 0;
StreamContent streamContent = new StreamContent(tempStream);
foreach(var header in Request.Content.Headers)
{
streamContent.Headers.Add(header.Key, header.Value);
}
// Read the form data and return an async task.
await streamContent.ReadAsMultipartAsync(provider);
Hope this helps.
Reading through your existing research and following through to the codeplex issue reported it looks like someone else confirmed this issue to still exist in September.
They believe that MVC 4 fails to parse uploads without a terminating "\r\n".
The issue is really simple but extremely hard to fix. The problem is that Uploadify does > not add an "\r\n" at the end of the MultiPartForm message
http://aspnetwebstack.codeplex.com/discussions/354215
It may be worth checking that the Flex upload adds the "\r\n"
For those landing here googling:
Unexpected end of MIME multipart stream. MIME multipart message is not complete.
Reading the request stream more than once will also cause this exception. I struggled with it for hours until I found a source explaining that the request stream only could be read once.
In my case, I combined trying to read the request stream using a MultipartMemoryStreamProvider and at the same time letting ASP.NET do some magic for me by specifying parameters (coming from the request body) for my api method.
Make sure the virtual directory ("~/App_Data" directory as below example) where the image files are first uploaded are physically existance. When you publish the project, it may not be in the output files.
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
I just removed my headers I was setting on my post method which ended up solving this issue.
The problem is this line:
string root = HttpContext.Current.Server.MapPath("~/App_Data");
It will only work in localhost, you can use HostingEnvironment.MapPath instead in any context where System.Web objects like HttpContext.Current are not available (e.g also from a static method).
var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/SomePath");
See also What is the difference between Server.MapPath and HostingEnvironment.MapPath?
Reference to this answer How to do a Server Map Path.

Get full path of a file stored in sharepint documentlibrary

I have a file stored in a sharepoint libarary like
filePathAndName = "http://spstore/sites/appsitename/documentlibraryname/abc.xls"
I need to be able to open the the abc.xls file using
byte[] buffer = System.IO.File.ReadAllBytes(filePathAndName);
but i get an error stating. uri formats are not supported. How do I get the full path to the file?
You have to download the file first. For example you could use a WebClient to send an HTTP request to the remote server and retrieve the file contents:
using (var client = new WebClient())
{
byte[] file = client.DownloadData("http://spstore/sites/appsitename/documentlibraryname/abc.xls");
// TODO: do something with the file data
}

Resources