1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package cz.hobrasoft.pdfmu.operation.args;
18
19 import com.itextpdf.text.pdf.PdfReader;
20 import cz.hobrasoft.pdfmu.PdfmuUtils;
21 import static cz.hobrasoft.pdfmu.error.ErrorType.INPUT_CLOSE;
22 import static cz.hobrasoft.pdfmu.error.ErrorType.INPUT_NOT_FOUND;
23 import static cz.hobrasoft.pdfmu.error.ErrorType.INPUT_NOT_VALID_PDF;
24 import cz.hobrasoft.pdfmu.operation.OperationException;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.FileNotFoundException;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.util.logging.Logger;
31 import net.sourceforge.argparse4j.impl.Arguments;
32 import net.sourceforge.argparse4j.inf.ArgumentParser;
33 import net.sourceforge.argparse4j.inf.Namespace;
34
35 public class InPdfArgs implements ArgsConfiguration, AutoCloseable {
36
37 private final String name = "in";
38 private final String help = "input PDF document";
39 private final String metavar;
40
41 private static final Logger logger = Logger.getLogger(InPdfArgs.class.getName());
42
43 public InPdfArgs(String metavar) {
44 this.metavar = metavar;
45 }
46
47 public InPdfArgs() {
48 this("IN.pdf");
49 }
50
51 @Override
52 public void addArguments(ArgumentParser parser) {
53 parser.addArgument(name)
54 .help(help)
55 .metavar(metavar)
56 .type(Arguments.fileType().acceptSystemIn());
57 }
58
59 private File file = null;
60
61 public File getFile() {
62 return file;
63 }
64
65 private InputStream is = null;
66 private PdfReader pdfReader = null;
67
68 @Override
69 public void setFromNamespace(Namespace namespace) {
70 file = namespace.get(name);
71 assert file != null;
72 }
73
74 public PdfReader open() throws OperationException {
75 assert file != null;
76 assert is == null;
77 assert pdfReader == null;
78
79 logger.info(String.format("Input file: %s", file));
80
81
82 try {
83 is = new FileInputStream(file);
84 } catch (FileNotFoundException ex) {
85 throw new OperationException(INPUT_NOT_FOUND, ex,
86 PdfmuUtils.sortedMap(new String[]{"file"}, new Object[]{file}));
87 }
88
89
90 try {
91 pdfReader = new PdfReader(is);
92 } catch (IOException ex) {
93 throw new OperationException(INPUT_NOT_VALID_PDF, ex,
94 PdfmuUtils.sortedMap(new String[]{"file"}, new Object[]{file}));
95 }
96
97 return pdfReader;
98 }
99
100 @Override
101 public void close() throws OperationException {
102 if (pdfReader != null) {
103
104 pdfReader.close();
105 pdfReader = null;
106 }
107
108 if (is != null) {
109
110 try {
111 is.close();
112 } catch (IOException ex) {
113 throw new OperationException(INPUT_CLOSE, ex);
114 }
115 is = null;
116 }
117 }
118
119 public PdfReader getPdfReader() {
120 return pdfReader;
121 }
122
123 }