IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

avec Java Discussion :

Débutant - API Path


Sujet :

avec Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut Débutant - API Path
    Bonjour,

    Je voudrais faire des test pour prendre en main cette api path avec du code tout simple, mais j'ai des erreurs ..

    Voici le code, j'ai que celui là sur eclipse dans un fichier test :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    package test;
    import java.nio;
     
     
    public class testpath {
    	Path chemin = Paths.get("C:/Users/avide/Desktop/facture_test.pdf");  
    	System.out.println("toString()     = " + chemin.toString());
    	System.out.println("getFileName()  = " + chemin.getFileName());
    	System.out.println("getRoot()      = " + chemin.getRoot());
    	System.out.println("getName(0)     = " + chemin.getName(0));
    	System.out.println("getNameCount() = " + chemin.getNameCount());
    	System.out.println("getParent()    = " + chemin.getParent());
    	System.out.println("subpath(0,3)   = " + chemin.subpath(0,3));
    }
    Pour la ligne ou je fait import il me dit :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Only a type can be imported. java.nio resolves to a package
    A la ligne path chemin = paths.get(...) j'ai :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Multiple markers at this line
    	- Paths cannot be resolved
    	- Path cannot be resolved to a type
    Et a chaque ligne ou j'ai printIn j'ai ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Multiple markers at this line
    	- Syntax error on token "println", = expected after this token
    	- Syntax error on token(s), misplaced construct(s)
    Je voudrais simplement qu'il m'affiche ceci dans la console une fois exécuté :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    toString()     = C:/Users/avide/Desktop/facture_test.pdf
    getFileName()  = facture_test.pdf
    getRoot()      = C:\
    getName(0)     = Users
    getNameCount() = 4
    getParent()    = C:/Users/avide/Desktop/
    subpath(0,3)   = Users/avide/Desktop/

  2. #2
    Membre Expert

    Homme Profil pro
    Consultant informatique
    Inscrit en
    Janvier 2004
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Janvier 2004
    Messages : 2 301
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    import java.nio.*;
    import java.nio.file.*;

  3. #3
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    J'ai réussi à trouver pour les import merci, mais les erreurs suivantes sont toujours présentes, et quand je veut run il me dit qu'il faut un main()
    Pas évident de débuter Java et d'avoir directement à modifier une application

    Le but de mon programme de test étant d'arriver à :
    -Surveiller un répertoire en continue
    -M'informer quand un nouveau fichier arrive dans ce répertoire et me renvoyer son chemin et son nom

    Puis ensuite, une fois que j'aurais fait ça il va falloir que je le "greffe" au code d'un logiciel open source java de signature numérique :
    -Un nouveau fichier arrive dans un répertoire qui a été définit au lancement de l'application
    -L'application détecte le nouveau fichier, en retire son nom + son chemin
    -L'application signe numériquement le document (il y en a donc deux à ce moment) et envoie le document signé dans un répertoire définit au lancement de l'appli
    -L'application surveille si le document signé est arrivé à destination, et s'il y est arrivé supprime le document non signé du 1er répertoire => Si j'ai le temps

    EDIT :
    J'ai trouvé pour le main(), ça me fait ce code là :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    package test;
    import java.nio.*;
    import java.nio.file.*;
     
    public class testpath {
     
    	public static void main(String[] args)
    	{
    		// TODO Auto-generated method stub
     
    		Path chemin = Paths.get("C:/Users/avide/Desktop/facture_test.pdf");
     
    		System.out.println("toString()     = " + chemin.toString());
    		System.out.println("getFileName()  = " + chemin.getFileName());
    		System.out.println("getRoot()      = " + chemin.getRoot());
    		System.out.println("getName(0)     = " + chemin.getName(0));
    		System.out.println("getNameCount() = " + chemin.getNameCount());
    		System.out.println("getParent()    = " + chemin.getParent());
    		System.out.println("subpath(0,3)   = " + chemin.subpath(0,3));
    	}
     
    }

  4. #4
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Ce que j'ai fait jusqu'ici fonctionne mais la suite non :p
    J'ai ajouter ça comme code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    try {
     
    			final Path dir = chemin.getParent();
    			WatchService watcher = FileSystems.getDefault().newWatchService();
     
    			WatchKey key = dir.register(watcher,
    		    		StandardWatchEventKinds.ENTRY_CREATE,
    		    		StandardWatchEventKinds.ENTRY_DELETE,
    		    		StandardWatchEventKinds.ENTRY_MODIFY);
    		} catch (IOException x) {
    		    System.err.println(x);
    		}
    Et j'ai une erreur sur le register, qui est :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    The method register(WatchService, WatchEvent.Kind[], WatchEvent.Modifier[]) in the type Path is not applicable for the arguments (WatchService, WatchEvent.Kind, WatchEvent.Kind, WatchEvent.Kind)
    Et je voit pas comment la résoudre

  5. #5
    Membre Expert

    Homme Profil pro
    Consultant informatique
    Inscrit en
    Janvier 2004
    Messages
    2 301
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Janvier 2004
    Messages : 2 301
    Par défaut
    Ton code, sans aucune modification, compile et s'exécute en Java 7 chez moi.

  6. #6
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Ça a fonctionné chez moi aussi, bizaree
    Sinon depuis j'ai avancé et finit mon code de test qui fonctionne : une fois run il tourne en boucle et m'indique lorsqu'un nouveau fichier .pdf arrive dans le répertoire. Si ça n'est pas un .pdf il me l'indique

    Voici le code si vous voulez :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    package test;
    import java.io.IOException;
    import java.nio.*;
    import java.nio.file.*;
    import java.nio.file.StandardWatchEventKinds.*;
    import java.util.Iterator;
     
     
     
     
     
    public class testpath {
     
    	public static void main(String[] args)
    	{
    		// TODO Auto-generated method stub
     
    		Path chemin = Paths.get("C:/Users/avide/Desktop/facture/test.pdf", args);
     
    		System.out.println("toString()     = " + chemin.toString());
    		System.out.println("getFileName()  = " + chemin.getFileName());
    		System.out.println("getRoot()      = " + chemin.getRoot());
    		System.out.println("getName(0)     = " + chemin.getName(0));
    		System.out.println("getNameCount() = " + chemin.getNameCount());
    		System.out.println("getParent()    = " + chemin.getParent());
    		System.out.println("subpath(0,3)   = " + chemin.subpath(0,3));
     
    try {
     
    		final Path dir = Paths.get("C:/Users/avide/Documents/test");
    		WatchService watcher = FileSystems.getDefault().newWatchService();
     
    		WatchKey key = dir.register(watcher,
    	    		StandardWatchEventKinds.ENTRY_CREATE);
     
    for (;;) {
     
    		    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); //On récupère l'extension du fichier
    		        try {
    		            Path child = dir.resolve(filename);
    		            if (!Files.probeContentType(child).equals("application/pdf")) {
     
    		                System.err.format("New file '%s'" +
    		                    " is not a pdf application file.%n", filename);
    		                continue;
     
     
    		           }
    		        } catch (IOException x) {
    		            System.err.println(x);
     
    		            continue;
    		        }
     
    		        //Affiche la variable filename et son extension
    		        System.out.println("File : "+filename +" Type : " +type);
    		    }
    		    if (!valid) {
    		        break;
    		    }
    		}
    Maintenant il faut que je modifie les noms qui s'affiche dans le menu graphique de l'application (déjà que ou ), que je trouve la variable où est renseignée le nom de répertoire entré, comment s'enregistre le document de sortie (car il faut soit : rien renseigner et il se met dans le même répertoire + même nom avec "_signed" en plus soit : avoir renseigner le chemin de sortie AVEC son nom) et ce qu'il se passe dans l'appli lorsqu'on "signe" pour appeler ce même code lorsqu'il y a un nouveau document dans le répertoire

    Si vous avez des idées de solutions n'hésiter pas, je vous tiens au courant de la suite



    EDIT : Je pense avoir trouver le code qui signe le document fourni, je vais éplucher ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    /*
     * The contents of this file are subject to the Mozilla Public License
     * Version 1.1 (the "License"); you may not use this file except in
     * compliance with the License. You may obtain a copy of the License at
     * http://www.mozilla.org/MPL/
     * 
     * Software distributed under the License is distributed on an "AS IS"
     * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     * License for the specific language governing rights and limitations
     * under the License.
     * 
     * The Original Code is 'JSignPdf, a free application for PDF signing'.
     * 
     * The Initial Developer of the Original Code is Josef Cacek.
     * Portions created by Josef Cacek are Copyright (C) Josef Cacek. All Rights Reserved.
     * 
     * Contributor(s): Josef Cacek.
     * 
     * Alternatively, the contents of this file may be used under the terms
     * of the GNU Lesser General Public License, version 2.1 (the  "LGPL License"), in which case the
     * provisions of LGPL License are applicable instead of those
     * above. If you wish to allow use of your version of this file only
     * under the terms of the LGPL License and not to allow others to use
     * your version of this file under the MPL, indicate your decision by
     * deleting the provisions above and replace them with the notice and
     * other provisions required by the LGPL License. If you do not delete
     * the provisions above, a recipient may use your version of this file
     * under either the MPL or the LGPL License.
     */
    package net.sf.jsignpdf;
     
    import static net.sf.jsignpdf.Constants.*;
     
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.Proxy;
    import java.security.MessageDigest;
    import java.security.PrivateKey;
    import java.security.cert.Certificate;
    import java.security.cert.X509Certificate;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
     
    import net.sf.jsignpdf.crl.CRLInfo;
    import net.sf.jsignpdf.ssl.SSLInitializer;
    import net.sf.jsignpdf.types.HashAlgorithm;
    import net.sf.jsignpdf.types.PDFEncryption;
    import net.sf.jsignpdf.types.RenderMode;
    import net.sf.jsignpdf.types.ServerAuthentication;
    import net.sf.jsignpdf.utils.FontUtils;
    import net.sf.jsignpdf.utils.KeyStoreUtils;
     
    import org.apache.commons.lang3.ArrayUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.commons.lang3.text.StrSubstitutor;
    import org.apache.log4j.Logger;
     
    import com.lowagie.text.Font;
    import com.lowagie.text.Image;
    import com.lowagie.text.Rectangle;
    import com.lowagie.text.pdf.AcroFields;
    import com.lowagie.text.pdf.OcspClientBouncyCastle;
    import com.lowagie.text.pdf.PdfDate;
    import com.lowagie.text.pdf.PdfDictionary;
    import com.lowagie.text.pdf.PdfName;
    import com.lowagie.text.pdf.PdfPKCS7;
    import com.lowagie.text.pdf.PdfReader;
    import com.lowagie.text.pdf.PdfSignature;
    import com.lowagie.text.pdf.PdfSignatureAppearance;
    import com.lowagie.text.pdf.PdfStamper;
    import com.lowagie.text.pdf.PdfString;
    import com.lowagie.text.pdf.PdfWriter;
    import com.lowagie.text.pdf.TSAClientBouncyCastle;
     
    /**
     * Main logic of signer application. It uses iText to create signature in PDF.
     * 
     * @author Josef Cacek
     */
    public class SignerLogic implements Runnable {
     
    	private final static Logger LOGGER = Logger.getLogger(SignerLogic.class);
     
    	private final BasicSignerOptions options;
     
    	/**
             * Constructor with all necessary parameters.
             * 
             * @param anOptions
             *            options of signer
             */
    	public SignerLogic(final BasicSignerOptions anOptions) {
    		if (anOptions == null) {
    			throw new NullPointerException("Options has to be filled.");
    		}
    		options = anOptions;
    	}
     
    	/*
    	 * (non-Javadoc)
    	 * 
    	 * @see java.lang.Runnable#run()
    	 */
    	public void run() {
    		signFile();
    	}
     
    	/**
             * Signs a single file.
             * 
             * @return true when signing is finished succesfully, false otherwise
             */
    	public boolean signFile() {
    		final String outFile = options.getOutFileX();
    		if (!validateInOutFiles(options.getInFile(), outFile)) {
    			LOGGER.info(RES.get("console.skippingSigning"));
    			return false;
    		}
     
    		boolean finished = false;
    		Throwable tmpException = null;
    		FileOutputStream fout = null;
    		try {
    			SSLInitializer.init(options);
     
    			final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options);
    			final PrivateKey key = pkInfo.getKey();
    			final Certificate[] chain = pkInfo.getChain();
    			if (ArrayUtils.isEmpty(chain)) {
    				// the certificate was not found
    				LOGGER.info(RES.get("console.certificateChainEmpty"));
    				return false;
    			}
    			LOGGER.info(RES.get("console.createPdfReader", options.getInFile()));
    			PdfReader reader;
    			try {
    				reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStrX().getBytes());
    			} catch (Exception e) {
    				try {
    					reader = new PdfReader(options.getInFile(), new byte[0]);
    				} catch (Exception e2) {
    					// try to read without password
    					reader = new PdfReader(options.getInFile());
    				}
    			}
     
    			LOGGER.info(RES.get("console.createOutPdf", outFile));
    			fout = new FileOutputStream(outFile);
     
    			final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX();
     
    			LOGGER.info(RES.get("console.createSignature"));
    			char tmpPdfVersion = '\0'; // default version - the same as input
    			if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) {
    				// this covers also problems with visible signatures (embedded
    				// fonts) in PDF 1.2, because the minimal version
    				// for hash algorithms is 1.3 (for SHA1)
    				if (options.isAppendX()) {
    					// if we are in append mode and version should be updated
    					// then return false (not possible)
    					LOGGER.info(RES.get("console.updateVersionNotPossibleInAppendMode"));
    					return false;
    				}
    				tmpPdfVersion = hashAlgorithm.getPdfVersion();
    				LOGGER.info(RES.get("console.updateVersion", new String[] { String.valueOf(reader.getPdfVersion()),
    						String.valueOf(tmpPdfVersion) }));
    			}
     
    			final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, options.isAppendX());
    			if (!options.isAppendX()) {
    				// we are not in append mode, let's remove existing signatures
    				// (otherwise we're getting to troubles)
    				final AcroFields acroFields = stp.getAcroFields();
    				@SuppressWarnings("unchecked")
    				final List<String> sigNames = acroFields.getSignatureNames();
    				for (String sigName : sigNames) {
    					acroFields.removeField(sigName);
    				}
    			}
    			if (options.isAdvanced() && options.getPdfEncryption() != PDFEncryption.NONE) {
    				LOGGER.info(RES.get("console.setEncryption"));
    				final int tmpRight = options.getRightPrinting().getRight()
    						| (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0)
    						| (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0)
    						| (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0)
    						| (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0)
    						| (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0)
    						| (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0);
    				switch (options.getPdfEncryption()) {
    				case PASSWORD:
    					stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStrX(), tmpRight);
    					break;
    				case CERTIFICATE:
    					final X509Certificate encCert = KeyStoreUtils.loadCertificate(options.getPdfEncryptionCertFile());
    					if (encCert == null) {
    						LOGGER.error(RES.get("console.pdfEncError.wrongCertificateFile",
    								StringUtils.defaultString(options.getPdfEncryptionCertFile())));
    						return false;
    					}
    					if (!KeyStoreUtils.isEncryptionSupported(encCert)) {
    						LOGGER.error(RES
    								.get("console.pdfEncError.cantUseCertificate", encCert.getSubjectDN().getName()));
    						return false;
    					}
    					stp.setEncryption(new Certificate[] { encCert }, new int[] { tmpRight },
    							PdfWriter.ENCRYPTION_AES_128);
    					break;
    				default:
    					LOGGER.error(RES.get("console.unsupportedEncryptionType"));
    					return false;
    				}
    			}
     
    			final PdfSignatureAppearance sap = stp.getSignatureAppearance();
    			sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
    			final String reason = options.getReason();
    			if (StringUtils.isNotEmpty(reason)) {
    				LOGGER.info(RES.get("console.setReason", reason));
    				sap.setReason(reason);
    			}
    			final String location = options.getLocation();
    			if (StringUtils.isNotEmpty(location)) {
    				LOGGER.info(RES.get("console.setLocation", location));
    				sap.setLocation(location);
    			}
    			final String contact = options.getContact();
    			if (StringUtils.isNotEmpty(contact)) {
    				LOGGER.info(RES.get("console.setContact", contact));
    				sap.setContact(contact);
    			}
    			LOGGER.info(RES.get("console.setCertificationLevel"));
    			sap.setCertificationLevel(options.getCertLevelX().getLevel());
     
    			if (options.isVisible()) {
    				// visible signature is enabled
    				LOGGER.info(RES.get("console.configureVisible"));
    				LOGGER.info(RES.get("console.setAcro6Layers", Boolean.toString(options.isAcro6Layers())));
    				sap.setAcro6Layers(options.isAcro6Layers());
     
    				final String tmpImgPath = options.getImgPath();
    				if (tmpImgPath != null) {
    					LOGGER.info(RES.get("console.createImage", tmpImgPath));
    					final Image img = Image.getInstance(tmpImgPath);
    					LOGGER.info(RES.get("console.setSignatureGraphic"));
    					sap.setSignatureGraphic(img);
    				}
    				final String tmpBgImgPath = options.getBgImgPath();
    				if (tmpBgImgPath != null) {
    					LOGGER.info(RES.get("console.createImage", tmpBgImgPath));
    					final Image img = Image.getInstance(tmpBgImgPath);
    					LOGGER.info(RES.get("console.setImage"));
    					sap.setImage(img);
    				}
    				LOGGER.info(RES.get("console.setImageScale"));
    				sap.setImageScale(options.getBgImgScale());
    				LOGGER.info(RES.get("console.setL2Text"));
    				final String signer = PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN");
    				final String timestamp = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z").format(sap.getSignDate()
    						.getTime());
    				if (options.getL2Text() != null) {
    					final Map<String, String> replacements = new HashMap<String, String>();
    					replacements.put(L2TEXT_PLACEHOLDER_SIGNER, StringUtils.defaultString(signer));
    					replacements.put(L2TEXT_PLACEHOLDER_TIMESTAMP, timestamp);
    					replacements.put(L2TEXT_PLACEHOLDER_LOCATION, StringUtils.defaultString(location));
    					replacements.put(L2TEXT_PLACEHOLDER_REASON, StringUtils.defaultString(reason));
    					replacements.put(L2TEXT_PLACEHOLDER_CONTACT, StringUtils.defaultString(contact));
    					final String l2text = StrSubstitutor.replace(options.getL2Text(), replacements);
    					sap.setLayer2Text(l2text);
    				} else {
    					final StringBuilder buf = new StringBuilder();
    					buf.append(RES.get("default.l2text.signedBy")).append(" ").append(signer).append('\n');
    					buf.append(RES.get("default.l2text.date")).append(" ").append(timestamp);
    					if (StringUtils.isNotEmpty(reason))
    						buf.append('\n').append(RES.get("default.l2text.reason")).append(" ").append(reason);
    					if (StringUtils.isNotEmpty(location))
    						buf.append('\n').append(RES.get("default.l2text.location")).append(" ").append(location);
    					sap.setLayer2Text(buf.toString());
    				}
    				if (FontUtils.getL2BaseFont() != null) {
    					sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize()));
    				}
    				LOGGER.info(RES.get("console.setL4Text"));
    				sap.setLayer4Text(options.getL4Text());
    				LOGGER.info(RES.get("console.setRender"));
    				RenderMode renderMode = options.getRenderMode();
    				if (renderMode == RenderMode.GRAPHIC_AND_DESCRIPTION && sap.getSignatureGraphic() == null) {
    					LOGGER.warn("Render mode of visible signature is set to GRAPHIC_AND_DESCRIPTION, but no image is loaded. Fallback to DESCRIPTION_ONLY.");
    					LOGGER.info(RES.get("console.renderModeFallback"));
    					renderMode = RenderMode.DESCRIPTION_ONLY;
    				}
    				sap.setRender(renderMode.getRender());
    				LOGGER.info(RES.get("console.setVisibleSignature"));
    				sap.setVisibleSignature(
    						new Rectangle(options.getPositionLLX(), options.getPositionLLY(), options.getPositionURX(),
    								options.getPositionURY()), options.getPage(), null);
    			}
     
    			LOGGER.info(RES.get("console.processing"));
    			final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
    			if (!StringUtils.isEmpty(reason)) {
    				dic.setReason(sap.getReason());
    			}
    			if (!StringUtils.isEmpty(location)) {
    				dic.setLocation(sap.getLocation());
    			}
    			if (!StringUtils.isEmpty(contact)) {
    				dic.setContact(sap.getContact());
    			}
    			dic.setDate(new PdfDate(sap.getSignDate()));
    			sap.setCryptoDictionary(dic);
     
    			final Proxy tmpProxy = options.createProxy();
     
    			final CRLInfo crlInfo = new CRLInfo(options, chain);
     
    			// CRLs are stored twice in PDF c.f.
    			// PdfPKCS7.getAuthenticatedAttributeBytes
    			final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount());
    			final Map<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    			exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
    			sap.preClose(exc);
     
    			PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null, false);
    			InputStream data = sap.getRangeStream();
    			final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName());
    			byte buf[] = new byte[8192];
    			int n;
    			while ((n = data.read(buf)) > 0) {
    				messageDigest.update(buf, 0, n);
    			}
    			byte hash[] = messageDigest.digest();
    			Calendar cal = Calendar.getInstance();
    			byte[] ocsp = null;
    			if (options.isOcspEnabledX() && chain.length >= 2) {
    				LOGGER.info(RES.get("console.getOCSPURL"));
    				String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
    				if (StringUtils.isEmpty(url)) {
    					// get from options
    					LOGGER.info(RES.get("console.noOCSPURL"));
    					url = options.getOcspServerUrl();
    				}
    				if (!StringUtils.isEmpty(url)) {
    					LOGGER.info(RES.get("console.readingOCSP", url));
    					final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0],
    							(X509Certificate) chain[1], url);
    					ocspClient.setProxy(tmpProxy);
    					ocsp = ocspClient.getEncoded();
    				}
    			}
    			byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
    			sgn.update(sh, 0, sh.length);
     
    			TSAClientBouncyCastle tsc = null;
    			if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) {
    				LOGGER.info(RES.get("console.creatingTsaClient"));
    				if (options.getTsaServerAuthn() == ServerAuthentication.PASSWORD) {
    					tsc = new TSAClientBouncyCastle(options.getTsaUrl(),
    							StringUtils.defaultString(options.getTsaUser()), StringUtils.defaultString(options
    									.getTsaPasswd()));
    				} else {
    					tsc = new TSAClientBouncyCastle(options.getTsaUrl());
     
    				}
    				tsc.setProxy(tmpProxy);
    				final String policyOid = options.getTsaPolicy();
    				if (StringUtils.isNotEmpty(policyOid)) {
    					LOGGER.info(RES.get("console.settingTsaPolicy", policyOid));
    					tsc.setPolicy(policyOid);
    				}
    			}
    			byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);
     
    			if (contentEstimated + 2 < encodedSig.length) {
    				System.err.println("SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length);
    				throw new Exception("Not enough space");
    			}
     
    			byte[] paddedSig = new byte[contentEstimated];
    			System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
     
    			PdfDictionary dic2 = new PdfDictionary();
    			dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
    			LOGGER.info(RES.get("console.closeStream"));
    			sap.close(dic2);
    			fout.close();
    			fout = null;
    			finished = true;
    		} catch (Exception e) {
    			LOGGER.error(RES.get("console.exception"), e);
    		} catch (OutOfMemoryError e) {
    			LOGGER.fatal(RES.get("console.memoryError"), e);
    		} finally {
    			if (fout != null) {
    				try {
    					fout.close();
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
     
    			LOGGER.info(RES.get("console.finished." + (finished ? "ok" : "error")));
    			options.fireSignerFinishedEvent(tmpException);
    		}
    		return finished;
    	}
     
    	/**
             * Validates if input and output files are valid for signing.
             * 
             * @param inFile
             *            input file
             * @param outFile
             *            output file
             * @return true if valid, false otherwise
             */
    	private boolean validateInOutFiles(final String inFile, final String outFile) {
    		LOGGER.info(RES.get("console.validatingFiles"));
    		if (StringUtils.isEmpty(inFile) || StringUtils.isEmpty(outFile)) {
    			LOGGER.info(RES.get("console.fileNotFilled.error"));
    			return false;
    		}
    		final File tmpInFile = new File(inFile);
    		final File tmpOutFile = new File(outFile);
    		if (!(tmpInFile.exists() && tmpInFile.isFile() && tmpInFile.canRead())) {
    			LOGGER.info(RES.get("console.inFileNotFound.error"));
    			return false;
    		}
    		if (tmpInFile.getAbsolutePath().equals(tmpOutFile.getAbsolutePath())) {
    			LOGGER.info(RES.get("console.filesAreEqual.error"));
    			return false;
    		}
    		return true;
    	}
     
    }

  7. #7
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Je vois enfin comment modifier tout ça, en gros l'utilisateur lance l'application
    Ensuite il signe un document (exemple.pdf) en renseignant : C:/.../exemple.pdf (l'entrée fichier donc) et C:/.../exemple_signed.pdf (sortie fichier)
    A partir de ce moment, mon code que j'aurais ajouter faire un Path répertoire1=getparents(chemin d'entrée) et Path répertoire2=getparents(chemin de sortie) : je récupère le chemin du répertoire d'entrée et de sortie

    S'il détecte un nouveau document dans répertoire1 mon code fera appel à Jsignpdf>src>net.sf.jsignpdf>SignerLogic.java>SignerLogic>signFile(). Mon code est dans Jsignpdf>src>net.sf.jsignpdf>test.java>test>main()

    Sauf que je sais pas comment appeler signFile() à partir d'un autre fichier dans le projet. La saisie des chemin des documents à l'air de se faire à chaque fois que l'on rentre dans signFile() .. Donc faudrait que j'aille aussi modifier dans signFile() du code.
    Pour ce dernier je pensais passer une variable(X=1) lorsqu'on a un nouveau fichier et dans signFile faire un if sur les chemins&nom : si X=1 alors chemin et nom d'entrée = chemin et nom du nouveau doc du répertoire 1 sinon c'est le chemin et nom saisie
    Et pour la sortie si X=1 alors chemin et nom de sortie = chemin du répertoire 2 et nom du doc de base avec "_signed" en plus

    Par exemple :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    On lance l'appli
    Chemin d'entrée = C:/.../repertoire_1/exemple.pdf 
    Chemin de sortie = C:/.../repertoire_2/exemple_signed.pdf 
    On clique sur "Signer", le document pdf se signe
     
    A partir de ce moment repertoire_1 sera surveillé et l'appli aura récupéré les chemins d'entrée et de sortie des répertoires 
    répertoire1=C:/.../repertoire_1
    répertoire2=C:/.../repertoire_2
     
    Un nouveau document arrive dans le répertoire
    Mon code vérifie si c'est un PDF, si oui il fait X=1 et appelle le code pour signer un doc, sinon il fait rien
    Et dans le code de signFile(), ou bien l'endroit où est saisie les chemins, j'ajoute if(X=1) : Chemin d'entrée = répertoire1 
    Chemin de sortie = répertoire2
    Voilà je sais pas ci c'est très clair pour vous, mon principal problème est que je ne sais pas comment, quand et où se font les saisies textes/des chemins .. Donc grosse galère

Discussions similaires

  1. [débutant] < forward path=A.B.C>
    Par wooky dans le forum Struts 1
    Réponses: 1
    Dernier message: 08/01/2007, 19h19
  2. (Débutant API) Utilisation de Richedit avec les APIs
    Par LibrairieSI dans le forum Windows
    Réponses: 2
    Dernier message: 10/08/2005, 16h53
  3. [Débutant] API WINDOWS pb de linker avec DEV-C++
    Par coolmaxou dans le forum Windows
    Réponses: 3
    Dernier message: 12/07/2005, 09h24
  4. [débutante][API] basculer vers une autre appli en VB6
    Par zazaraignée dans le forum Windows
    Réponses: 7
    Dernier message: 04/06/2004, 15h15

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo