Flying saucer ignoring css - java

I have trouble displaying my xml file with the attached CSS. Below is my java code
package mainPackage;
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class pdf_test {
public static void main(String[] args) throws IOException, DocumentException {
String inputFile = "/Users/jgonzo4/Desktop/Coen174/COEN174/output.xml";
String outputFile = "test1.pdf";
OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new File(inputFile));
renderer.layout();
renderer.createPDF(os);
os.close();
}
}
The pdf gets created but it is just blank. Below is the xml file
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/Users/jgonzo4/Desktop/Coen174/COEN174/src/mainPackage/test.css"?>
<program_of_studies>
<student_info firstName="Jesus" lastName="Gonzalez" primaryEmail="email" secondaryEmail="email" home_phone="number" advisor="Teacher" last_modified="1383613851235" />
<grad_core_reqs />
<appl_math />
<focus_area_core />
<other_area_core />
<addit_elect_courses />
<transfer_cred_reqs />
<meta_data version="1.0.0" />
<history />
Here is the CSS file that should work
student_info:before {
font-size: 115%;
content:attr(firstName)""attr(middleName)" "attr(lastName)" "attr(primaryEmail);
display: block;
}
student_info:after {
font-size: 115%;
content:attr(secondaryEmail)" "attr(home_phone)" "attr(advisor);
display: block;
}
This works exactly the way I want it on a browser so I'm guessing that I am doing something wrong in my java function. Please let me know of any suggestions

Related

Getting a pdf for an Alfresco Java Webscript Controller

I'm trying to build a simple Webscript Endpoint in Alfresco that gets a pdf using a Java Webscript controller. We eventually want to expand this endpoint to take multiple pdfs and do some manipulation, but for right now we are just trying to read in and save 1 pdf.
The problem is the resulting InputStream is empty. This is despite it working just fine for xml files.
This is our uploadpdf.get.desc
<webscript>
<shortname>Upload PDFs</shortname>
<description>Upload PDFs</description>
<url>/uploadpdf</url>
<authentication>user</authentication>
<format default="html"></format>
</webscript>
This is our uploadpdf.get.html.ftl
<html>
<body>
<form action="${url.service}" method="post" enctype="multipart/form-data">
PDF1: <input type="file" name="pdf1"><br>
XML1: <input type="file" name="xml1"><br>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
This is our uploadpdf.post.dec
<webscript>
<shortname>Upload PDFs</shortname>
<description>Upload PDFs</description>
<url>/uploadpdf</url>
<authentication>user</authentication>
<format default="json"></format>
</webscript>
This is our uploadpdf.post.json.ftl (currently just returning a test string)
${newFile}
This is our Webscript-context.xml
<?xml version='1.0' encoding='UTF-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="webscript.alfresco.tutorials.helloworld.get"
class="com.test.platformsample.HelloWorldWebScript"
parent="webscript">
</bean>
<bean id="webscript.uploadpdf.get"
class="com.test.UploadPdfWebScript"
parent="webscript">
</bean>
<bean id="webscript.uploadpdf.post"
class="com.test.UploadPdfWebScript"
parent="webscript">
</bean>
</beans>
And this is our UploadPdfWebscript.java (notice for testing purposes we are using org.springframework.extensions.webscripts.servlet.FormData;
This is to easily get the file. The code then saves the file to the local docker container. The problem is that file and by extention the InputStream is empty.
package com.test;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.servlet.FormData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
public class UploadPdfWebScript extends DeclarativeWebScript {
private static Log logger = LogFactory.getLog(UploadPdfWebScript.class);
protected Map<String, Object> executeImpl(
WebScriptRequest req, Status status, Cache cache) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("fromJava", "HelloFromJava");
logger.debug("Your 'UploadPdf' Web Script was called!");
final FormData form = (FormData)req.parseContent();
InputStream file1 = null;
if(form == null || form.getFields() == null) {
return model;
}
for (FormData.FormField field : form.getFields())
{
if (field.getName().equals("pdf1"))
{
file1 = field.getInputStream();
}
}
String result = "this should be overwritten";
try{
result = processFile(file1);
} catch(Exception e) {
logger.error(e.getMessage());
}
if(result == null || result.equals("")) {
result = "No result";
}
model.put("newFile", result);
return model;
}
public String processFile(InputStream file) {
String ret = "{\”Result\": Success}”;
try {
byte[] buffer = new byte[file.available()];
file.read(buffer);
File targetFile = new File("targetFile.pdf");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer2);
} catch (Exception e) {
ret = "{\”Result\": Failure}”;
logger.error(e.getMessage(), e);
}
return ret;
}
How can I get a pdf or other arbitrary file type from the InputStream? Again the InputStream that is returned from the form is empty whenever I try to upload a pdf and as a result so is the saved pdf.
Note: If I try to read the pdf from the local file system rather than sending it via a post request, this works fine. The pdf I'm uploading is definitely valid and not empty. I also know the webscript is being properly called as it is posting a log message, returning Success, and creating the targetFile.pdf which is empty.
Change this line:
outStream.write(buffer2);
To:
outStream.write(buffer);
Here's what shows up in the tomcat dir on my Docker container:
-rw-r----- 1 root root 117249 Aug 7 19:28 targetFile.pdf
Looks like it works!

