Cannot find Package fop ( Ithink) - java

Hello friends I try to use fop engine programatically I search for an example and I find this class
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXResult;
import org.apache.avalon.framework.ExceptionUtil;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.apache.fop.messaging.MessageHandler;
public class Invokefop
{
public void convertXML2PDF(File xml, File xslt, File pdf)
throws IOException, FOPException, TransformerException {
Driver driver = new Driver();
Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
driver.setLogger(logger);
MessageHandler.setScreenLogger(logger);
driver.setRenderer(Driver.RENDER_PDF);
OutputStream out = new java.io.FileOutputStream(pdf);
try {
driver.setOutputStream(out);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(xslt));
Source src = new StreamSource(xml);
Result res = new SAXResult(driver.getContentHandler());
transformer.transform(src, res);
} finally {
out.close();
}
}
public static void main(String[] args) {
try {
System.out.println("JAVA XML2PDF:: FOP ExampleXML2PDF\n");
System.out.println("JAVA XML2PDF:: Preparing...");
File base = new File("../");
File baseDir = new File(base, "in");
File outDir = new File(base, "out");
outDir.mkdirs();
File xmlfile = new File(baseDir, args[0]);
File xsltfile = new File(baseDir, args[1]);
File pdffile = new File(outDir, args[2]);
System.out.println("JAVA XML2PDF:: Input: XML (" + xmlfile + ")");
System.out.println("JAVA XML2PDF:: Stylesheet: " + xsltfile);
System.out.println("JAVA XML2PDF:: Output: PDF (" + pdffile + ")");
System.out.println();
System.out.println("JAVA XML2PDF:: Transforming...");
Invokefop app = new Invokefop();
app.convertXML2PDF(xmlfile, xsltfile, pdffile);
System.out.println("JAVA XML2PDF:: Success!");
} catch (Exception e) {
System.err.println(ExceptionUtil.printStackTrace(e));
System.exit(-1);
}
}
}
All the Libs from Fop are in the Classpath including the fop.jar in build directory. After
I run thejavac Invokefop.java I get this error:
> C:\....\fop>javac Invokefop.java
Invokefop.java:21: cannot find symbol
symbol : class Driver
location: package org.apache.fop.apps
import org.apache.fop.apps.Driver;
^
Invokefop.java:23: package org.apache.fop.messaging does not exist
import org.apache.fop.messaging.MessageHandler;
^
Invokefop.java:31: cannot find symbol
symbol : class Driver
location: class Invokefop
Driver driver = new Driver();
^
Invokefop.java:31: cannot find symbol
symbol : class Driver
location: class Invokefop
Driver driver = new Driver();
^
Invokefop.java:36: cannot find symbol
symbol : variable MessageHandler
location: class Invokefop
MessageHandler.setScreenLogger(logger);
^
Invokefop.java:39: cannot find symbol
symbol : variable Driver
location: class Invokefop
driver.setRenderer(Driver.RENDER_PDF);
^
6 errors
I am relatively new to Java, but with this approach I try to execute the fop engine in c++ using this java class..
Have anybody some Idea, how to solve this errors...
Thanx in advance..

The classes that are coming up with "cannot find symbol" errors don't exist in the fop.jar file.
I just downloaded v0.95 of the FOP library, and I can't see those classes in any of the jar files in the distribution. (You can open a jar file in any zip program and have a look - a jar is basically a zip file with a few extra bits in there that Java uses).
I would guess that the classes referenced in your example code were removed at some stage from the FOP library, and the example is for the older version. So you could try and find an older version of the library that contains those classes, or look for newer examples. The binary distribution comes with some examples - maybe have a look through those to see if any are useful for you?

In my case I added the dependency in pom.xml
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>fop</artifactId>
<version>2.5</version>
</dependency>

Related

Run java class from cmd with full path?

I have compile a java file
javac XSDValidator.java
And I get a XSDValidator.class
Lets say I have the the class (XSDValidatorc.class) file in
C:\xampp\htdocs\xsd_validtion
And I write this in cmd
C:\xampp\htdocs\xsd_validtion> java XSDValidator students.xsd students.xml
It works fine. But its not working if I I'am in another directory and want to run the file with absolute path. Why doesn't it work?
Lite this, lets say I'am in the directory
C:\aaa\User\Document
And write like this it's not working.
java C:\xampp\htdocs\xsd_validtion\XSDValidator C:\xampp\htdocs\xsd_validtion\students.xsd C:\xampp\htdocs\xsd_validtion\students.xml
This is the java-file
https://www.tutorialspoint.com/xsd/xsd_validation.htm
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class XSDValidator {
public static void main(String[] args) {
if(args.length !=2){
System.out.println("Usage : XSDValidator <file-name.xsd> <file-name.xml>" );
} else {
boolean isValid = validateXMLSchema(args[0],args[1]);
if(isValid){
System.out.println(args[1] + " is valid against " + args[0]);
} else {
System.out.println(args[1] + " is not valid against " + args[0]);
}
}
}
public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
} catch (IOException e){
System.out.println("Exception: "+e.getMessage());
return false;
}catch(SAXException e1){
System.out.println("SAX Exception: "+e1.getMessage());
return false;
}
return true;
}
}
use the java classpath:
java -cp C:\xampp\htdocs\xsd_validtion\ XSDValidator C:\xampp\htdocs\xsd_validtion\students.xsd C:\xampp\htdocs\xsd_validtion\students.xml
This includes the directory where the class file is located to the classpath.
directories in java are package structures. Thats why you can not use it as a normal Path
The answer from Jens
java -cp C:\xampp\htdocs\xsd_validtion\ XSDValidator C:\xampp\htdocs\xsd_validtion\students.xsd C:\xampp\htdocs\xsd_validtion\students.xml
can be the accepted one. I just want to give another solution, in some situations, it's better
CD C:\xampp\htdocs\xsd_validtion
java XSDValidator students.xsd students.xml
CD C:\aaa\User\Document

Set up URI or catalog resolver with Saxon/XQuery

I am developing a simple command line application in Java to mine data from a large XML data set (15,000+ XML files). I have chosen to use Saxon S9API as the XQuery processor for this. Everything works fine so long as there is open access to the internet where the parser used by Saxon can resolve the xsi:noNamespaceSchemaLocation URI (or any other I will assume).
I have scoured Stackoverflow, as well as general Google searching, for answers on how to provide a catalog to the XQuery processor. I have not found a good explanation on how to do so.
This is the simple code I have at this point, which as I stated works fine when there is open access the Internet:
package ipd.part.info.mining.app;
import java.io.File;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
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.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import net.sf.saxon.Configuration;
import net.sf.saxon.TransformerFactoryImpl;
import net.sf.saxon.s9api.DOMDestination;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XQueryCompiler;
import net.sf.saxon.s9api.XQueryEvaluator;
import net.sf.saxon.s9api.XQueryExecutable;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.lib.*;
import static org.apache.xerces.jaxp.JAXPConstants.JAXP_SCHEMA_LANGUAGE;
import static org.apache.xerces.jaxp.JAXPConstants.W3C_XML_SCHEMA;
import org.apache.xerces.util.XMLCatalogResolver;
import org.apache.xml.resolver.tools.CatalogResolver;
import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
/**
*
* #author tfurst
*/
public class IPDPartInfoMiningApp {
/**
* #param args the command line arguments
*/
private static Scanner scanner = new Scanner(System.in);
private static String ietmPath;
private static String outputPath;
private static CatalogResolver resolver;
private static org.apache.xerces.util.XMLCatalogResolver xres;
private static ErrorHandler eHandler;
private static DocumentBuilderFactory DBF;
private static DocumentBuilder DB;
public static void main(String[] args) {
initDb();
try {
// TODO code application logic here
System.out.println("Enter path to complete IETM Export:");
ietmPath = scanner.nextLine();
System.out.println("Enter path to save report:");
outputPath = scanner.nextLine();
Processor proc = new Processor(true);
XQueryCompiler comp = proc.newXQueryCompiler();
//File xq = fixXquery(new File(XQ));
//XQueryExecutable exp = comp.compile(xq);
XQueryExecutable exp = comp.compile("declare variable $path external;\n" +
"\n" +
"let $coll := collection(concat($path,'?select=*.xml'))//itemSequenceNumber \n" +
"\n" +
"return\n" +
"<parts>\n" +
"{\n" +
" for $mod in $coll\n" +
" let $pn := normalize-space($mod/partNumber)\n" +
" let $nomen := $mod/partIdentSegment[1]/descrForPart\n" +
" let $smr := $mod/locationRcmdSegment/locationRcmd/sourceMaintRecoverability\n" +
" order by $pn\n" +
" return <part pn=\"{$pn}\" nomen=\"{$nomen}\" smr=\"{$smr}\"/>\n" +
"}\n" +
"</parts>");
//Serializer out = proc.newSerializer(System.out);
Document dom = DB.newDocument();
XQueryEvaluator ev = exp.load();
ev.setExternalVariable(new QName("path"), new XdmAtomicValue(new File(ietmPath).toPath().toUri().toString().substring(0, new File(ietmPath).toPath().toUri().toString().lastIndexOf("/"))));
ev.run(new DOMDestination(dom));
TransformerFactoryImpl tfact = new net.sf.saxon.TransformerFactoryImpl();
Transformer trans = tfact.newTransformer();
DOMSource src = new DOMSource(dom);
StreamResult res = new StreamResult(new File(outputPath + File.separator + "output.xml"));
trans.transform(src, res);
} catch (SaxonApiException | TransformerException ex) {
Logger.getLogger(IPDPartInfoMiningApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static XMLCatalogResolver createXMLCatalogResolver(CatalogResolver resolver)
{
int i = 0;
List files = resolver.getCatalog().getCatalogManager().getCatalogFiles();
String[] catalogs = new String[files.size()];
XMLCatalogResolver xcr = new XMLCatalogResolver();
for(Object file : files)
{
catalogs[i] = new File(file.toString()).getAbsolutePath();
}
xcr.setCatalogList(catalogs);
return xcr;
}
private static void initDb()
{
try
{
resolver = new CatalogResolver();
eHandler = new DocumentErrorHandler();
xres = createXMLCatalogResolver(resolver);
DBF = DocumentBuilderFactory.newInstance();
DBF.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
DBF.setNamespaceAware(true);
DB = DBF.newDocumentBuilder();
DB.setEntityResolver(xres);
DB.setErrorHandler(eHandler);
}
catch (ParserConfigurationException ex)
{
ex.printStackTrace();
}
}
}
I am receiving this error when I disconnect my machine from the network:
C:\Users\tfurst\Desktop\XQuery Test\testXml\test\tool>java -jar IPD_Part_Info_Mining_App.jar
Enter path to complete IETM Export:
C:\Users\tfurst\Desktop\Wire Repl Testing
Enter path to save report:
C:\Users\tfurst\Desktop\Wire Repl Testing\report
Error on line 6 column 2
collection(): failed to parse XML file
file:/C:/Users/tfurst/Desktop/Wire%20Repl%20Testing/DMC-HH60W-A-52-21-0001-04AAA-520A-B.xml: I/O error reported by XML parser processing file:/C:/Users/tfurst/Desktop/Wire%20Repl%20Testing/DMC-HH60W-A-52-21-0001-04AAA-520A-B.xml: Read timed out
Aug 20, 2019 2:55:23 PM ipd.part.info.mining.app.IPDPartInfoMiningApp main
SEVERE: null
net.sf.saxon.s9api.SaxonApiException: collection(): failed to parse XML file file:/C:/Users/tfurst/Desktop/Wire%20Repl%20Testing/DMC-HH60W-A-52-21-0001-04AAA-520A-B.xml: I/O error reported by XML parser processing file:/C:/Users/tfurst/Desktop/Wire%20Repl%20Testing/DMC-HH60W-A-52-21-0001-04AAA-520A-B.xml: Read timed out
at net.sf.saxon.s9api.XQueryEvaluator.run(XQueryEvaluator.java:372)
at ipd.part.info.mining.app.IPDPartInfoMiningApp.main(IPDPartInfoMiningApp.java:80)
Caused by: net.sf.saxon.trans.XPathException: collection(): failed to parse XML file file:/C:/Users/tfurst/Desktop/Wire%20Repl%20Testing/DMC-HH60W-A-52-21-0001-04AAA-520A-B.xml: I/O error reported by XML parser processing file:/C:/Users/tfurst/Desktop/Wire%20Repl%20Testing/DMC-HH60W-A-52-21-0001-04AAA-520A-B.xml: Read timed out
at net.sf.saxon.resource.XmlResource.getItem(XmlResource.java:113)
at net.sf.saxon.functions.CollectionFn$2.mapItem(CollectionFn.java:246)
at net.sf.saxon.expr.ItemMappingIterator.next(ItemMappingIterator.java:113)
at net.sf.saxon.expr.ItemMappingIterator.next(ItemMappingIterator.java:108)
at net.sf.saxon.expr.ItemMappingIterator.next(ItemMappingIterator.java:108)
at net.sf.saxon.om.FocusTrackingIterator.next(FocusTrackingIterator.java:85)
at net.sf.saxon.expr.ContextMappingIterator.next(ContextMappingIterator.java:59)
at net.sf.saxon.expr.sort.DocumentOrderIterator.<init>(DocumentOrderIterator.java:47)
at net.sf.saxon.expr.sort.DocumentSorter.iterate(DocumentSorter.java:230)
at net.sf.saxon.expr.flwor.ForClausePush.processTuple(ForClausePush.java:34)
at net.sf.saxon.expr.flwor.FLWORExpression.process(FLWORExpression.java:841)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:337)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:284)
at net.sf.saxon.expr.instruct.Instruction.process(Instruction.java:151)
at net.sf.saxon.query.XQueryExpression.run(XQueryExpression.java:411)
at net.sf.saxon.s9api.XQueryEvaluator.run(XQueryEvaluator.java:370)
... 1 more
C:\Users\tfurst\Desktop\XQuery Test\testXml\test\tool>pause
Press any key to continue . . .
I am sure this is probably a relatively simple fix, most likely something I have overlooked. I know how to handle this when working with XSL tranformations, by supplying a catalog and the location of the schemas. Thanks in advance for any help, much appreciated.
To use an XML catalog file something like the following in your code should work:
Processor proc = new Processor(false); //false for Saxon-HE
XQueryCompiler compiler = proc.newXQueryCompiler();
XmlCatalogResolver.setCatalog("path/catalog.xml", proc.getUnderlyingConfiguration(), false);
...

i get an error when i run this code

package demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.openxml4j.opc.*;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class DocxToPdf {
public static void main(String[] args){
try
{
String inputFile = "F:\\MY WORK\\CollectionPractice\\WebContent\\APCR1.docx";
String outputFile = "F:\\MY WORK\\CollectionPractice\\WebContent\\APCR1.pdf";
System.out.println("inputFile:" + inputFile + ",outputFile:" + outputFile);
FileInputStream in = new FileInputStream(inputFile);
XWPFDocument document = new XWPFDocument(in);
File outFile = new File(outputFile);
OutputStream out = new FileOutputStream(outFile);
PdfOptions options = null;
PdfConverter.getInstance().convert(document, out, options);
} catch (Exception e) {
e.printStackTrace();
}
}
}
when i run this code an error occur like these and i have used following jar files also.
error:
java.lang.NoSuchMethodError: org.apache.poi.POIXMLDocumentPart.getPackageRelationship()Lorg/apache/poi/openxml4j/opc/PackageRelationship;
jars:
List of jar files
You likely have jar-versions of POI mixed up. The error indicates that the class that was loaded did not have a method that the calling class saw during compilation, so you have a different version of POI in your classpath.
See "Component Map" at https://poi.apache.org/overview.html for the different components that are included and which jars they end up, make sure you only have one of these jars in your classpath, not multiple different versions.

Compilation of Hadoop Java program with additional dependencies

I'm attempting to build a Hadoop program, the purpose of which is to cat files that I've previously uploaded to HDFS, based largely on this tutorial, the program looks like this:
import java.io.*;
import java.net.URI;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
public class ReadHDFS {
public static void main(String[] args) throws IOException {
String uri = args[0];
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
FSDataInputStream in = null ;
try
{
in = fs.open(new Path(uri));
IOUtils.copyBytes(in, System.out, 4096, false);
}
finally
{
IOUtils.closeStream(in);
}
}
}
It seems to me that the tutorial is flawed, because- according to my understanding- IOUtils is part of the apache.commons library. However, although I added the following line to the program I've been trying to deploy:
import org.apache.commons.compress.utils.IOUtils;
I'm still met with the following error:
That is:
FileSystemCat.java:37: error: cannot find symbol
IOUtils.copyBytes(in, System.out, 4096, false);
^
symbol: method copyBytes(InputStream,PrintStream,int,boolean)
location: class IOUtils
FileSystemCat.java:40: error: cannot find symbol
IOUtils.closeStream(in);
^
symbol: variable in
location: class FileSystemCat
2 errors
I'm executing it on the NameNode with this command:
javac -cp /usr/local/hadoop/share/hadoop/common/hadoop-common-2.8.1.jar:/home/ubuntu/job_program/commons-io-2.5/commons-io-2.5.jar FileSystemCat.java
Necessary appendix to ~/.bashrc:
# Classpath for Java
# export HADOOP_CLASSPATH=$($HADOOP_HOME/bin/hadoop classpath)
export HADOOP_CLASSPATH=$($HADOOP_HOME/bin/hadoop classpath)
How to compule the program at the bottom:
javac -cp ${HADOOP_CLASSPATH}:commons-io-2.5.jar ReaderHDFS.java
How to generate the jar file for that program:
jar cf rhdfs.jar ReaderHDFS*.class
Run the command:
$HADOOP_HOME/bin/hadoop jar rhdfs.jar ReaderHDFS hdfs://master:9000/input_1/codes.txt
This is the program:
import org.apache.hadoop.io.IOUtils;
//import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URI;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
public class ReaderHDFS {
public static void main(String[] args) throws IOException {
String uri = args[0];
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
FSDataInputStream in = null ;
try
{
in = fs.open(new Path(uri));
IOUtils.copyBytes(in, System.out, 4096, false);
}
finally
{
IOUtils.closeStream(in);
}
}
}

Java eclipse error - Multiple Markers at this line - URL & SAXException cannot be resolved to a type

I am writing a java code to validate XMLs against XSD file.
Eclipse shows 2 error in following code.
Multiple Markers at this line -
URL cannot be resolved to a type
SAXException cannot be resolved to a type
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
public class xml_validator_class {
public static void main(String argv[]) {
URL schemaFile = new URL("xsdfile.xsd");
Source xmlFile = new StreamSource(new File("xmlfile.xml"));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
try {
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
}
}
}
Kindly refer to this link for below program :
Import the missing classes so that the unqualified types can be used in the program
import java.net.URL;
import org.xml.sax.SAXException;
This error occurs because you have used some classes from some other package and Compiler is not able to resolve those dependencies because of missing imports.
Use Ctrl+Shift+O to Auto import all the required dependencies. Or use manual import as suggested by #Reimeus.
Copy and paste 'URL' class somewhere in your machine with extension of .Java, delete URL class from package, and copy URL Class paste on package folder, Clean the projects. it's worked for me.

Categories

Resources