all examples show how to read an xml from an local file. But how do I read a xml from a url or a stream and process it further?
Example: http://www.oreillynet.com/xml/blog/2006/03/hello_saxon_on_net_an_aspnet_i.html
thanks in advance
Look for XsltExamples.cs in the saxon-resources download available on both Sourceforge and www.saxonica.com. The very first example seems to do what you are asking for.
public static void ExampleSimple1(String sourceUri, String xsltUri) {
// Create a Processor instance.
Processor processor = new Processor();
// Load the source document
XdmNode input = processor.NewDocumentBuilder().Build(new Uri(sourceUri));
// Create a transformer for the stylesheet.
XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(xsltUri)).Load();
// Set the root node of the source document to be the initial context node
transformer.InitialContextNode = input;
// Create a serializer
Serializer serializer = new Serializer();
serializer.SetOutputWriter(Console.Out);
// Transform the source XML to System.out.
transformer.Run(serializer);
}
Are you using an XmlDocument object for reading the XML? If so, you'll want XMLDocument.Load() method, which can take a file path or URL, TextReader or Stream as input.
Likewise, XDocument.Load()(msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.load(v=vs.110).aspx) has a similar set of overloads.
Related
I am using Beanshell sampler to save one pdf file content into another pdf file.
In Beanshell sampler I have put this following code:
FileInputStream in = new FileInputStream("C:\\Users\\Dey\\Downloads\\sample.pdf");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int i; (i = in.read(buffer)) != -1; ) {
bos.write(buffer, 0, i);
}
in.close();
byte[] extractdata = bos.toByteArray();
bos.close();
vars.put("extractdata", new String(extarctdata));
using beanshell post processor I saved this variable ${extractdata} in another pdf file .
file is generated but when open the file it's empty means there is no content showing.
So , can someone please tell me how to resolve this issue ?? is there anything wrong in above code snippet ?? please guide me.
You made a typo
byte[] extractdata = bos.toByteArray();
and
vars.put("extractdata", new String(extarctdata));
so your test element is silently failing, check jmeter.log file it should contain some errors.
It's not possible to state what else is wrong because we don't see your Beanshell Post-Processor code, most probably there is an issue with encoding when converting the byte array to string and vice versa.
So I would suggest skipping this step and using vars.putObject() function instead like:
vars.put("extractdata", extractdata);
and then
byte [] extractdata = vars.getObject("extractdata");
If you just need to copy the file you can use the following snippet:
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
Path source = Paths.get("C:\\Users\\Dey\\Downloads\\sample.pdf");
Path target = Paths.get("/location/for/the/new/file.pdf")
Files.copy(source, target);
Since JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy for scripting so you should switch to Groovy, in this case you will be able to do something like:
new File('/location/for/the/new/file.pdf').bytes = new File('C:\\Users\\Dey\\Downloads\\sample.pdf').bytes
More information on Groovy scripting in JMeter: Apache Groovy: What Is Groovy Used For?
I'm uploading a file using primefaces components.
public void handleFileUpload(FileUploadEvent event) {
UploadedFile file = event.getFile();
}
For the further progress of the application, I have a function given from a library that I have to use. This function is only accepting a FileObject as input parameter.
How can I convert the UploadedFile (primefaces) to a FileObject (Apache Common)?
A workaround would be converting the UploadedFile to a File and then convert the file to a FileObject using VFS.getManager() and its functions. But to do this, I would have to save the file on the server and delete it later again.
I'm looking for a way, where I can convert the UploadedFile directly to a FileObject. Maybe by converting it to a bytearray first?
Glad for all suggestions.
Apache Commons VFS supports many different 'virtual file systems', one of them being 'RAM' which does not require storing in a real disk based file(system)
You can use it something like this (disclaimer: not tested)
public void handleFileUpload(FileUploadEvent event) {
UploadedFile file = event.getFile();
FileObject ram = VFS.getManager().resolveFile("ram:"+file.getFileName());
OutputStream os = ram.getContent().getOutputStream();
os.write(file.getContents());
ram.getContent().close();
// Use the ram FileObject
}
Maybe the easiest solution would be to simply build a custom implementation of FileObject that receives a FileUpload as a constructor parameter, extracts it's InputStream's contents and returns them as requested.
Look at the documentation to know the required methods.
I have a WCF connected service in a .net core application. I'm using the code that is autogenerated taken the wsdl definition.
Currently at the top of the request xml is including this line:
<?xml version="1.0" encoding="utf-16"?>
I can't find a simple way to change this encoding to UTF-8 when sending the request.
Since I could find a configuration option a the request/client objects, I've tried to change the message with following code at IClientMessageInspector.BeforeSendRequest
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
// Load a new xml document from current request
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(request.ToString());
((XmlDeclaration)xmlDocument.FirstChild).Encoding = Encoding.UTF8.HeaderName;
// Create streams to copy
var memoryStream = new MemoryStream();
var xmlWriter = XmlWriter.Create(memoryStream);
xmlDocument.Save(xmlWriter);
xmlWriter.Flush();
xmlWriter.Close();
memoryStream.Position = 0;
var xmlReader = XmlReader.Create(memoryStream);
// Create a new message
var newMessage = Message.CreateMessage(request.Version, null, xmlReader);
newMessage.Headers.CopyHeadersFrom(request);
newMessage.Properties.CopyProperties(request.Properties);
return null;
}
But the newMessage object still writes the xml declaration using utf-16. I can see it while debugging at the watch window since.
Any idea on how to accomplish this (should be) simple change will be very apreciated.
Which binding do you use to create the communication channel? The textmessageencoding element which has been contained in the CustomBinding generally contains TextEncoding property.
https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/textmessageencoding
WriteEncoding property specifies the character set encoding to be used for emitting messages on the binding. Valid values are
UnicodeFffeTextEncoding: Unicode BigEndian encoding
Utf16TextEncoding: Unicode encoding
Utf8TextEncoding: 8-bit encoding
The default is Utf8TextEncoding. This attribute is of type Encoding.
As for the specific binding, it contains the textEncoding property too.
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.basichttpbinding.textencoding?view=netframework-4.0
Feel free to let me know if there is anything I can help with.
I need to do download an XML file from a public website (http://www.tcmb.gov.tr/kurlar/201707/10072017.xml) to get exchange rates.
But I have a problem since the XML contains an xml-stylesheet processing instruction.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="isokur.xsl"?>
<Tarih_Date Tarih="07.07.2017" Date="07/07/2017" Bulten_No="2017/131" >
I use a WCF-Custom port with webHttpBindng and BizTalk REST starter kit from bLogical. Everything works fine, but when I try to parse the incoming xml, I get an error on that processing instruction.
System.Xml.XmlException: Processing instructions (other than the XML declaration) and DTDs are not supported. Line 2, position 2.
I'm not sure what the best way would be to fix this. I tried to follow this guide WCF Errors on XML Deserialization but it still fails when I try to access the message content using the CreateBufferedCopy method.
using (var readStream = new System.IO.MemoryStream())
{
using (var buffer = reply.CreateBufferedCopy(int.MaxValue))
{
buffer.WriteMessage(readStream);
}
readStream.Position = 0;
xdoc.Load(readStream);
}
Does anybody know how I can access the content of my message without actually parsing the XML? I'm just trying to find a way to either remove that line or make the parser ignore it.
I found the solution myself in the end. Instead of a message inspector, I created a Message Encoder based on the CustomTextMessageEncoder that you can find online.
In the ReadMessage method I just added a little bit of code
public override Message ReadMessage(System.IO.Stream stream, int maxSizeOfHeaders, string contentType)
{
XmlReaderSettings xsettings = new XmlReaderSettings();
xsettings.IgnoreProcessingInstructions = true;
XmlReader reader = XmlReader.Create(stream,xsettings);
return Message.CreateMessage(reader, maxSizeOfHeaders, this.MessageVersion);
}
I am using Google diff-match-patch JAVA plugin to create patch between two JSON strings and storing the patch to database.
diff_match_patch dmp = new diff_match_patch();
LinkedList<Patch> diffs = dmp.patch_make(latestString, originalString);
String patch = dmp.patch_toText(diffs); // Store patch to DB
Now is there any way to use this patch to re-create the originalString by passing the latestString?
I google about this and found this very old comment # Google diff-match-patch Wiki saying,
Unpatching can be done by just looping through the diff, swapping
DIFF_INSERT with DIFF_DELETE, then applying the patch.
But i did not find any useful code that demonstrates this. How could i achieve this with my existing code ? Any pointers or code reference would be appreciated.
Edit:
The problem i am facing is, in the front-end i am showing a revisions module that shows all the transactions of a particular fragment (take for example an employee details), like which user has updated what details etc. Now i am recreating the fragment JSON by reverse applying each patch to get the current transaction data and show it as a table (using http://marianoguerra.github.io/json.human.js/). But some JSON data are not valid JSON and I am getting JSON.parse error.
I was looking to do something similar (in C#) and what is working for me with a relatively simple object is the patch_apply method. This use case seems somewhat missing from the documentation, so I'm answering here. Code is C# but the API is cross language:
static void Main(string[] args)
{
var dmp = new diff_match_patch();
string v1 = "My Json Object;
string v2 = "My Mutated Json Object"
var v2ToV1Patch = dmp.patch_make(v2, v1);
var v2ToV1PatchText = dmp.patch_toText(v2ToV1Patch); // Persist text to db
string v3 = "Latest version of JSON object;
var v3ToV2Patch = dmp.patch_make(v3, v2);
var v3ToV2PatchTxt = dmp.patch_toText(v3ToV2Patch); // Persist text to db
// Time to re-hydrate the objects
var altV3ToV2Patch = dmp.patch_fromText(v3ToV2PatchTxt);
var altV2 = dmp.patch_apply(altV3ToV2Patch, v3)[0].ToString(); // .get(0) in Java I think
var altV2ToV1Patch = dmp.patch_fromText(v2ToV1PatchText);
var altV1 = dmp.patch_apply(altV2ToV1Patch, altV2)[0].ToString();
}
I am attempting to retrofit this as an audit log, where previously the entire JSON object was saved. As the audited objects have become more complex the storage requirements have increased dramatically. I haven't yet applied this to the complex large objects, but it is possible to check if the patch was successful by checking the second object in the array returned by the patch_apply method. This is an array of boolean values, all of which should be true if the patch worked correctly. You could write some code to check this, which would help check if the object can be successfully re-hydrated from the JSON rather than just getting a parsing error. My prototype C# method looks like this:
private static bool ValidatePatch(object[] patchResult, out string patchedString)
{
patchedString = patchResult[0] as string;
var successArray = patchResult[1] as bool[];
foreach (var b in successArray)
{
if (!b)
return false;
}
return true;
}