Impossible to load image in jsp?

I am having this little problem, I see that it is impossible to load picture in my console, I don't know how to solve the problem.
I am getting my image name from database as a String in my controller, just the name, something like that ' image.jpg' and it is stored in my folder 'images'.
Here is my jsp file :
<c:if test="${ !(post.cover == 'empty')}">
<div class="imgPub">
<img src="Assets/images/${post.cover }">
</div>
</c:if>
In my inspector i can see the whole src written exactly, but a message next to it saying impossible to load image.
Any help would be much appreciated.
HttpServlet will do the job.
use:
youraddress.xxx/images/filename.png
this is important #WebServlet("/images/*")
It will automatically leads to folder defined in PATH and retrieve the image based on the name.
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
#WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
public static final String PATH = "C:/"
/*
linux
public static final String PATH = "/home/images/"
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getPathInfo().substring(1);
File file = new File(PATH,filename);
response.setHeader("Content-Type", getServletContext().getMimeType(filename));
response.setHeader("Content-Length",String.valueOf(file.length()));
response.setHeader("Content-Disposition","inline; filename=\""+filename +"\"");
Files.copy(file.toPath(),response.getOutputStream());
}
}

How to read data from xml attributes recurssively and store it in CSV in Java

I have the xml data as follows below,
<?xml version="1.0" encoding="ISO-8859-1"?>
<FIXML xsi:schemaLocation="http://www.fixprotocol.org/FIXML-5-0-SP2 fixml-main-5-0-SP2_.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" s="2012-04-23" v="FIX.5.0SP2">
<Batch ID="RPTTA111PUBLI20170509">
<MktDef MktID="XEUR" MktSegID="14" EfctvBizDt="2017-05-11" NxtEfctvBizDt="2017-05-15" MktSeg="CONF" MarketSegmentDesc="FUT 8-13 Y. SWISS GOV.BONDS 6%" Sym="CH0002741988" ParentMktSegmID="FBND" Ccy="CHF" MktSegStat="1" USFirmFlag="Y" PartID="2">
<MtchRules MtchRuleProdCmplx="5" MtchAlgo="PT" />
<MtchRules MtchRuleProdCmplx="1" MtchAlgo="PT" />
<FlexProdEligs FlexProdEligCmplx="5" FlexProdElig="Y" />
<BaseTrdgRules QtSideInd="1" FastMktPctg="0">
<TickRules TickRuleProdCmplx="1" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.01" />
<TickRules TickRuleProdCmplx="5" StartTickPxRng="0" EndTickPxRng="99999.9999" TickIncr="0.01" />
<QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="0" />
<QuotSizeRules MinBidSz="1" MinOfrSz="1" FastMktInd="1" />
<PxRngRules PxRngRuleID="75" PxRngProdCmplx="1" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.15" />
<PxRngRules PxRngRuleID="347" PxRngProdCmplx="5" StartPxRng="0" EndPxRng="99999.9999" PxRngValu="0.12" />
</BaseTrdgRules>
<MDFeedTyps MDFeedTyp="HS" MDBkTyp="2" MktDepth="10" MDRcvryTmIntvl="120000" SvcLctnID1="224.0.50.102" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.230" SvcLctnSubID2="59500" />
<MDFeedTyps MDFeedTyp="HI" MDBkTyp="2" MktDepth="10" MktDepthTmIntvl="0" SvcLctnID1="224.0.50.103" SvcLctnSubID1="59501" SvcLctnID2="224.0.50.231" SvcLctnSubID2="59501" />
<MDFeedTyps MDFeedTyp="HI" MDBkTyp="3" MktDepthTmIntvl="0" SvcLctnID1="224.0.114.97" SvcLctnSubID1="59501" SvcLctnID2="224.0.114.113" SvcLctnSubID2="59501" />
<MDFeedTyps MDFeedTyp="HS" MDBkTyp="3" SvcLctnID1="224.0.114.96" SvcLctnSubID1="59500" SvcLctnID2="224.0.114.112" SvcLctnSubID2="59500" />
<MDFeedTyps MDFeedTyp="L" MDBkTyp="2" MktDepth="5" MktDepthTmIntvl="3500" MDRcvryTmIntvl="30000" SvcLctnID1="224.0.50.89" SvcLctnSubID1="59500" SvcLctnID2="224.0.50.217" SvcLctnSubID2="59500" />
</MktDef>
<SecDef PriSetPx="158.39">
<Instrmt ID="408805" Src="M" SecTyp="FUT" Status="1" ProdCmplx="1" CFI="FFMPSX" MatDt="2017-06-08" MMY="201706" Mult="1" ValMeth="FUT" SettlMeth="P" SettlSubMeth="4" PxPrcsn="2" MinPxIncr="0.01" MinPxIncrAmt="10">
<AID AltID="1048612" AltIDSrc="M" />
<AID AltID="XF000001RQD8" AltIDSrc="4" />
<Evnt EventTyp="7" Dt="2017-06-08" />
</Instrmt>
<MktSegGrp MktSegID="14">
<SecTrdgRules>
<BaseTrdgRules>
<PxRngRules PxRngRuleID="75" />
</BaseTrdgRules>
</SecTrdgRules>
</MktSegGrp>
</SecDef>
</Batch>
</FIXML>
I want to read the data from this XML and store it in CSV file as below.
Column names should be the RootElementName_ChildElementName(if we have)_AttributeName. This format I should follow,
Suppose RootElement is FIXML and we have attributes "s" and "v" so the column name should be as follows FIXML_s, FIXML_v.
And the Child Elements Batch and MktDef the column names should be
FIXML_Batch_ID and FIXML_Batch_MktDef_MktID like that it follows.
1) FIXML_s FIXML_v FIXML_Batch_ID FIXML_Batch_MktDef_MktID . . . . .
"2012-04-23" "FIX.5.0SP2" RPTTA111PUBLI20170509 XEUR ....
.
.
.
We have data like that for thousands of lines and when it reaches to the "</SecDef>" the data should print in 2nd line and 3rd line like that it continues.
Can someone guide me on this. I am very new to working on XML data.
You can take this is as a sample
where
you have to desgn your own
style.xsl
hear is mine
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="text" omit-xml-declaration="yes" indent="no" />
<xsl:template match="/">
topic,title,url
<xsl:for-each select="//topic"><xsl:value-of select="#id" /><xsl:value-of select="concat(',' , title, ',' , url,' ')" /></xsl:for-each></xsl:template>
</xsl:stylesheet>
this is the converter
import org.w3c.dom.Document;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class XMLToCSV {
public static void main(String args[]) throws Exception {
File stylesheet = new File("/home/1/style.xsl");
File xmlSource = new File("/home/1/xml.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlSource);
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
Source source = new DOMSource(document);
Result outputTarget = new StreamResult(new File("/home/1/howto.csv"));
transformer.transform(source, outputTarget);
System.out.println("Done.");
}
}
You can formatt the output as you want using this
This is how my xml looks like
<?xml version="1.0"?>
<howto>
<topic id="1">
<title>Java</title>
<url>http://www.google.com</url>
</topic>
<topic id="2">
<title>XML</title>
<url>http://www.ab</url>
</topic>
<topic id="3">
<title>Javascript</title>
<url>http://www.tt</url>
</topic>
<topic id="4">
<title>VBScript</title>
<url>http://www.wewe</url>
</topic>
</howto>
Hope this helped ...

File not found exception when using XPath for XML parsing

I am trying to write a Java program to add attribute to an already existing XML file.The XML is :
<Items ApplyDifferences="Y" ValidateItems="Y" CompleteInventoryFlag="Y" ShipNode=" ACMEUSDC" >
<Item InventoryOrganizationCode="ACMEUS" ItemID="2000033672234"
ProductClass="GOOD" UnitOfMeasure="EACH">
<Supplies>
<Supply AvailabilityType="TRACK" Quantity="20.00" ShipByDate="2500-01-01"
SupplyType="ONHAND"/>
</Supplies>
</Item>
<Item InventoryOrganizationCode="ACMEUS" ItemID="2000033672235"
ProductClass="GOOD" UnitOfMeasure="EACH">
<Supplies>
<Supply AvailabilityType="TRACK" Quantity="25.00" ShipByDate="2500-01-01"
SupplyType="ONHAND"/>
</Supplies>
</Item>
<Item InventoryOrganizationCode="ACMEUS" ItemID="2000033672236"
ProductClass="GOOD" UnitOfMeasure="EACH">
<Supplies>
<Supply AvailabilityType="TRACK" Quantity="25.00" ShipByDate="2500-01-01"
SupplyType="ONHAND"/>
</Supplies>
</Item>
</Items>
My Java code is:
package xmltest;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Testxml4 {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformerException {
// TODO Auto-generated method stub
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File inputFile = new File("C:/Users/praveen.sharma/Desktop/XMLs/xml4.xml");
System.out.println(new File(".").getAbsolutePath());
System.out.println(inputFile.exists());
Document doc = builder.parse(inputFile);
Element element = (Element) XPathAPI.selectSingleNode(doc,"Order/OrderLines/OrderLine[#PrimeLineNo='6']/OrderLineSourcingControls/OrderLineSourcingCntrl[#Node='Node1']");
element.setAttribute("Node", "Node02");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(inputFile);
transformer.transform(source, result);
}
}
This is the error I am getting:
Exception in thread "main" javax.xml.transform.TransformerException: java.io.FileNotFoundException: file:\C:\Users\praveen.sharma\Desktop\XMLs\xml4.xml (The filename, directory name, or volume label syntax is incorrect)
at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(TransformerIdentityImpl.java:263)
at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:296)
at xmltest.Testxml4.main(Testxml4.java:46)
Caused by: java.io.FileNotFoundException: file:\C:\Users\praveen.sharma\Desktop\XMLs\xml4.xml (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(TransformerIdentityImpl.java:253)
... 2 more
---------
java.io.FileNotFoundException: file:\C:\Users\praveen.sharma\Desktop\XMLs\xml4.xml (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at org.apache.xalan.transformer.TransformerIdentityImpl.createResultContentHandler(TransformerIdentityImpl.java:253)
at org.apache.xalan.transformer.TransformerIdentityImpl.transform(TransformerIdentityImpl.java:296)
at xmltest.Testxml4.main(Testxml4.java:46)
I can assure you my XML is present at the specified path and has all required permission.
You are trying to write the output to the same file from where you are reading. You should write to a different file instead.
If you want to "change" the same file, then the safest way is to write to a temporary file, then close all streams, then delete the original file and then rename the temporary file to the original name.

Fatal Error - Content is not allowed in prolog

Similar to this question, but unfortunately didn't help
I am trying to parse a String to XML in Java and keep getting the error:
[Fatal Error] output.txt:1:1: Content is not allowed in prolog.
I know it must be something to do with my XML string, because I ran a test with very basic XML and the error dissappeared.
XML
<?xml version="1.0" encoding="UTF-8"?>
<?xfa generator="ff99v250_01" APIVersion="1.4.3139.0"?>
<jfxpf:XPF xmlns:jfxpf="http://www.xfa.com/schema/xml-package">
<jfxpf:Package>
<jfxpf:Resource Location="GenReq">
<jfxpf:Link ContentType="application/x-jetform-cft" />
</jfxpf:Resource>
<jfxpf:Resource Location="default.xml">
<jfxpf:Content ContentType="text/xml" Location="default.xml">
<xfa:Data xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:DataGroup>
<data xmlns:xfe="http://www.xfa.org/schema/xfa-events/1.0" xfe:script="$config.proto.common.template.uri='GenReq'" xfe:event="$config:load">
<?jetform ^Dat ^page 1?>
<FR_NAME>Administrator</FR_NAME>
<JFWF_DELEGATE />
<ADHOC_DLN_ACTOR />
<ADHOC_DLN_MSG />
<ADHOC_DLN_TIME />
<ADHOC_DLN_UNITS>Days</ADHOC_DLN_UNITS>
<ADHOC_RMD_MSG />
<ADHOC_RMD_TIME />
<ADHOC_RMD_UNITS>Days</ADHOC_RMD_UNITS>
<ADHOC_RPT_TIME />
<ADHOC_RPT_UNITS>Days</ADHOC_RPT_UNITS>
<CIRCULATETO />
<COMPLETION />
<FOLLOWUP />
<MSGSUBJECT />
<OTHERFIELD />
<PRIORITY>Low</PRIORITY>
<REQUEST />
<RESPONSE />
<Submit />
<ADHOC_VALIDDATA>True</ADHOC_VALIDDATA>
<JFWF_TRANID>2xxyg9sffane7pwd5j8yv9t49s.1</JFWF_TRANID>
<JFWF_INSTRUCTION>Initiate a General Request. Fill the request form, then identify the next participant.</JFWF_INSTRUCTION>
<JFWF_TRANSPORT>HTTP</JFWF_TRANSPORT>
<JFWF_STATUS>RECEIVED</JFWF_STATUS>
<JFWF_ACTION />
<JFWF_CHOICE>*Select Next Participant,Cancel</JFWF_CHOICE>
<JFWF_VERSION>6.2</JFWF_VERSION>
<JFWF_READONLY>1</JFWF_READONLY>
</data>
</xfa:DataGroup>
</xfa:Data>
</jfxpf:Content>
</jfxpf:Resource>
</jfxpf:Package>
</jfxpf:XPF>
However, I am having trouble finding the text that is causing this issue. My Java code is below:
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
EDIT
Removing the Data node works, so the error is somewhere deep in the XML. This does not throw an error:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<?xfa generator=\"ff99v250_01\" APIVersion=\"1.4.3139.0\"?>
<jfxpf:XPF xmlns:jfxpf=\"http://www.xfa.com/schema/xml-package\">
<jfxpf:Package>
<jfxpf:Resource Location=\"GenReq\">
<jfxpf:Link ContentType=\"application/x-jetform-cft\"/>
</jfxpf:Resource>
<jfxpf:Resource Location=\"default.xml\">
<jfxpf:Content ContentType=\"text/xml\" Location=\"default.xml\">
</jfxpf:Content>
</jfxpf:Resource>
</jfxpf:Package>
</jfxpf:XPF>
My Imports
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
My guess is that the file starts with a BOM character U+FEFF: error at line 1, column 1.This is a zero-width space used sometimes to mark a file as being in some Unicode representation, UTF-8, UTF-16LE, UTF-16BE.
The BOM character can be removed. Check the file size, and then look what options you have: save as UTF-8 without BOM, delete.
In java (should the editor be stubborn):
Path path = Paths.get(".... .xml");
byte[] content = Files.readAllBytes(path);
String s = new String(content, StandardCharsets.UTF_8);
s = s.replaceFirst("^\uFEFF", "");
byte[] content2 = s.getBytes(StandardCharsets.UTF_8);
if (content2.length != content.length) {
Files.write(path, content2);
}
The document and sample code you provided works fine in Java 1.8u25:
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class FatalErrorTest
{
#Test
public void as_given() throws SAXException, IOException, ParserConfigurationException
{
String xml ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<?xfa generator=\"ff99v250_01\" APIVersion=\"1.4.3139.0\"?>\r\n<jfxpf:XPF xmlns:jfxpf=\"http://www.xfa.com/schema/xml-package\">\r\n <jfxpf:Package>\r\n <jfxpf:Resource Location=\"GenReq\">\r\n <jfxpf:Link ContentType=\"application/x-jetform-cft\" />\r\n </jfxpf:Resource>\r\n <jfxpf:Resource Location=\"default.xml\">\r\n <jfxpf:Content ContentType=\"text/xml\" Location=\"default.xml\">\r\n <xfa:Data xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\">\r\n <xfa:DataGroup>\r\n <data xmlns:xfe=\"http://www.xfa.org/schema/xfa-events/1.0\" xfe:script=\"$config.proto.common.template.uri='GenReq'\" xfe:event=\"$config:load\">\r\n <?jetform ^Dat ^page 1?>\r\n <FR_NAME>Administrator</FR_NAME>\r\n <JFWF_DELEGATE />\r\n <ADHOC_DLN_ACTOR />\r\n <ADHOC_DLN_MSG />\r\n <ADHOC_DLN_TIME />\r\n <ADHOC_DLN_UNITS>Days</ADHOC_DLN_UNITS>\r\n <ADHOC_RMD_MSG />\r\n <ADHOC_RMD_TIME />\r\n <ADHOC_RMD_UNITS>Days</ADHOC_RMD_UNITS>\r\n <ADHOC_RPT_TIME />\r\n <ADHOC_RPT_UNITS>Days</ADHOC_RPT_UNITS>\r\n <CIRCULATETO />\r\n <COMPLETION />\r\n <FOLLOWUP />\r\n <MSGSUBJECT />\r\n <OTHERFIELD />\r\n <PRIORITY>Low</PRIORITY>\r\n <REQUEST />\r\n <RESPONSE />\r\n <Submit />\r\n <ADHOC_VALIDDATA>True</ADHOC_VALIDDATA>\r\n <JFWF_TRANID>2xxyg9sffane7pwd5j8yv9t49s.1</JFWF_TRANID>\r\n <JFWF_INSTRUCTION>Initiate a General Request. Fill the request form, then identify the next participant.</JFWF_INSTRUCTION>\r\n <JFWF_TRANSPORT>HTTP</JFWF_TRANSPORT>\r\n <JFWF_STATUS>RECEIVED</JFWF_STATUS>\r\n <JFWF_ACTION />\r\n <JFWF_CHOICE>*Select Next Participant,Cancel</JFWF_CHOICE>\r\n <JFWF_VERSION>6.2</JFWF_VERSION>\r\n <JFWF_READONLY>1</JFWF_READONLY>\r\n </data>\r\n </xfa:DataGroup>\r\n </xfa:Data>\r\n </jfxpf:Content>\r\n </jfxpf:Resource>\r\n </jfxpf:Package>\r\n</jfxpf:XPF>";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
assertNotNull(doc);
}
}

Categories