Pass a parameter from java-embedded fop to xsl file - java

I've embedded fop in a java programm:
public class run {
public static void main(String [ ] args){
FopFactory fopFactory = FopFactory.newInstance();
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(new File("F:/test.pdf")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("F:/main_structure.xsl"));
Transformer transformer = factory.newTransformer(xslt);
Source src = new StreamSource(new File("F:/source.xml"));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
} catch (FOPException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} finally {
try {
out.close();
System.out.println("ende");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
now my xsl (main_structure.xsl) needs a parameter to run
<xsl:param name="OFFSET_LEFT" select="1"/>
in the console I would be using the "-param name value" attribute to pass that parameter to fop.
So how do I pass a parameter into my xsl file in the embedded version of fop?

For example read: http://www.onlamp.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=4
Transformer transformer = factory.newTransformer(xslt);
transformer.setParameter("PARAMETER", "VALUE");

Related

Premature end of file error. How to resolve? XML

I've been reading over this SAXParseException error for a while and trying to resolve it but to no success.
[Fatal Error] schedule.xml:1:1: Premature end of file.
org.xml.sax.SAXParseException; systemId: file:/U:/schedule.xml; lineNumber: 1; columnNumber: 1; Premature end of file.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at package.DOMclass.importDocument(DOMclass.java:681) //<---.parse(new File(fileToImport));
...
I've read how it could be the stream being used is empty (or xml file being read is empty), as well as it can't be reused? Also, the problem of reading and writing back to the same file. Here's a link that explains it but I still don't understand.
Also, another possibility could be that my xml is malformed/not correct but I've looked over it and it's fine, the tags are good and I've encoded it in UTF-8 (without BOM) in Notepad++ since some posts have said there might be hidden whitespace before the xml declaration but again, no success.
This is my reading in code
public TestClass(){
Node root = DOMclass.importDocument("U:\\schedule.xml");
... read nodes, attribute values, etc..
}
public static Document importDocument(String fileToImport)
{
Document document = null;
try
{
document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new File(fileToImport)); //<--- where the error is at
//Do I need a Reader here? to close?
}
catch(SAXException saxe)
{
saxe.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch(ParserConfigurationException pce)
{
pce.printStackTrace();
}
return document;
}
This is my writing out.
public static void addNode(String name, String lastName,...){
String filepath = "U;\\schedule.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
...
... make/traverse xml nodes, elements, appending
...
}
DOMUtils.exportDocument(doc, filepath);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void exportDocument(Document documentToExport, String fileName)
{
Transformer transformer = null;
DOMSource domSource = null;
StreamResult streamResult = null;
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
transformer = TransformerFactory.newInstance().newTransformer();
domSource = new DOMSource(documentToExport);
streamResult = new StreamResult(out);
System.out.println("\nStream Result: " + streamResult);
transformer.transform(domSource, streamResult);
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
catch(TransformerException e)
{
e.printStackTrace();
}
finally
{
transformer = null;
domSource = null;
streamResult = null;
}
}
}
Any thoughts? Thank you.

Convert an XML String to CSV file (Java) -> CSV Result is empty

I need help understanding why the XML String does not convert into a CSV file. Why is the CSV Resut always empty?
Here is an example of a Java Code
public class transformCSV_1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String xmlData = new String(
"<?xml version=\"1.0\"?><PurchaseOrder xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://localhost:8080/source/schemas/poSource/xsd/purchaseOrder.xsd\"><Reference>SBELL-2002100912333601PDT</Reference><Actions><Action><User>SVOLLMAN</User></Action></Actions><Requestor>Sarah J. Bell</Requestor><User>SBELL</User><CostCenter>S30</CostCenter><ShippingInstructions><name>Sarah J. Bell</name><address>400 Oracle Parkway Redwood Shores CA 94065 USA</address><telephone>650 506 7400</telephone></ShippingInstructions><SpecialInstructions>Air Mail</SpecialInstructions><LineItems><LineItem ItemNumber=\"1\"><Description>A Night to Remember</Description><Part Id=\"715515009058\" UnitPrice=\"39.95\" Quantity=\"2\"/></LineItem><LineItem ItemNumber=\"2\"><Description>The Unbearable Lightness Of Being</Description><Part Id=\"37429140222\" UnitPrice=\"29.95\" Quantity=\"2\"/></LineItem><LineItem ItemNumber=\"3\"><Description>Sisters</Description><Part Id=\"715515011020\" UnitPrice=\"29.95\" Quantity=\"4\"/></LineItem></LineItems></PurchaseOrder>");
String stylesheet = new String(
"<?xml version=\"1.0\" encoding=\"utf-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:output method=\"text\" /><xsl:variable name=\"delimiter\" select=\"','\" /><!-- define an array containing the fields we are interested in --><xsl:variable name=\"fieldArray\"><field>Reference</field><field>User</field><field>Reject</field><field>Requestor</field></xsl:variable><xsl:param name=\"fields\" select=\"document('')/*/xsl:variable[#name='fieldArray']/*\" /><xsl:template match=\"/\"><!-- output the header row --><xsl:for-each select=\"$fields\"><xsl:if test=\"position() != 1\"><xsl:value-of select=\"$delimiter\"/></xsl:if><xsl:value-of select=\".\" /></xsl:for-each><!-- output newline --><xsl:text>
</xsl:text><xsl:apply-templates select=\"PurchaseOrder\"/></xsl:template><xsl:template match=\"PurchaseOrder\"><xsl:variable name=\"currNode\" select=\".\" /><!-- output the data row --><!-- loop over the field names and find the value of each one in the xml --><xsl:for-each select=\"$fields\"><xsl:if test=\"position() != 1\"><xsl:value-of select=\"$delimiter\"/></xsl:if><xsl:value-of select=\"$currNode/*[name() = current()]\" /></xsl:for-each><!-- output newline --><xsl:text>
</xsl:text></xsl:template></xsl:stylesheet>");
InputStream xmlSource = new ByteArrayInputStream(
xmlData.getBytes("UTF-8"));
InputStream styleSource = new ByteArrayInputStream(
stylesheet.getBytes("UTF-8"));
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlSource);
StreamSource stylesource = new StreamSource(styleSource);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(stylesource);
Source source = new DOMSource(document);
Result outputTarget = new StreamResult(new File("src/resultI.csv"));
transformer.transform(source, outputTarget);
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Best way is to use XSLT to "transform" the XML to CSV --> Can someone give me hint?
Consider to load the XSLT code from a file or URI (instead of from a string) as otherwise your approach of doing <xsl:param name="fields" select="document('')/*/xsl:variable[#name='fieldArray']/*" /> where document('') tries to pull in the XSLT code again is likely to fail, unless you set up a special resolver.

Append data to already existing Sitemap.xml file

I have created sitemap using the com.redfin.sitemapgenerator jar, now I want to add nodes i.e the urls in the urlset at run time, I have checked that the sitemap already exists or not but now I am unable to append to the already existing sitemap.xml file.`public String searchforques()
throws IllegalArgumentException {
// TODO Auto-generated method stub
System.out.println("calledd");
WebSitemapGenerator sitemapGenerator = null;
WebSitemapUrl sitemapUrl = null;
File file=new File("C:\\sitemap\\sitemap.xml");
try {
if(!file.exists())
{
sitemapGenerator = WebSitemapGenerator
.builder("http://www.testing.com", new File("C:\\sitemap"))
.gzip(false).build();
/*------------------------------------------*/
try {
sitemapUrl = new WebSitemapUrl.Options(
"http://www.testing.com/#!dashboard1")
.lastMod(new Date()).priority(1.0)
.changeFreq(ChangeFreq.HOURLY).build();
System.out.println("-----------");
System.out.println("sitemapUrl :: "+sitemapUrl.getUrl());
sitemapGenerator.addUrl(sitemapUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/****************/
}
else
{
System.out.println("file already exist");
sitemapGenerator = WebSitemapGenerator
.builder("http://www.testing.com", file)
.gzip(false).build();
try {
sitemapGenerator
.addUrl("http://www.testing.com/#!ques");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("sitemapGenerator :: "+sitemapGenerator);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sitemapGenerator.write();
// this will configure the URL with lastmod=now, priority=1.0,
// changefreq=hourly
// You can add any number of urls here
return "";
}
But my else part is not working it directly goes to server fail.
I am working on java with gwt.
So, any one could help to add dynamically the nodes(urls) in the urlset at runtime.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
File file=new File("war/abc.xml"); //local war
String val=null;
if(!file.exists())
{
val= "not exist";
try {
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("urlset");
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
document.appendChild(rootElement);
Element url = document.createElement("url");
Element loc = document.createElement("loc");
loc.appendChild(document.createTextNode(urllink));
url.appendChild(loc);
Element lastmod = document.createElement("lastmod");
lastmod.appendChild(document.createTextNode(dateText));
url.appendChild(lastmod);
Element changefreq = document.createElement("changefreq");
changefreq.appendChild(document.createTextNode("always"));
url.appendChild(changefreq);
Element priority = document.createElement("priority");
priority.appendChild(document.createTextNode("1.0"));
url.appendChild(priority);
rootElement.appendChild(url);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try
{
transformer = transformerFactory.newTransformer();
}
catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(file);
// Output to console for testing
//StreamResult result = new StreamResult(System.out);
try
{
transformer.transform(source, result);
}
catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File saved!");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println("file already exist append ");
val="file already exist append ";
DocumentBuilder documentBuilder = null;
try {
documentBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Document document = null;
try {
document = documentBuilder.parse(file);
document.normalize();
} catch (SAXException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Element rootElement = document.getDocumentElement();
Element url = document.createElement("url");
Element loc = document.createElement("loc");
loc.appendChild(document.createTextNode(urllink));
url.appendChild(loc);
Element lastmod = document.createElement("lastmod");
lastmod.appendChild(document.createTextNode(dateText));
url.appendChild(lastmod);
Element changefreq = document.createElement("changefreq");
changefreq.appendChild(document.createTextNode("always"));
url.appendChild(changefreq);
Element priority = document.createElement("priority");
priority.appendChild(document.createTextNode("1.0"));
url.appendChild(priority);
rootElement.appendChild(url);
DOMSource source = new DOMSource(document);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StreamResult result = new StreamResult(file);
System.out.println("result :: "+result.toString());
try {
transformer.transform(source, result);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

How to disable prettyPrint xstream xml and still add stylesheet and prolog?

I can remove prettyprint in xml (all newlines/carriage returns) by using CompactWriter() but how to keep my prolog and stylesheets?
Currently I am using Writer class to add prolog and stylesheet using write method.
Below is my function to serialize an object.
private void serializeData(DiagData diagData){
fileinfo=new HashMap<String,String>();
XStream xstream = new XStream();
xstream.processAnnotations(DiagData.class);
FileOutputStream fileOutputStream=null;
Writer writer=null;
//CompactWriter writer=null;
xstream.registerConverter(new MapConverter());
try {
String path = Constants.XML_PATH+File.separator+Constants.DIRECTORY_NAME;
File diagnosticDir = new File(path);
String serialNumber=null;
IDataCollector dataCollector=new DataCollector();
serialNumber=dataCollector.getSerialNumber();
String fileName = new SimpleDateFormat("yyyyMMddhhmmss'.xml'").format(new Date());
if(serialNumber!=null)fileName=serialNumber+Constants.UNDERSCORE+fileName;
fileName=Constants.PHONEHOME+Constants.UNDERSCORE+fileName;
fileOutputStream = new FileOutputStream(path+File.separator+fileName);
writer = new OutputStreamWriter(fileOutputStream);
//writer = new CompactWriter(new OutputStreamWriter(fileOutputStream));
writer.write(Constants.PROLOG);
writer.write(Constants.STYLESHEET);
xstream.toXML(diagData, writer);
//xstream.marshal(diagData, writer);
} catch (FileNotFoundException e1) {
} catch (Exception e) {
} finally {
try {
fileOutputStream.close();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
If you look at the XStream documentation, they clearly state that you have to add the XML prolog yourself:
Why does XStream not write an XML declaration?
XStream is designed to write XML snippets, so you can embed its output into
an existing stream or string. You can write the XML declaration yourself into
the Writer before using it to call XStream.toXML(writer).
The following code should work. I removed most of your code, so you have to put it back. The purpose is just to give you a rough working example:
private static void serializeData(Object diagData) throws Exception {
XStream xstream = new XStream();
xstream.processAnnotations(DiagData.class);
FileOutputStream fileOutputStream = null;
Writer writer = new PrintWriter(new File(your file));
CompactWriter compactWriter = new CompactWriter(writer);
try {
writer.write(your xml prolog);
writer.write(your stylesheet);
xstream.marshal(diagData, compactWriter);
} catch (FileNotFoundException e1) {
} catch (Exception e) {
} finally {
release resources
}
}

Redirecting Error/Exception to HTML page

Needs to redirect the error and exceptions which i found in the catch block to .html page
This is my code now i want if anytime any file not found excpetion will come then it should redirect to .html page or borwser
public class XmlToHtml {
public static void main(String[] args) {
if (args.length == 3 && args.length !=0) {
String dataXML = args[0];
String inputXSL = args[1];
String outputHTML = args[2];
XmlToHtml xmltoHtml = new XmlToHtml();
try {
xmltoHtml.transform(dataXML, inputXSL, outputHTML);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
System.out.println("TransformerConfigurationException" + e);
} catch (TransformerException e) {
e.printStackTrace();
System.out.println("TransformerException" + e);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("FileNotFoundException" + e);
}
} else {
System.err.println("Wrong Input");
System.err
.println("Please Enter in the follwing format : Data.xml Input.xsl Output.html");
}
}
public void transform(String dataXML, String inputXSL, String outputHTML)
throws FileNotFoundException, TransformerException,
TransformerConfigurationException {
TransformerFactory tFactory = TransformerFactory.newInstance();
Source xslDoc = new StreamSource(inputXSL);
Source xmlDoc = new StreamSource(dataXML);
OutputStream htmlDoc = new FileOutputStream(outputHTML);
Transformer transformer = tFactory.newTransformer(xslDoc);
transformer.transform(xmlDoc, new StreamResult(htmlDoc));
Desktop dk = Desktop.getDesktop();
try {
dk.open(new File(outputHTML));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories