Merge pull request #33 from CSSAG/closedresourceleaks

close resource leaks and use tryWithResource
This commit is contained in:
Jochen Staerk
2017-06-05 20:46:21 +02:00
committed by GitHub
8 changed files with 258 additions and 236 deletions

1
.gitignore vendored
View File

@@ -5,3 +5,4 @@ PDFA*.pdf
target/ target/
pom.xml.* pom.xml.*
bin/ bin/
/.gradle/

View File

@@ -1,7 +1,12 @@
package org.mustangproject.ZUGFeRD; package org.mustangproject.ZUGFeRD;
public class ZUGFeRDExportException extends RuntimeException { public class ZUGFeRDExportException extends RuntimeException {
public ZUGFeRDExportException() { /**
*
*/
private static final long serialVersionUID = 1L;
public ZUGFeRDExportException() {
} }
public ZUGFeRDExportException(String message) { public ZUGFeRDExportException(String message) {

View File

@@ -28,19 +28,12 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.activation.FileDataSource;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller; import javax.xml.bind.Marshaller;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.PDFAIdentificationSchema;
import org.apache.pdfbox.cos.COSArray; import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary; import org.apache.pdfbox.cos.COSDictionary;
@@ -58,13 +51,57 @@ import org.apache.pdfbox.preflight.ValidationResult;
import org.apache.pdfbox.preflight.exception.ValidationException; import org.apache.pdfbox.preflight.exception.ValidationException;
import org.apache.pdfbox.preflight.parser.PreflightParser; import org.apache.pdfbox.preflight.parser.PreflightParser;
import org.apache.pdfbox.preflight.utils.ByteArrayDataSource; import org.apache.pdfbox.preflight.utils.ByteArrayDataSource;
import org.apache.pdfbox.util.Version;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.PDFAIdentificationSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.type.BadFieldValueException; import org.apache.xmpbox.type.BadFieldValueException;
import org.apache.xmpbox.xml.XmpSerializer; import org.apache.xmpbox.xml.XmpSerializer;
import org.mustangproject.ZUGFeRD.model.*; import org.mustangproject.ZUGFeRD.model.AmountType;
import org.mustangproject.ZUGFeRD.model.CodeType;
import org.mustangproject.ZUGFeRD.model.CountryIDType;
import org.mustangproject.ZUGFeRD.model.CreditorFinancialAccountType;
import org.mustangproject.ZUGFeRD.model.CreditorFinancialInstitutionType;
import org.mustangproject.ZUGFeRD.model.CrossIndustryDocumentType;
import org.mustangproject.ZUGFeRD.model.DateTimeType;
import org.mustangproject.ZUGFeRD.model.DocumentCodeType;
import org.mustangproject.ZUGFeRD.model.DocumentContextParameterType;
import org.mustangproject.ZUGFeRD.model.DocumentLineDocumentType;
import org.mustangproject.ZUGFeRD.model.ExchangedDocumentContextType;
import org.mustangproject.ZUGFeRD.model.ExchangedDocumentType;
import org.mustangproject.ZUGFeRD.model.IDType;
import org.mustangproject.ZUGFeRD.model.IndicatorType;
import org.mustangproject.ZUGFeRD.model.LogisticsServiceChargeType;
import org.mustangproject.ZUGFeRD.model.NoteType;
import org.mustangproject.ZUGFeRD.model.ObjectFactory;
import org.mustangproject.ZUGFeRD.model.PaymentMeansCodeType;
import org.mustangproject.ZUGFeRD.model.PercentType;
import org.mustangproject.ZUGFeRD.model.QuantityType;
import org.mustangproject.ZUGFeRD.model.SupplyChainEventType;
import org.mustangproject.ZUGFeRD.model.SupplyChainTradeAgreementType;
import org.mustangproject.ZUGFeRD.model.SupplyChainTradeDeliveryType;
import org.mustangproject.ZUGFeRD.model.SupplyChainTradeLineItemType;
import org.mustangproject.ZUGFeRD.model.SupplyChainTradeSettlementType;
import org.mustangproject.ZUGFeRD.model.SupplyChainTradeTransactionType;
import org.mustangproject.ZUGFeRD.model.TaxCategoryCodeType;
import org.mustangproject.ZUGFeRD.model.TaxRegistrationType;
import org.mustangproject.ZUGFeRD.model.TaxTypeCodeType;
import org.mustangproject.ZUGFeRD.model.TextType;
import org.mustangproject.ZUGFeRD.model.TradeAddressType;
import org.mustangproject.ZUGFeRD.model.TradeAllowanceChargeType;
import org.mustangproject.ZUGFeRD.model.TradePartyType;
import org.mustangproject.ZUGFeRD.model.TradePaymentTermsType;
import org.mustangproject.ZUGFeRD.model.TradePriceType;
import org.mustangproject.ZUGFeRD.model.TradeProductType;
import org.mustangproject.ZUGFeRD.model.TradeSettlementMonetarySummationType;
import org.mustangproject.ZUGFeRD.model.TradeSettlementPaymentMeansType;
import org.mustangproject.ZUGFeRD.model.TradeTaxType;
public class ZUGFeRDExporter implements Closeable { public class ZUGFeRDExporter implements Closeable {
private void init() { private void init() {
try { try {
jaxbContext = JAXBContext jaxbContext = JAXBContext
@@ -75,7 +112,7 @@ public class ZUGFeRDExporter implements Closeable {
} catch (JAXBException e) { } catch (JAXBException e) {
throw new ZUGFeRDExportException("Could not initialize JAXB", e); throw new ZUGFeRDExportException("Could not initialize JAXB", e);
} }
} }
/** /**
* * You will need Apache PDFBox. To use the ZUGFeRD exporter, implement * * You will need Apache PDFBox. To use the ZUGFeRD exporter, implement
@@ -100,7 +137,7 @@ public class ZUGFeRDExporter implements Closeable {
public ZUGFeRDExporter(PDDocument doc2) { public ZUGFeRDExporter(PDDocument doc2) {
init(); init();
doc=doc2; doc=doc2;
} }
private class LineCalc { private class LineCalc {
@@ -264,12 +301,12 @@ public class ZUGFeRDExporter implements Closeable {
* DecimalFormatSymbols(); symbols.setDecimalSeparator(','); * DecimalFormatSymbols(); symbols.setDecimalSeparator(',');
* symbols.setGroupingSeparator(' '); * symbols.setGroupingSeparator(' ');
* df.setDecimalFormatSymbols(symbols); * df.setDecimalFormatSymbols(symbols);
* *
* but that would not switch off grouping. Although I liked very much * but that would not switch off grouping. Although I liked very much
* the (incomplete) "BNF diagram" in * the (incomplete) "BNF diagram" in
* http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html * http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
* in the end I decided to calculate myself and take eur+sparator+cents * in the end I decided to calculate myself and take eur+sparator+cents
* *
* This function will cut off, i.e. floor() subcent values Tests: * This function will cut off, i.e. floor() subcent values Tests:
* System.err.println(utils.currencyFormat(new BigDecimal(0), * System.err.println(utils.currencyFormat(new BigDecimal(0),
* ".")+"\n"+utils.currencyFormat(new BigDecimal("-1.10"), * ".")+"\n"+utils.currencyFormat(new BigDecimal("-1.10"),
@@ -278,7 +315,7 @@ public class ZUGFeRDExporter implements Closeable {
* ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3489"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3489"),
* ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3419"), * ",")+"\n"+utils.currencyFormat(new BigDecimal("20000123.3419"),
* ",")+"\n"+utils.currencyFormat(new BigDecimal("12"), ",")); * ",")+"\n"+utils.currencyFormat(new BigDecimal("12"), ","));
* *
* results 0.00 -1,10 -1,10 -1,01 20000123,34 20000123,34 12,00 * results 0.00 -1,10 -1,10 -1,01 20000123,34 20000123,34 12,00
*/ */
value = value.setScale(scale, BigDecimal.ROUND_HALF_UP); // first, round value = value.setScale(scale, BigDecimal.ROUND_HALF_UP); // first, round
@@ -384,13 +421,12 @@ public class ZUGFeRDExporter implements Closeable {
* PreflightDocument (that inherits from PDDocument) This document * PreflightDocument (that inherits from PDDocument) This document
* process the end of PDF/A validation. * process the end of PDF/A validation.
*/ */
PreflightDocument document = parser.getPreflightDocument(); try (PreflightDocument document = parser.getPreflightDocument()) {
document.validate(); document.validate();
// Get validation result
result = document.getResult();
document.close();
// Get validation result
result = document.getResult();
}
} catch (ValidationException e) { } catch (ValidationException e) {
/* /*
* the parse method can throw a SyntaxValidationException if the PDF * the parse method can throw a SyntaxValidationException if the PDF
@@ -425,15 +461,25 @@ public class ZUGFeRDExporter implements Closeable {
/** /**
* Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on * Makes A PDF/A3a-compliant document from a PDF-A1 compliant document (on
* the metadata level, this will not e.g. convert graphics to JPG-2000) * the metadata level, this will not e.g. convert graphics to JPG-2000)
* @param filename
* @param producer
* @param creator
* @param attachZugferdHeaders
* @return
* @throws IOException
* @throws TransformerException
* *
*/ */
public PDDocumentCatalog PDFmakeA3compliant(String filename, public PDDocumentCatalog PDFmakeA3compliant(String filename, String producer, String creator, boolean attachZugferdHeaders)
String producer, String creator, boolean attachZugferdHeaders)
throws IOException, TransformerException { throws IOException, TransformerException {
if (!ignoreA1Errors && !isValidA1(new FileInputStream(filename))) { try (FileInputStream fis = new FileInputStream(filename)) {
throw new IOException("File is not a valid PDF/A-1 input file"); boolean validA1 = isValidA1(fis);
if (!ignoreA1Errors && !validA1) {
throw new IOException("File is not a valid PDF/A-1 input file");
}
} }
loadPDFA3(filename); loadPDFA3(filename);
return makeDocPDFA3compliant(producer, creator, attachZugferdHeaders); return makeDocPDFA3compliant(producer, creator, attachZugferdHeaders);
@@ -452,37 +498,39 @@ public class ZUGFeRDExporter implements Closeable {
baos.write(buf, 0, n); baos.write(buf, 0, n);
byte[] content = baos.toByteArray(); byte[] content = baos.toByteArray();
InputStream is1 = new ByteArrayInputStream(content); try (InputStream is1 = new ByteArrayInputStream(content)) {
if (!ignoreA1Errors && !isValidA1(is1)) { if (!ignoreA1Errors && !isValidA1(is1)) {
throw new IOException("File is not a valid PDF/A-1 input file"); throw new IOException("File is not a valid PDF/A-1 input file");
}
} }
InputStream is2 = new ByteArrayInputStream(content); InputStream is2 = new ByteArrayInputStream(content);
loadPDFA3(is2); loadPDFA3(is2);
return makeDocPDFA3compliant(producer, creator, attachZugferdHeaders); return makeDocPDFA3compliant(producer, creator, attachZugferdHeaders);
} }
private PDDocumentCatalog makeDocPDFA3compliant(String producer, private PDDocumentCatalog makeDocPDFA3compliant(String producer,
String creator, boolean attachZugferdHeaders) throws IOException, String creator, boolean attachZugferdHeaders) throws IOException,
TransformerException { TransformerException {
String fullProducer = producer + " (via mustangproject.org " String fullProducer = producer + " (via mustangproject.org "
+ Version.VERSION + ")"; + Version.getVersion() + ")";
PDDocumentCatalog cat = doc.getDocumentCatalog(); PDDocumentCatalog cat = doc.getDocumentCatalog();
PDMetadata metadata = new PDMetadata(doc); PDMetadata metadata = new PDMetadata(doc);
cat.setMetadata(metadata); cat.setMetadata(metadata);
XMPMetadata xmp = XMPMetadata.createXMPMetadata(); XMPMetadata xmp = XMPMetadata.createXMPMetadata();
PDFAIdentificationSchema pdfaid = new PDFAIdentificationSchema(xmp); PDFAIdentificationSchema pdfaid = new PDFAIdentificationSchema(xmp);
xmp.addSchema(pdfaid); xmp.addSchema(pdfaid);
DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema(); DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
dc.addCreator(creator); dc.addCreator(creator);
XMPBasicSchema xsb = xmp.createAndAddXMPBasicSchema(); XMPBasicSchema xsb = xmp.createAndAddXMPBasicSchema();
xsb.setCreatorTool(creator); xsb.setCreatorTool(creator);
xsb.setCreateDate(GregorianCalendar.getInstance()); xsb.setCreateDate(GregorianCalendar.getInstance());
// PDDocumentInformation pdi=doc.getDocumentInformation(); // PDDocumentInformation pdi=doc.getDocumentInformation();
@@ -530,10 +578,11 @@ public class ZUGFeRDExporter implements Closeable {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(xmp, baos, false); serializer.serialize(xmp, baos, false);
metadata.importXMPMetadata( baos.toByteArray() ); metadata.importXMPMetadata( baos.toByteArray() );
return cat; return cat;
} }
@Override
public void close() throws IOException { public void close() throws IOException {
if (doc != null) { if (doc != null) {
doc.close(); doc.close();
@@ -548,10 +597,10 @@ public class ZUGFeRDExporter implements Closeable {
private Totals totals; private Totals totals;
private String createZugferdXMLForTransaction(IZUGFeRDExportableTransaction trans) { private String createZugferdXMLForTransaction(IZUGFeRDExportableTransaction trans1) {
this.trans = trans; this.trans = trans1;
this.totals = new Totals(); this.totals = new Totals();
currency = trans.getCurrency(); currency = trans1.getCurrency();
CrossIndustryDocumentType invoice = xmlFactory CrossIndustryDocumentType invoice = xmlFactory
.createCrossIndustryDocumentType(); .createCrossIndustryDocumentType();
@@ -621,7 +670,7 @@ public class ZUGFeRDExporter implements Closeable {
TextType name = xmlFactory.createTextType(); TextType name = xmlFactory.createTextType();
name.setValue("RECHNUNG"); name.setValue("RECHNUNG");
document.getName().add(name); document.getName().add(name);
if (trans.getOwnOrganisationFullPlaintextInfo() != null) { if (trans.getOwnOrganisationFullPlaintextInfo() != null) {
NoteType regularInfo = xmlFactory.createNoteType(); NoteType regularInfo = xmlFactory.createNoteType();
CodeType regularInfoSubjectCode = xmlFactory.createCodeType(); CodeType regularInfoSubjectCode = xmlFactory.createCodeType();
@@ -633,13 +682,13 @@ public class ZUGFeRDExporter implements Closeable {
regularInfo.getContent().add(regularInfoContent); regularInfo.getContent().add(regularInfoContent);
document.getIncludedNote().add(regularInfo); document.getIncludedNote().add(regularInfo);
} }
if (trans.getReferenceNumber() != null && !new String().equals(trans.getReferenceNumber())){ if (trans.getReferenceNumber() != null && !new String().equals(trans.getReferenceNumber())){
NoteType referenceInfo = xmlFactory.createNoteType(); NoteType referenceInfo = xmlFactory.createNoteType();
TextType referenceInfoContent = xmlFactory.createTextType(); TextType referenceInfoContent = xmlFactory.createTextType();
referenceInfoContent.setValue("Ursprungsbeleg: " + trans.getReferenceNumber()); referenceInfoContent.setValue("Ursprungsbeleg: " + trans.getReferenceNumber());
referenceInfo.getContent().add(referenceInfoContent); referenceInfo.getContent().add(referenceInfoContent);
document.getIncludedNote().add(referenceInfo); document.getIncludedNote().add(referenceInfo);
} }
return document; return document;
@@ -1385,7 +1434,7 @@ public class ZUGFeRDExporter implements Closeable {
* data should hav ebeen set via * data should hav ebeen set via
* <code>setZUGFeRDXMLData(byte[] zugferdData)</code> * <code>setZUGFeRDXMLData(byte[] zugferdData)</code>
*/ */
public void PDFattachZugferdFile(IZUGFeRDExportableTransaction trans) public void PDFattachZugferdFile(IZUGFeRDExportableTransaction trans1)
throws IOException { throws IOException {
if (zugferdData == null) // XML ZUGFeRD data not set externally, needs if (zugferdData == null) // XML ZUGFeRD data not set externally, needs
@@ -1394,7 +1443,7 @@ public class ZUGFeRDExporter implements Closeable {
// create a dummy file stream, this would probably normally be a // create a dummy file stream, this would probably normally be a
// FileInputStream // FileInputStream
byte[] zugferdRaw = createZugferdXMLForTransaction(trans).getBytes(); //$NON-NLS-1$ byte[] zugferdRaw = createZugferdXMLForTransaction(trans1).getBytes(); //$NON-NLS-1$
if ((zugferdRaw[0] == (byte) 0xEF) if ((zugferdRaw[0] == (byte) 0xEF)
&& (zugferdRaw[1] == (byte) 0xBB) && (zugferdRaw[1] == (byte) 0xBB)
@@ -1437,12 +1486,12 @@ public class ZUGFeRDExporter implements Closeable {
* the binary data of the file/attachment * the binary data of the file/attachment
* @throws java.io.IOException * @throws java.io.IOException
*/ */
public void PDFAttachGenericFile(PDDocument doc, String filename, public void PDFAttachGenericFile(PDDocument doc1, String filename,
String relationship, String description, String subType, byte[] data) String relationship, String description, String subType, byte[] data)
throws IOException { throws IOException {
PDComplexFileSpecification fs = new PDComplexFileSpecification(); PDComplexFileSpecification fs = new PDComplexFileSpecification();
fs.setFile(filename); fs.setFile(filename);
COSDictionary dict = fs.getCOSObject(); COSDictionary dict = fs.getCOSObject();
dict.setName("AFRelationship", relationship); dict.setName("AFRelationship", relationship);
@@ -1450,7 +1499,7 @@ public class ZUGFeRDExporter implements Closeable {
dict.setString("Desc", description); dict.setString("Desc", description);
ByteArrayInputStream fakeFile = new ByteArrayInputStream(data); ByteArrayInputStream fakeFile = new ByteArrayInputStream(data);
PDEmbeddedFile ef = new PDEmbeddedFile(doc, fakeFile); PDEmbeddedFile ef = new PDEmbeddedFile(doc1, fakeFile);
ef.setSubtype(subType); ef.setSubtype(subType);
ef.setSize(data.length); ef.setSize(data.length);
ef.setCreationDate(new GregorianCalendar()); ef.setCreationDate(new GregorianCalendar());
@@ -1468,7 +1517,7 @@ public class ZUGFeRDExporter implements Closeable {
// now add the entry to the embedded file tree and set in the document. // now add the entry to the embedded file tree and set in the document.
PDDocumentNameDictionary names = new PDDocumentNameDictionary( PDDocumentNameDictionary names = new PDDocumentNameDictionary(
doc.getDocumentCatalog()); doc1.getDocumentCatalog());
PDEmbeddedFilesNameTreeNode efTree = names.getEmbeddedFiles(); PDEmbeddedFilesNameTreeNode efTree = names.getEmbeddedFiles();
if (efTree == null) { if (efTree == null) {
efTree = new PDEmbeddedFilesNameTreeNode(); efTree = new PDEmbeddedFilesNameTreeNode();
@@ -1486,20 +1535,20 @@ public class ZUGFeRDExporter implements Closeable {
efTree.setNames(namesMap); efTree.setNames(namesMap);
names.setEmbeddedFiles(efTree); names.setEmbeddedFiles(efTree);
doc.getDocumentCatalog().setNames(names); doc1.getDocumentCatalog().setNames(names);
// AF entry (Array) in catalog with the FileSpec // AF entry (Array) in catalog with the FileSpec
COSArray cosArray = (COSArray) doc.getDocumentCatalog() COSArray cosArray = (COSArray) doc1.getDocumentCatalog()
.getCOSObject().getItem("AF"); .getCOSObject().getItem("AF");
if (cosArray == null) { if (cosArray == null) {
cosArray = new COSArray(); cosArray = new COSArray();
} }
cosArray.add(fs); cosArray.add(fs);
COSDictionary dict2 = doc.getDocumentCatalog().getCOSObject(); COSDictionary dict2 = doc1.getDocumentCatalog().getCOSObject();
COSArray array = new COSArray(); COSArray array = new COSArray();
array.add(fs.getCOSObject()); // see below array.add(fs.getCOSObject()); // see below
dict2.setItem("AF",array); dict2.setItem("AF",array);
doc.getDocumentCatalog().getCOSObject().setItem("AF", cosArray); doc1.getDocumentCatalog().getCOSObject().setItem("AF", cosArray);
} }
/** /**
@@ -1532,7 +1581,7 @@ public class ZUGFeRDExporter implements Closeable {
* *
* @param zUGFeRDConformanceLevel * @param zUGFeRDConformanceLevel
* the new conformance level * the new conformance level
* *
* @deprecated Use {@link #setConformanceLevel(PDFAConformanceLevel)} instead * @deprecated Use {@link #setConformanceLevel(PDFAConformanceLevel)} instead
*/ */
@Deprecated @Deprecated
@@ -1555,14 +1604,14 @@ public class ZUGFeRDExporter implements Closeable {
metadata.addSchema(zf); metadata.addSchema(zf);
XMPSchemaPDFAExtensions pdfaex = new XMPSchemaPDFAExtensions(metadata); XMPSchemaPDFAExtensions pdfaex = new XMPSchemaPDFAExtensions(metadata);
metadata.addSchema(pdfaex); metadata.addSchema(pdfaex);
} }
/**** /****
* Returns the PDFBox PDF Document * Returns the PDFBox PDF Document
* *
* @return PDDocument * @return PDDocument
*/ */
public PDDocument getDoc() { public PDDocument getDoc() {

View File

@@ -9,6 +9,7 @@ import org.apache.pdfbox.preflight.PreflightDocument;
import org.apache.pdfbox.preflight.exception.ValidationException; import org.apache.pdfbox.preflight.exception.ValidationException;
import org.apache.pdfbox.preflight.parser.PreflightParser; import org.apache.pdfbox.preflight.parser.PreflightParser;
import org.apache.pdfbox.preflight.utils.ByteArrayDataSource; import org.apache.pdfbox.preflight.utils.ByteArrayDataSource;
import org.apache.pdfbox.util.Version;
import org.apache.xmpbox.XMPMetadata; import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.AdobePDFSchema; import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema; import org.apache.xmpbox.schema.DublinCoreSchema;
@@ -45,9 +46,13 @@ public class ZUGFeRDExporterFromA1Factory {
public ZUGFeRDExporter loadFromPDFA1(String pdfFilename) throws IOException { public ZUGFeRDExporter loadFromPDFA1(String pdfFilename) throws IOException {
ensurePDFIsValidA1(new FileDataSource(pdfFilename)); ensurePDFIsValidA1(new FileDataSource(pdfFilename));
PDDocument doc = PDDocument.load(new File(pdfFilename)); ZUGFeRDExporter zugFeRDExporter = null;
makePDFA3compliant(doc); try(PDDocument doc = PDDocument.load(new File(pdfFilename))) {
return new ZUGFeRDExporter(doc); makePDFA3compliant(doc);
zugFeRDExporter = new ZUGFeRDExporter(doc);
}
return zugFeRDExporter;
} }
/** /**
@@ -56,12 +61,16 @@ public class ZUGFeRDExporterFromA1Factory {
* *
* @param pdfBinary binary of a PDF/A1 compliant document * @param pdfBinary binary of a PDF/A1 compliant document
*/ */
public ZUGFeRDExporter loadFromPDFA1(byte[] pdfBinary) throws IOException, TransformerException { public ZUGFeRDExporter loadFromPDFA1(byte[] pdfBinary) throws IOException {
ensurePDFIsValidA1(new ByteArrayDataSource(new ByteArrayInputStream(pdfBinary))); ensurePDFIsValidA1(new ByteArrayDataSource(new ByteArrayInputStream(pdfBinary)));
PDDocument doc = PDDocument.load(pdfBinary); ZUGFeRDExporter zugFeRDExporter;
makePDFA3compliant(doc); try (PDDocument doc = PDDocument.load(pdfBinary)) {
return new ZUGFeRDExporter(doc); makePDFA3compliant(doc);
zugFeRDExporter = new ZUGFeRDExporter(doc);
}
return zugFeRDExporter;
} }
/** /**
@@ -70,7 +79,7 @@ public class ZUGFeRDExporterFromA1Factory {
* *
* @param pdfSource source to read a PDF/A1 compliant document from * @param pdfSource source to read a PDF/A1 compliant document from
*/ */
public ZUGFeRDExporter loadFromPDFA1(InputStream pdfSource) throws IOException, TransformerException { public ZUGFeRDExporter loadFromPDFA1(InputStream pdfSource) throws IOException {
return loadFromPDFA1(readAllBytes(pdfSource)); return loadFromPDFA1(readAllBytes(pdfSource));
} }
@@ -87,7 +96,7 @@ public class ZUGFeRDExporterFromA1Factory {
} }
private void makePDFA3compliant(PDDocument doc) throws IOException { private void makePDFA3compliant(PDDocument doc) throws IOException {
String fullProducer = producer + " (via mustangproject.org " + Version.VERSION + ")"; String fullProducer = producer + " (via mustangproject.org " + Version.getVersion() + ")";
PDDocumentCatalog cat = doc.getDocumentCatalog(); PDDocumentCatalog cat = doc.getDocumentCatalog();
PDMetadata metadata = new PDMetadata(doc); PDMetadata metadata = new PDMetadata(doc);
@@ -198,23 +207,22 @@ public class ZUGFeRDExporterFromA1Factory {
} }
private static boolean getA1ParserValidationResult(PreflightParser parser) throws IOException { private static boolean getA1ParserValidationResult(PreflightParser parser) throws IOException {
PreflightDocument document = null; /*
try { * Parse the PDF file with PreflightParser that inherits from the
* NonSequentialParser. Some additional controls are present to
* check a set of PDF/A requirements. (Stream length consistency,
* EOL after some Keyword...)
*/
parser.parse();
/*
* Parse the PDF file with PreflightParser that inherits from the
* NonSequentialParser. Some additional controls are present to
* check a set of PDF/A requirements. (Stream length consistency,
* EOL after some Keyword...)
*/
parser.parse();
try ( PreflightDocument document = parser.getPreflightDocument()) {
/* /*
* Once the syntax validation is done, the parser can provide a * Once the syntax validation is done, the parser can provide a
* PreflightDocument (that inherits from PDDocument) This document * PreflightDocument (that inherits from PDDocument) This document
* process the end of PDF/A validation. * process the end of PDF/A validation.
*/ */
document = parser.getPreflightDocument();
document.validate(); document.validate();
// Get validation result // Get validation result
@@ -226,10 +234,6 @@ public class ZUGFeRDExporterFromA1Factory {
* instance of ValidationResult * instance of ValidationResult
*/ */
return false; return false;
} finally {
if (document != null) {
document.close();
}
} }
} }

View File

@@ -8,14 +8,13 @@ package org.mustangproject.ZUGFeRD;
* @author jstaerk * @author jstaerk
* */ * */
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.Map; import java.util.Map;
import javax.management.RuntimeErrorException;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
@@ -23,7 +22,6 @@ import javax.xml.parsers.ParserConfigurationException;
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary; import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode; import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
import org.apache.pdfbox.pdmodel.common.COSObjectable;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification; import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile; import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
import org.w3c.dom.Document; import org.w3c.dom.Document;
@@ -62,13 +60,10 @@ public class ZUGFeRDImporter {
* Extracts a ZUGFeRD invoice from a PDF document represented by a file name. * Extracts a ZUGFeRD invoice from a PDF document represented by a file name.
* Errors are just logged to STDOUT. * Errors are just logged to STDOUT.
*/ */
public void extract(String pdfFilename) public void extract(String pdfFilename) {
{ try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pdfFilename))) {
try extractLowLevel(bis);
{ } catch (IOException ioe) {
extractLowLevel(new BufferedInputStream(new FileInputStream(pdfFilename)));
} catch (IOException ioe)
{
ioe.printStackTrace(); ioe.printStackTrace();
} }
} }
@@ -78,18 +73,15 @@ public class ZUGFeRDImporter {
* Errors are reported via exception handling. * Errors are reported via exception handling.
*/ */
public void extractLowLevel(InputStream pdfStream) throws IOException { public void extractLowLevel(InputStream pdfStream) throws IOException {
PDDocument doc = null; PDEmbeddedFilesNameTreeNode etn;
try { try (PDDocument doc = PDDocument.load(pdfStream)) {
doc = PDDocument.load(pdfStream);
// PDDocumentInformation info = doc.getDocumentInformation(); // PDDocumentInformation info = doc.getDocumentInformation();
PDDocumentNameDictionary names = new PDDocumentNameDictionary( PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
doc.getDocumentCatalog());
PDEmbeddedFilesNameTreeNode etn;
etn = names.getEmbeddedFiles(); etn = names.getEmbeddedFiles();
if (etn==null) { if (etn == null) {
doc.close();
return; return;
} }
Map<String, PDComplexFileSpecification> efMap = etn.getNames(); Map<String, PDComplexFileSpecification> efMap = etn.getNames();
// String filePath = "/tmp/"; // String filePath = "/tmp/";
for (String filename : efMap.keySet()) { for (String filename : efMap.keySet()) {
@@ -100,8 +92,7 @@ public class ZUGFeRDImporter {
if (filename.equals("ZUGFeRD-invoice.xml")) { //$NON-NLS-1$ if (filename.equals("ZUGFeRD-invoice.xml")) { //$NON-NLS-1$
containsMeta = true; containsMeta = true;
PDComplexFileSpecification fileSpec = (PDComplexFileSpecification) efMap PDComplexFileSpecification fileSpec = efMap.get(filename);
.get(filename);
PDEmbeddedFile embeddedFile = fileSpec.getEmbeddedFile(); PDEmbeddedFile embeddedFile = fileSpec.getEmbeddedFile();
// String embeddedFilename = filePath + filename; // String embeddedFilename = filePath + filename;
// File file = new File(filePath + filename); // File file = new File(filePath + filename);
@@ -109,7 +100,7 @@ public class ZUGFeRDImporter {
// ByteArrayOutputStream fileBytes=new // ByteArrayOutputStream fileBytes=new
// ByteArrayOutputStream(); // ByteArrayOutputStream();
// FileOutputStream fos = new FileOutputStream(file); // FileOutputStream fos = new FileOutputStream(file);
rawXML = embeddedFile.toByteArray(); rawXML = embeddedFile.toByteArray();
setMeta(new String(rawXML)); setMeta(new String(rawXML));
extracted=true; extracted=true;
@@ -117,18 +108,7 @@ public class ZUGFeRDImporter {
// fos.close(); // fos.close();
} }
} }
} catch (IOException e1) {
throw e1;
} }
finally {
try {
if(doc!=null) {
doc.close();
}
} catch (IOException e) {}
}
} }
public void parse() { public void parse() {
@@ -421,9 +401,9 @@ public class ZUGFeRDImporter {
public String getMeta() { public String getMeta() {
if (rawXML==null){ if (rawXML==null){
return null; return null;
} else {
return new String(rawXML);
} }
return new String(rawXML);
} }

View File

@@ -1,8 +1,8 @@
// //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 generiert // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// <20>nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // <20>nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2015.10.16 um 06:16:03 PM CEST // Generiert: 2015.10.16 um 06:16:03 PM CEST
// //
@@ -11,23 +11,22 @@ package org.mustangproject.ZUGFeRD.model;
import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry; import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName; import javax.xml.namespace.QName;
/** /**
* This object contains factory methods for each * This object contains factory methods for each
* Java content interface and Java element interface * Java content interface and Java element interface
* generated in the org.mustangproject.ZUGFeRD.model package. * generated in the org.mustangproject.ZUGFeRD.model package.
* <p>An ObjectFactory allows you to programatically * <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation * construct new instances of the Java representation
* for XML content. The Java representation of XML * for XML content. The Java representation of XML
* content can consist of schema derived interfaces * content can consist of schema derived interfaces
* and classes representing the binding of schema * and classes representing the binding of schema
* type definitions, element declarations and model * type definitions, element declarations and model
* groups. Factory methods for each of these are * groups. Factory methods for each of these are
* provided in this class. * provided in this class.
* *
*/ */
@XmlRegistry @XmlRegistry
public class ObjectFactory { public class ObjectFactory {
@@ -36,14 +35,14 @@ public class ObjectFactory {
/** /**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.mustangproject.ZUGFeRD.model * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.mustangproject.ZUGFeRD.model
* *
*/ */
public ObjectFactory() { public ObjectFactory() {
} }
/** /**
* Create an instance of {@link DateTimeType } * Create an instance of {@link DateTimeType }
* *
*/ */
public DateTimeType createDateTimeType() { public DateTimeType createDateTimeType() {
return new DateTimeType(); return new DateTimeType();
@@ -51,7 +50,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link CrossIndustryDocumentType } * Create an instance of {@link CrossIndustryDocumentType }
* *
*/ */
public CrossIndustryDocumentType createCrossIndustryDocumentType() { public CrossIndustryDocumentType createCrossIndustryDocumentType() {
return new CrossIndustryDocumentType(); return new CrossIndustryDocumentType();
@@ -59,7 +58,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link AllowanceChargeReasonCodeType } * Create an instance of {@link AllowanceChargeReasonCodeType }
* *
*/ */
public AllowanceChargeReasonCodeType createAllowanceChargeReasonCodeType() { public AllowanceChargeReasonCodeType createAllowanceChargeReasonCodeType() {
return new AllowanceChargeReasonCodeType(); return new AllowanceChargeReasonCodeType();
@@ -67,7 +66,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link CountryIDType } * Create an instance of {@link CountryIDType }
* *
*/ */
public CountryIDType createCountryIDType() { public CountryIDType createCountryIDType() {
return new CountryIDType(); return new CountryIDType();
@@ -75,7 +74,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link DeliveryTermsCodeType } * Create an instance of {@link DeliveryTermsCodeType }
* *
*/ */
public DeliveryTermsCodeType createDeliveryTermsCodeType() { public DeliveryTermsCodeType createDeliveryTermsCodeType() {
return new DeliveryTermsCodeType(); return new DeliveryTermsCodeType();
@@ -83,7 +82,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link DocumentCodeType } * Create an instance of {@link DocumentCodeType }
* *
*/ */
public DocumentCodeType createDocumentCodeType() { public DocumentCodeType createDocumentCodeType() {
return new DocumentCodeType(); return new DocumentCodeType();
@@ -91,7 +90,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link PaymentMeansCodeType } * Create an instance of {@link PaymentMeansCodeType }
* *
*/ */
public PaymentMeansCodeType createPaymentMeansCodeType() { public PaymentMeansCodeType createPaymentMeansCodeType() {
return new PaymentMeansCodeType(); return new PaymentMeansCodeType();
@@ -99,7 +98,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link ReferenceCodeType } * Create an instance of {@link ReferenceCodeType }
* *
*/ */
public ReferenceCodeType createReferenceCodeType() { public ReferenceCodeType createReferenceCodeType() {
return new ReferenceCodeType(); return new ReferenceCodeType();
@@ -107,7 +106,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TaxCategoryCodeType } * Create an instance of {@link TaxCategoryCodeType }
* *
*/ */
public TaxCategoryCodeType createTaxCategoryCodeType() { public TaxCategoryCodeType createTaxCategoryCodeType() {
return new TaxCategoryCodeType(); return new TaxCategoryCodeType();
@@ -115,7 +114,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TaxTypeCodeType } * Create an instance of {@link TaxTypeCodeType }
* *
*/ */
public TaxTypeCodeType createTaxTypeCodeType() { public TaxTypeCodeType createTaxTypeCodeType() {
return new TaxTypeCodeType(); return new TaxTypeCodeType();
@@ -123,7 +122,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link AmountType } * Create an instance of {@link AmountType }
* *
*/ */
public AmountType createAmountType() { public AmountType createAmountType() {
return new AmountType(); return new AmountType();
@@ -131,7 +130,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link CodeType } * Create an instance of {@link CodeType }
* *
*/ */
public CodeType createCodeType() { public CodeType createCodeType() {
return new CodeType(); return new CodeType();
@@ -139,7 +138,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link IDType } * Create an instance of {@link IDType }
* *
*/ */
public IDType createIDType() { public IDType createIDType() {
return new IDType(); return new IDType();
@@ -147,7 +146,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link IndicatorType } * Create an instance of {@link IndicatorType }
* *
*/ */
public IndicatorType createIndicatorType() { public IndicatorType createIndicatorType() {
return new IndicatorType(); return new IndicatorType();
@@ -155,7 +154,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link MeasureType } * Create an instance of {@link MeasureType }
* *
*/ */
public MeasureType createMeasureType() { public MeasureType createMeasureType() {
return new MeasureType(); return new MeasureType();
@@ -163,7 +162,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link NumericType } * Create an instance of {@link NumericType }
* *
*/ */
public NumericType createNumericType() { public NumericType createNumericType() {
return new NumericType(); return new NumericType();
@@ -171,7 +170,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link PercentType } * Create an instance of {@link PercentType }
* *
*/ */
public PercentType createPercentType() { public PercentType createPercentType() {
return new PercentType(); return new PercentType();
@@ -179,7 +178,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link QuantityType } * Create an instance of {@link QuantityType }
* *
*/ */
public QuantityType createQuantityType() { public QuantityType createQuantityType() {
return new QuantityType(); return new QuantityType();
@@ -187,7 +186,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TextType } * Create an instance of {@link TextType }
* *
*/ */
public TextType createTextType() { public TextType createTextType() {
return new TextType(); return new TextType();
@@ -195,7 +194,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link CreditorFinancialAccountType } * Create an instance of {@link CreditorFinancialAccountType }
* *
*/ */
public CreditorFinancialAccountType createCreditorFinancialAccountType() { public CreditorFinancialAccountType createCreditorFinancialAccountType() {
return new CreditorFinancialAccountType(); return new CreditorFinancialAccountType();
@@ -203,7 +202,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link CreditorFinancialInstitutionType } * Create an instance of {@link CreditorFinancialInstitutionType }
* *
*/ */
public CreditorFinancialInstitutionType createCreditorFinancialInstitutionType() { public CreditorFinancialInstitutionType createCreditorFinancialInstitutionType() {
return new CreditorFinancialInstitutionType(); return new CreditorFinancialInstitutionType();
@@ -211,7 +210,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link DebtorFinancialAccountType } * Create an instance of {@link DebtorFinancialAccountType }
* *
*/ */
public DebtorFinancialAccountType createDebtorFinancialAccountType() { public DebtorFinancialAccountType createDebtorFinancialAccountType() {
return new DebtorFinancialAccountType(); return new DebtorFinancialAccountType();
@@ -219,7 +218,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link DebtorFinancialInstitutionType } * Create an instance of {@link DebtorFinancialInstitutionType }
* *
*/ */
public DebtorFinancialInstitutionType createDebtorFinancialInstitutionType() { public DebtorFinancialInstitutionType createDebtorFinancialInstitutionType() {
return new DebtorFinancialInstitutionType(); return new DebtorFinancialInstitutionType();
@@ -227,7 +226,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link DocumentContextParameterType } * Create an instance of {@link DocumentContextParameterType }
* *
*/ */
public DocumentContextParameterType createDocumentContextParameterType() { public DocumentContextParameterType createDocumentContextParameterType() {
return new DocumentContextParameterType(); return new DocumentContextParameterType();
@@ -235,7 +234,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link DocumentLineDocumentType } * Create an instance of {@link DocumentLineDocumentType }
* *
*/ */
public DocumentLineDocumentType createDocumentLineDocumentType() { public DocumentLineDocumentType createDocumentLineDocumentType() {
return new DocumentLineDocumentType(); return new DocumentLineDocumentType();
@@ -243,7 +242,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link ExchangedDocumentContextType } * Create an instance of {@link ExchangedDocumentContextType }
* *
*/ */
public ExchangedDocumentContextType createExchangedDocumentContextType() { public ExchangedDocumentContextType createExchangedDocumentContextType() {
return new ExchangedDocumentContextType(); return new ExchangedDocumentContextType();
@@ -251,7 +250,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link ExchangedDocumentType } * Create an instance of {@link ExchangedDocumentType }
* *
*/ */
public ExchangedDocumentType createExchangedDocumentType() { public ExchangedDocumentType createExchangedDocumentType() {
return new ExchangedDocumentType(); return new ExchangedDocumentType();
@@ -259,7 +258,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link LogisticsServiceChargeType } * Create an instance of {@link LogisticsServiceChargeType }
* *
*/ */
public LogisticsServiceChargeType createLogisticsServiceChargeType() { public LogisticsServiceChargeType createLogisticsServiceChargeType() {
return new LogisticsServiceChargeType(); return new LogisticsServiceChargeType();
@@ -267,7 +266,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link LogisticsTransportMovementType } * Create an instance of {@link LogisticsTransportMovementType }
* *
*/ */
public LogisticsTransportMovementType createLogisticsTransportMovementType() { public LogisticsTransportMovementType createLogisticsTransportMovementType() {
return new LogisticsTransportMovementType(); return new LogisticsTransportMovementType();
@@ -275,7 +274,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link NoteType } * Create an instance of {@link NoteType }
* *
*/ */
public NoteType createNoteType() { public NoteType createNoteType() {
return new NoteType(); return new NoteType();
@@ -283,7 +282,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link ProductCharacteristicType } * Create an instance of {@link ProductCharacteristicType }
* *
*/ */
public ProductCharacteristicType createProductCharacteristicType() { public ProductCharacteristicType createProductCharacteristicType() {
return new ProductCharacteristicType(); return new ProductCharacteristicType();
@@ -291,7 +290,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link ProductClassificationType } * Create an instance of {@link ProductClassificationType }
* *
*/ */
public ProductClassificationType createProductClassificationType() { public ProductClassificationType createProductClassificationType() {
return new ProductClassificationType(); return new ProductClassificationType();
@@ -299,7 +298,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link ReferencedDocumentType } * Create an instance of {@link ReferencedDocumentType }
* *
*/ */
public ReferencedDocumentType createReferencedDocumentType() { public ReferencedDocumentType createReferencedDocumentType() {
return new ReferencedDocumentType(); return new ReferencedDocumentType();
@@ -307,7 +306,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link ReferencedProductType } * Create an instance of {@link ReferencedProductType }
* *
*/ */
public ReferencedProductType createReferencedProductType() { public ReferencedProductType createReferencedProductType() {
return new ReferencedProductType(); return new ReferencedProductType();
@@ -315,7 +314,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link SpecifiedPeriodType } * Create an instance of {@link SpecifiedPeriodType }
* *
*/ */
public SpecifiedPeriodType createSpecifiedPeriodType() { public SpecifiedPeriodType createSpecifiedPeriodType() {
return new SpecifiedPeriodType(); return new SpecifiedPeriodType();
@@ -323,7 +322,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link SupplyChainConsignmentType } * Create an instance of {@link SupplyChainConsignmentType }
* *
*/ */
public SupplyChainConsignmentType createSupplyChainConsignmentType() { public SupplyChainConsignmentType createSupplyChainConsignmentType() {
return new SupplyChainConsignmentType(); return new SupplyChainConsignmentType();
@@ -331,7 +330,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link SupplyChainEventType } * Create an instance of {@link SupplyChainEventType }
* *
*/ */
public SupplyChainEventType createSupplyChainEventType() { public SupplyChainEventType createSupplyChainEventType() {
return new SupplyChainEventType(); return new SupplyChainEventType();
@@ -339,7 +338,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link SupplyChainTradeAgreementType } * Create an instance of {@link SupplyChainTradeAgreementType }
* *
*/ */
public SupplyChainTradeAgreementType createSupplyChainTradeAgreementType() { public SupplyChainTradeAgreementType createSupplyChainTradeAgreementType() {
return new SupplyChainTradeAgreementType(); return new SupplyChainTradeAgreementType();
@@ -347,7 +346,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link SupplyChainTradeDeliveryType } * Create an instance of {@link SupplyChainTradeDeliveryType }
* *
*/ */
public SupplyChainTradeDeliveryType createSupplyChainTradeDeliveryType() { public SupplyChainTradeDeliveryType createSupplyChainTradeDeliveryType() {
return new SupplyChainTradeDeliveryType(); return new SupplyChainTradeDeliveryType();
@@ -355,7 +354,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link SupplyChainTradeLineItemType } * Create an instance of {@link SupplyChainTradeLineItemType }
* *
*/ */
public SupplyChainTradeLineItemType createSupplyChainTradeLineItemType() { public SupplyChainTradeLineItemType createSupplyChainTradeLineItemType() {
return new SupplyChainTradeLineItemType(); return new SupplyChainTradeLineItemType();
@@ -363,7 +362,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link SupplyChainTradeSettlementType } * Create an instance of {@link SupplyChainTradeSettlementType }
* *
*/ */
public SupplyChainTradeSettlementType createSupplyChainTradeSettlementType() { public SupplyChainTradeSettlementType createSupplyChainTradeSettlementType() {
return new SupplyChainTradeSettlementType(); return new SupplyChainTradeSettlementType();
@@ -371,7 +370,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link SupplyChainTradeTransactionType } * Create an instance of {@link SupplyChainTradeTransactionType }
* *
*/ */
public SupplyChainTradeTransactionType createSupplyChainTradeTransactionType() { public SupplyChainTradeTransactionType createSupplyChainTradeTransactionType() {
return new SupplyChainTradeTransactionType(); return new SupplyChainTradeTransactionType();
@@ -379,7 +378,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TaxRegistrationType } * Create an instance of {@link TaxRegistrationType }
* *
*/ */
public TaxRegistrationType createTaxRegistrationType() { public TaxRegistrationType createTaxRegistrationType() {
return new TaxRegistrationType(); return new TaxRegistrationType();
@@ -387,7 +386,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeAccountingAccountType } * Create an instance of {@link TradeAccountingAccountType }
* *
*/ */
public TradeAccountingAccountType createTradeAccountingAccountType() { public TradeAccountingAccountType createTradeAccountingAccountType() {
return new TradeAccountingAccountType(); return new TradeAccountingAccountType();
@@ -395,7 +394,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeAddressType } * Create an instance of {@link TradeAddressType }
* *
*/ */
public TradeAddressType createTradeAddressType() { public TradeAddressType createTradeAddressType() {
return new TradeAddressType(); return new TradeAddressType();
@@ -403,7 +402,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeAllowanceChargeType } * Create an instance of {@link TradeAllowanceChargeType }
* *
*/ */
public TradeAllowanceChargeType createTradeAllowanceChargeType() { public TradeAllowanceChargeType createTradeAllowanceChargeType() {
return new TradeAllowanceChargeType(); return new TradeAllowanceChargeType();
@@ -411,7 +410,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeContactType } * Create an instance of {@link TradeContactType }
* *
*/ */
public TradeContactType createTradeContactType() { public TradeContactType createTradeContactType() {
return new TradeContactType(); return new TradeContactType();
@@ -419,7 +418,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeCountryType } * Create an instance of {@link TradeCountryType }
* *
*/ */
public TradeCountryType createTradeCountryType() { public TradeCountryType createTradeCountryType() {
return new TradeCountryType(); return new TradeCountryType();
@@ -427,7 +426,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeDeliveryTermsType } * Create an instance of {@link TradeDeliveryTermsType }
* *
*/ */
public TradeDeliveryTermsType createTradeDeliveryTermsType() { public TradeDeliveryTermsType createTradeDeliveryTermsType() {
return new TradeDeliveryTermsType(); return new TradeDeliveryTermsType();
@@ -435,7 +434,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradePartyType } * Create an instance of {@link TradePartyType }
* *
*/ */
public TradePartyType createTradePartyType() { public TradePartyType createTradePartyType() {
return new TradePartyType(); return new TradePartyType();
@@ -443,7 +442,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradePaymentDiscountTermsType } * Create an instance of {@link TradePaymentDiscountTermsType }
* *
*/ */
public TradePaymentDiscountTermsType createTradePaymentDiscountTermsType() { public TradePaymentDiscountTermsType createTradePaymentDiscountTermsType() {
return new TradePaymentDiscountTermsType(); return new TradePaymentDiscountTermsType();
@@ -451,7 +450,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradePaymentPenaltyTermsType } * Create an instance of {@link TradePaymentPenaltyTermsType }
* *
*/ */
public TradePaymentPenaltyTermsType createTradePaymentPenaltyTermsType() { public TradePaymentPenaltyTermsType createTradePaymentPenaltyTermsType() {
return new TradePaymentPenaltyTermsType(); return new TradePaymentPenaltyTermsType();
@@ -459,7 +458,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradePaymentTermsType } * Create an instance of {@link TradePaymentTermsType }
* *
*/ */
public TradePaymentTermsType createTradePaymentTermsType() { public TradePaymentTermsType createTradePaymentTermsType() {
return new TradePaymentTermsType(); return new TradePaymentTermsType();
@@ -467,7 +466,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradePriceType } * Create an instance of {@link TradePriceType }
* *
*/ */
public TradePriceType createTradePriceType() { public TradePriceType createTradePriceType() {
return new TradePriceType(); return new TradePriceType();
@@ -475,7 +474,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeProductType } * Create an instance of {@link TradeProductType }
* *
*/ */
public TradeProductType createTradeProductType() { public TradeProductType createTradeProductType() {
return new TradeProductType(); return new TradeProductType();
@@ -483,7 +482,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeSettlementMonetarySummationType } * Create an instance of {@link TradeSettlementMonetarySummationType }
* *
*/ */
public TradeSettlementMonetarySummationType createTradeSettlementMonetarySummationType() { public TradeSettlementMonetarySummationType createTradeSettlementMonetarySummationType() {
return new TradeSettlementMonetarySummationType(); return new TradeSettlementMonetarySummationType();
@@ -491,7 +490,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeSettlementPaymentMeansType } * Create an instance of {@link TradeSettlementPaymentMeansType }
* *
*/ */
public TradeSettlementPaymentMeansType createTradeSettlementPaymentMeansType() { public TradeSettlementPaymentMeansType createTradeSettlementPaymentMeansType() {
return new TradeSettlementPaymentMeansType(); return new TradeSettlementPaymentMeansType();
@@ -499,7 +498,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link TradeTaxType } * Create an instance of {@link TradeTaxType }
* *
*/ */
public TradeTaxType createTradeTaxType() { public TradeTaxType createTradeTaxType() {
return new TradeTaxType(); return new TradeTaxType();
@@ -507,7 +506,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link UniversalCommunicationType } * Create an instance of {@link UniversalCommunicationType }
* *
*/ */
public UniversalCommunicationType createUniversalCommunicationType() { public UniversalCommunicationType createUniversalCommunicationType() {
return new UniversalCommunicationType(); return new UniversalCommunicationType();
@@ -515,7 +514,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link DateTimeType.DateTimeString } * Create an instance of {@link DateTimeType.DateTimeString }
* *
*/ */
public DateTimeType.DateTimeString createDateTimeTypeDateTimeString() { public DateTimeType.DateTimeString createDateTimeTypeDateTimeString() {
return new DateTimeType.DateTimeString(); return new DateTimeType.DateTimeString();
@@ -523,7 +522,7 @@ public class ObjectFactory {
/** /**
* Create an instance of {@link JAXBElement }{@code <}{@link CrossIndustryDocumentType }{@code >}} * Create an instance of {@link JAXBElement }{@code <}{@link CrossIndustryDocumentType }{@code >}}
* *
*/ */
@XmlElementDecl(namespace = "urn:ferd:CrossIndustryDocument:invoice:1p0", name = "CrossIndustryDocument") @XmlElementDecl(namespace = "urn:ferd:CrossIndustryDocument:invoice:1p0", name = "CrossIndustryDocument")
public JAXBElement<CrossIndustryDocumentType> createCrossIndustryDocument(CrossIndustryDocumentType value) { public JAXBElement<CrossIndustryDocumentType> createCrossIndustryDocument(CrossIndustryDocumentType value) {

View File

@@ -401,27 +401,18 @@ public class MustangReaderWriterEdgeTest extends TestCase implements IZUGFeRDExp
public void testZExport() public void testZExport()
{ {
final InputStream SOURCE_PDF = this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505blanko.pdf"); final String TARGET_PDF = "./target/testout-MustangGnuaccountingBeispielRE-20170509_505newEdge.pdf";
final String TARGET_PDF = "./target/testout-MustangGnuaccountingBeispielRE-20170509_505newEdge.pdf";
// the writing part
try // the writing part
{ // automatically add Zugferd to all outgoing invoices
// automatically add Zugferd to all outgoing invoices try (ZUGFeRDExporter ze = new ZUGFeRDExporter()) {
ZUGFeRDExporter ze = new ZUGFeRDExporter(); try(final InputStream SOURCE_PDF = this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505blanko.pdf")){
ze.PDFmakeA3compliant(SOURCE_PDF, "My Application", System.getProperty("user.name"), true); ze.PDFmakeA3compliant(SOURCE_PDF, "My Application", System.getProperty("user.name"), true);
ze.PDFattachZugferdFile(this); }
ze.export(TARGET_PDF); ze.PDFattachZugferdFile(this);
ze.export(TARGET_PDF);
} }
catch (IOException e) catch (Exception e)
{
e.printStackTrace();
}
catch (TransformerException e)
{
e.printStackTrace();
}
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }

View File

@@ -10,14 +10,13 @@ import java.util.GregorianCalendar;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestCase; import junit.framework.TestCase;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING) @FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MustangReaderWriterTest extends TestCase implements IZUGFeRDExportableTransaction public class MustangReaderWriterTest extends TestCase implements IZUGFeRDExportableTransaction
{ {
@@ -326,7 +325,7 @@ public class MustangReaderWriterTest extends TestCase implements IZUGFeRDExporta
public void setVATPercent(BigDecimal VATPercent) public void setVATPercent(BigDecimal VATPercent)
{ {
VATPercent = VATPercent; this.VATPercent = VATPercent;
} }
} }
@@ -363,8 +362,10 @@ public class MustangReaderWriterTest extends TestCase implements IZUGFeRDExporta
public void testAImport() throws IOException public void testAImport() throws IOException
{ {
ZUGFeRDImporter zi = new ZUGFeRDImporter(); ZUGFeRDImporter zi = new ZUGFeRDImporter();
InputStream inputStream = this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505.pdf"); try (InputStream inputStream = this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505.pdf")) {
zi.extractLowLevel(inputStream); zi.extractLowLevel(inputStream);
}
// Reading ZUGFeRD // Reading ZUGFeRD
String amount = null; String amount = null;
@@ -400,27 +401,19 @@ public class MustangReaderWriterTest extends TestCase implements IZUGFeRDExporta
*/ */
public void testZExport() public void testZExport()
{ {
final InputStream SOURCE_PDF = this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505blanko.pdf");
final String TARGET_PDF = "./target/testout-MustangGnuaccountingBeispielRE-20170509_505new.pdf"; final String TARGET_PDF = "./target/testout-MustangGnuaccountingBeispielRE-20170509_505new.pdf";
// the writing part // the writing part
try // automatically add Zugferd to all outgoing invoices
{ try (ZUGFeRDExporter ze = new ZUGFeRDExporter()) {
// automatically add Zugferd to all outgoing invoices try (final InputStream SOURCE_PDF = this.getClass().getResourceAsStream("/MustangGnuaccountingBeispielRE-20170509_505blanko.pdf")) {
ZUGFeRDExporter ze = new ZUGFeRDExporter(); ze.PDFmakeA3compliant(SOURCE_PDF, "My Application", System.getProperty("user.name"), true);
ze.PDFmakeA3compliant(SOURCE_PDF, "My Application", System.getProperty("user.name"), true); }
ze.PDFattachZugferdFile(this); ze.PDFattachZugferdFile(this);
ze.export(TARGET_PDF); ze.export(TARGET_PDF);
} }
catch (IOException e) catch (Exception e)
{
e.printStackTrace();
}
catch (TransformerException e)
{
e.printStackTrace();
}
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }