Convert a String into an XML file - java

I am using Castor XMLDiff to find the difference between 2 XML files. It compares two XML documents located at the given URL locations. Both my XML files are being generated at runtime and they are in the form of String. My question is how can I convert a String into an XML file, so that I can pass the file location as an argument.
I have a String in the following form:
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Header><MessageID>7dc1a6b9-5e84-4ee8-b801-816f4eccbe26</MessageID><MessageDate>.....
The method public XMLDiff(final String file1, final String file2) requires 2 file locations. Instead of a file location, I have the above stated string. What is the best way to persist this string in the form of an XML document, so that I can get its location and pass it to XMLDiff?

If the string contains XML data, then you just need to write it to disk. I would recommend a method such as FileUtils.write() from commons-io.
For example:
String xml = ...
FileUtils.write(new File("path/to/output"), xml, "UTF-8");
Of course, replace "UTF-8" with whatever encoding is advertised in your XML header.

If you are using Java 7, you don't need 3rd party libs and still only need very short code via use of the new IO api:
Path path = Files.createTempFile("prefix", null);
Files.write(path, yourXMLString.getBytes(Charset.forName("UTF-8")) , StandardOpenOption.CREATE, StandardOpenOption.WRITE);
String pathToTheFile = path.toString();
With this you can simply create two temporary files, fill them with the XML string and then provide the path strings to your library function.

Related

Generating XSL stylesheet in java (xml to xml)

i need a java code which makes an xsl style sheet that transforms an xml file to another xml file. but it should be dynamic.
i want to set the xsl:element names and path. and the java code should generate
me automaticly.
i have made one but if i want to change my type of xml, i need to add like 30 line code.
example from my code;
string xslelementstart = "<xsl:element name=\"" ;
string elementend="</xsl:element>";
string value="<xsl:value-of select=\"";
string name = "";(will be public and can be changed)
string path = "";(will be public and can be changed)
string end="\"\>";
string end2="\">";
if(path!="")
{
string xsl = xslelementstart+name+end2+"\n"+
value+path+end+"\n"
elementend
}
this is an example of my java code not the actual. im working with a big xml file. i want other xml files to be in my xml file format.but if i want to change my xml file (like adding another element) this code is not useful.as i said i should only set the values of my xml file and the java code should generates me. is it possible?
String concatenation is ugly, use Document Builder.
See the similar question: Create xslt files programmatically

Importing file to Alfresco programatically (through java backed webscript)

I am having problem when importing document (PDF) into Alfresco repository inside java backed webscript. I am using writer of ContentService.
If I use
ContentWriter writer = ContentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
writer.setEncoding("UTF-8");
writer.setMimetype("application/pdf");
writer.putContent(new String(byte []) );
or
writer.putContent(new String(byte [], "UTF-8") );
my document is not previewable (I see blank PDF file, tried with few small PDF files, don't know what would happen in case of other/larger files).
But if I use another putContent method which takes File as argument I'll successfully import the document.
writer.setEncoding("UTF-8");
writer.setMimetype("application/pdf");
writer.putContent(File);
I don't want to import file from disk since I get the file as Base64 encoded String but I don't know what am I missing.
You could use an InputStream as a parameter for ContentWriter::putContent. So you will prevent the String to byte array (and vice versa) conversions, which leads to difficulties with the encoding.
writer.putContent(new ByteArrayInputStream(Base64.decodeBase64("yourBase64EncodedString")))

Identify File Type in Java

I want to check that the user uploads only a particular file format (say text files only).
I've written a verification mechanism which checks for format after the file name like this
filename.txt
But, this created a problem when it was accepting other files also (like excel files) which are saved as .txt like
myexcelfile.txt is being assumed as a text file even when it is an excel file
So, What would be the unique parameter to check for to make sure that the uploaded file is of the required type?
Using apache-commons uploader, servlets.
======================EDIT=====================
Based on answers below, I've tried
FileInputStream my = new FileInputStream(uploadedFile2);
InputStream inputStream = new BufferedInputStream(my);
String mimeType = URLConnection.guessContentTypeFromStream(inputStream);
But is always returning a null value.
probe content type is based on filename extension and also there is a bug with this approach, checked that too.
I don't prefer to use third party file verifiers, I believe that this problem will have a logical solution.
Apache Tika has content detection capabilities for a wide range of file formats. From the documentation, one of the simplest ways to detect content type is based on the following code:
// default tika configuration can detect a lot of different file types
TikaConfig tika = new TikaConfig();
// meta data collected about the source file
Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, f.toString());
// determine mime type from file contents
String mimetype = tika.getDetector().detect
(TikaInputStream.get(uploadedFile2), metadata);
System.out.println("File " + uploadedFile2 + " is " + mimetype);
If mimetype is text/plain, then the file or stream contains plain text content.
You could open the file and read the first few bytes into a byte[] and check the values to see if it matches the known magic numbers for a particular file format. I tried finding out what that would be for an Excel file (pre-XML; the xlsx file format would identify as a zip file), but I haven't really found much data about that. The closest thing I've found so far was looking at the code for a Java Excel file parser library.
The old Excel data format used what's called BIFF. Check out the Apache POI library for parsers and such for those types of files. From the looks of it, the magic numbers for an Excel file would probably be 00 06 10 00 (for BIFF8 worksheet), or 00 05 10 00 (BIFF7 worksheet, sounds rather old).
try
Files.probeContentType(Paths.get("~/a.xls"))
note that output depends on system content type detector - it may be different on different machines.
As for me, this code returns
application/vnd.ms-excel
private static String getMimeType(String fileUrl) {
String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}

How to generate xml file using codename one api?

What I need is point 3:
Take one xsd file "testField.xsd" and parse it using "com.codename1.xml.XMLParser"
alter this xsd file and generate result
now I want to save this xsd file with name "testValues.xsd"
What i have done so far :
(1). Take one xsd file "testField.xsd" and parse it using "com.codename1.xml.XMLParser"
InputStream is = Display.getInstance().getResourceAsStream(null,
"/testField.xsd"+fileName);
Element response = xp.parse(new InputStreamReader(is));
(2). alter this xsd file and generate result
for(FormData fromDataObj : listInputs){
response.getElementById(fromDataObj.getInputId()).setAttribute("value",fromDataObj.getInputValue());
}
(3). now I want to save this xsd file with name testValues.xsd
//want to save above response as "testValues.xsd"
Look at the XmlWriter class it has the ability to write Element's to XML.

JSP: Get MIME Type on File Upload

I'm doing a file upload, and I want to get the Mime type from the uploaded file.
I was trying to use the request.getContentType(), but when I call:
String contentType = req.getContentType();
It will return:
multipart/form-data; boundary=---------------------------310662768914663
How can I get the correct value?
Thanks in advance
It sounds like as if you're homegrowing a multipart/form-data parser. I wouldn't recommend to do that. Rather use a decent one like Apache Commons FileUpload. For uploaded files, it offers a FileItem#getContentType() to extract the client-specified content type, if any.
String contentType = item.getContentType();
If it returns null (just because the client didn't specify it), then you can take benefit of ServletContext#getMimeType() based on the file name.
String filename = FilenameUtils.getName(item.getName());
String contentType = getServletContext().getMimeType(filename);
This will be resolved based on <mime-mapping> entries in servletcontainer's default web.xml (in case of for example Tomcat, it's present in /conf/web.xml) and also on the web.xml of your webapp, if any, which can expand/override the servletcontainer's default mappings.
You however need to keep in mind that the value of the multipart content type is fully controlled by the client and also that the client-provided file extension does not necessarily need to represent the actual file content. For instance, the client could just edit the file extension. Be careful when using this information in business logic.
Related:
How to upload files in JSP/Servlet?
How to check whether an uploaded file is an image?
just use:
public String ServletContext.getMimeType(String file)
You could use MimetypesFileTypeMap
String contentType = new MimetypesFileTypeMap().getContentType(fileName)); // gets mime type
However, you would encounter the overhead of editing the mime.types file, if the file type is not already listed. (Sorry, I take that back, as you could add instances to the map programmatically and that would be the first place that it checks)

Categories

Resources