1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
| package net.sf.jsignpdf;
import static net.sf.jsignpdf.Constants.*;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import net.sf.jsignpdf.ssl.SSLInitializer;
import net.sf.jsignpdf.utils.ConfigProvider;
import net.sf.jsignpdf.utils.GuiUtils;
import net.sf.jsignpdf.utils.KeyStoreUtils;
import net.sf.jsignpdf.utils.PKCS11Utils;
import net.sf.jsignpdf.utils.PropertyProvider;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
//******************
import static net.sf.jsignpdf.Constants.RES;
import java.awt.Toolkit;
import java.io.File;
import java.net.URL;
import java.security.KeyStore;
import java.util.Set;
import javax.net.ssl.SSLHandshakeException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import net.sf.jsignpdf.types.CertificationLevel;
import net.sf.jsignpdf.types.HashAlgorithm;
import net.sf.jsignpdf.types.PDFEncryption;
import net.sf.jsignpdf.types.PrintRight;
import net.sf.jsignpdf.utils.GuiUtils;
import net.sf.jsignpdf.utils.KeyStoreUtils;
import net.sf.jsignpdf.utils.PropertyProvider;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
/**
* JSignPdf main class - it either process command line or if no argument is
* given, sets system Look&Feel and creates SignPdfForm GUI.
*
* @author Josef Cacek
*/
public class Signer {
public final static Logger LOGGER = Logger.getLogger(Signer.class);
BasicSignerOptions options = new BasicSignerOptions();
public SignerLogic signerLogic = new SignerLogic(options);
static int auto;
static Path FileOut;
static Path FileIn;
/**
* Prints formatted help message (command line arguments).
*/
private static void printHelp() {
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(
80,
"java -jar JSignPdf.jar [file1.pdf [file2.pdf ...]]",
RES.get("hlp.header"),
SignerOptionsFromCmdLine.OPTS,
NEW_LINE + RES.get("hlp.footer.exitCodes") + NEW_LINE + StringUtils.repeat("-", 80) + NEW_LINE
+ RES.get("hlp.footer.examples"), true);
}
/**
* Main.
*
* @param args
* @throws IOException
* @throws KeyStoreException
* @throws CertificateException
* @throws NoSuchAlgorithmException
*/
public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
try {
SSLInitializer.init();
} catch (Exception e) {
LOGGER.warn("Unable to re-configure SSL layer", e);
}
final String pkcs11ProviderName = PKCS11Utils.registerProvider(ConfigProvider.getInstance().getProperty(
"pkcs11config.path"));
traceInfo();
if (args != null && args.length > 0) {
final SignerOptionsFromCmdLine tmpOpts = new SignerOptionsFromCmdLine();
parseCommandLine(args, tmpOpts);
if (tmpOpts.isPrintVersion()) {
System.out.println("JSignPdf version " + VERSION);
}
if (tmpOpts.isPrintHelp()) {
printHelp();
}
if (tmpOpts.isListKeyStores()) {
LOGGER.info(RES.get("console.keystores"));
for (String tmpKsType : KeyStoreUtils.getKeyStores()) {
System.out.println(tmpKsType);
}
}
if (tmpOpts.isListKeys()) {
final String[] tmpKeyAliases = KeyStoreUtils.getKeyAliases(tmpOpts);
LOGGER.info(RES.get("console.keys"));
// list certificate aliases in the keystore
for (String tmpCert : tmpKeyAliases) {
System.out.println(tmpCert);
}
}
if (ArrayUtils.isNotEmpty(tmpOpts.getFiles())
|| (!StringUtils.isEmpty(tmpOpts.getInFile()) && !StringUtils.isEmpty(tmpOpts.getOutFile()))) {
signFiles(tmpOpts);
} else {
final boolean tmpCommand = tmpOpts.isPrintVersion() || tmpOpts.isPrintHelp()
|| tmpOpts.isListKeyStores() || tmpOpts.isListKeys();
if (!tmpCommand) {
// no valid command provided - print help and exit
printHelp();
System.exit(EXIT_CODE_NO_COMMAND);
}
}
} else {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println("Can't set Look&Feel.");
}
SignPdfForm tmpForm = new SignPdfForm(WindowConstants.EXIT_ON_CLOSE);
tmpForm.pack();
GuiUtils.center(tmpForm);
tmpForm.setVisible(true);
}
// some tokens/card-readers hangs during second usage of the program, they have to be unplugged and plugged again
// following code should prevent this issue
if (pkcs11ProviderName != null) {
Security.removeProvider(pkcs11ProviderName);
//we should wait a little bit to de-register provider correctly (is it a driver issue?)
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Path chemin = Paths.get("C:/Users/avidegrain/Desktop/repertoire_1/test.pdf");
Path cheminout = Paths.get("C:/Users/avidegrain/Desktop/repertoire_2/test.pdf");
final Path dir = chemin.getParent();// on prend le répertoire du fichier infile
Path dirout = cheminout.getParent();
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchKey key = dir.register(watcher,
StandardWatchEventKinds.ENTRY_CREATE);
for (;;) {
// wait for key to be signaled
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
String type = Files.probeContentType(filename);
try {
Path child = dir.resolve(filename);
if (!Files.probeContentType(child).equals("application/pdf")) {
//probeContentType récupère l'extension //Equals compare deux string
System.err.format("New file '%s'" +
" is not a pdf application file.%n", filename);
continue;
}
} catch (IOException x) {
System.err.println(x);
continue;
}
//Affiche les chemins des fichiers pour vérification
System.out.println("Le fichier est : " + dir+ "\\" + filename );
Path FileOut = Paths.get(dirout+ "\\" + filename);
System.out.println("Le fichier Out est : " + FileOut);
Path FileIn = Paths.get(dir+ "\\" + filename);
System.out.println("Le fichier In est : " + FileIn);
BasicSignerOptions options = new BasicSignerOptions();
options.setInFile(FileIn.toString());
options.setOutFile(FileOut.toString());
int auto;
auto=1;
SignPdfForm spf = new SignPdfForm(0);
spf.btnSignItActionPerformed(null);
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (IOException x) {
System.err.println(x);
}
}
/**
* Writes info about security providers to the {@link Logger} instance. The
* log-level for messages is TRACE.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private static void traceInfo() {
if (LOGGER.isTraceEnabled()) {
try {
Provider[] aProvider = Security.getProviders();
for (int i = 0; i < aProvider.length; i++) {
Provider provider = aProvider[i];
LOGGER.trace("Provider " + (i + 1) + " : " + provider.getName() + " " + provider.getInfo() + " :");
List keyList = new ArrayList(provider.keySet());
try {
Collections.sort(keyList);
} catch (Exception e) {
LOGGER.trace("Provider's properties keys can't be sorted", e);
}
Iterator keyIterator = keyList.iterator();
while (keyIterator.hasNext()) {
String key = (String) keyIterator.next();
LOGGER.trace(key + ": " + provider.getProperty(key));
}
LOGGER.trace("------------------------------------------------");
}
} catch (Exception e) {
LOGGER.trace("Listing security providers failed", e);
}
}
}
/**
* Sign the files
*
* @param anOpts
*/
private static void signFiles(SignerOptionsFromCmdLine anOpts) {
final SignerLogic tmpLogic = new SignerLogic(anOpts);
if (ArrayUtils.isEmpty(anOpts.getFiles())) {
// we've used -lp (loadproperties) parameter
if (!tmpLogic.signFile()) {
System.exit(Constants.EXIT_CODE_ALL_SIG_FAILED);
}
return;
}
int successCount = 0;
int failedCount = 0;
for (final String wildcardPath : anOpts.getFiles()) {
final File wildcardFile = new File(wildcardPath);
File[] inputFiles;
if (StringUtils.containsAny(wildcardFile.getName(), '*', '?')) {
final File inputFolder = wildcardFile.getAbsoluteFile().getParentFile();
final FileFilter fileFilter = new AndFileFilter(FileFileFilter.FILE, new WildcardFileFilter(
wildcardFile.getName()));
inputFiles = inputFolder.listFiles(fileFilter);
if (inputFiles == null) {
continue;
}
} else {
inputFiles = new File[] { wildcardFile };
}
for (File inputFile : inputFiles) {
final String tmpInFile = inputFile.getPath();
if (!inputFile.canRead()) {
failedCount++;
System.err.println(RES.get("file.notReadable", new String[] { tmpInFile }));
continue;
}
anOpts.setInFile(tmpInFile);
String tmpNameBase = inputFile.getName();//variable nom d'entrée // saisie nom d'entrée
System.out.println("tmpNameBase est égal à :" + tmpNameBase );
String tmpSuffix = ".pdf";
if (StringUtils.endsWithIgnoreCase(tmpNameBase, tmpSuffix)) {
tmpSuffix = StringUtils.right(tmpNameBase, 4);
tmpNameBase = StringUtils.left(tmpNameBase, tmpNameBase.length() - 4);
}
final StringBuilder tmpName = new StringBuilder(anOpts.getOutPath());
tmpName.append(anOpts.getOutPrefix());
tmpName.append(tmpNameBase).append(anOpts.getOutSuffix()).append(tmpSuffix);
anOpts.setOutFile(tmpName.toString());
if (tmpLogic.signFile()) {
successCount++;
} else {
failedCount++;
}
}
}
if (failedCount > 0) {
System.exit(successCount > 0 ? Constants.EXIT_CODE_SOME_SIG_FAILED : Constants.EXIT_CODE_ALL_SIG_FAILED);
}
}
/**
* Parses the command line. Exits with error exit code when parsing fails.
*
* @param args
* @param opts
*/
private static void parseCommandLine(String[] args, final SignerOptionsFromCmdLine opts) {
try {
opts.loadCmdLine(args);
} catch (ParseException exp) {
System.err.println("Unable to parse command line (Use -h for the help)\n" + exp.getMessage());
System.exit(EXIT_CODE_PARSE_ERR);
}
}
} |
Partager