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 :

Variable qui se réinitialise


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 Variable qui se réinitialise
    Bonjour à tous,

    Je suis en train de modifier une application java open source pour mon stage (tout en étant débutant en langage JAVA ..) et je suis bloqué

    C'est une application pour signer les documents pdf et je dois rendre la signature "automatique" dés qu'un fichier arrive dans un répertoire

    Dans le main() de l'appli j'ai ajouté mon code de "scrutation" : qui me permet de savoir quand il y a un nouveau fichier dans le répertoire que j'ai ciblé "manuellement" (je fait pas encore de saisie pour l'instant)
    Quand il y a un nouveau fichier je récupère son chemin complet, j'actualise le chemin de sortie avec le nom du nouveau fichier et je passe ma variable auto à 1 pour la suite
    Juste après j'appelle la méthode d'une autre classe pour signer un document, de la même façon que si j'avais cliqué sur "signer"

    Mon problème c'est que mes variables sont null et auto = 0 à la sortie du main() // l'entrée de la méthode pour signer et je sais pas comment résoudre le problème :/

    Visiblement les variables se réinitialise lorsque je les appelle dans ma méthode pour signer, de cette manière : (Signer étant ma classe main() )
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    Signer Sg = new Signer();
    int atq;
    atq= Sg.auto;
    String infile = Sg.FileIn.toString();
    String outfile = Sg.FileOut.toString();
    Suite à ça j'ai déclarer mes 3 variables en static pour voir si ça aller fonctionner : même problème

    C'est peut être une erreur toute simple, mais étant débutant je vois pas .. Peut être que vous la verrez

  2. #2
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 713
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 713
    Par défaut
    Sans le code de la classe "Signer", cela ne va pas être facile de t'aider
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

  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
    Voici le code de la classe, le code que j'ai ajouté dans le main est en couleur
    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
    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);
    		}
    	}
    }

  4. #4
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 713
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 713
    Par défaut Variable static masquée
    Ben déjà, à la ligne 92 tu déclares la variable static "auto"
    mais à la ligne 255, tu la déclares à nouveau.
    Du coup, la déclaration à la ligne 255 masque la déclaration static de la ligne 92.
    et donc auto (static) est toujours null
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

  5. #5
    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
    Quel erreur de c** ! Du coup j'ai fait la même erreur pour FileIn et FileOut j'ai rectifié ça et la signature automatique fonctionne ! MERCI !

    Maintenant faut que je trouve une solution pour la saisie des répertoires d'entrée et de sortie : 1) est ce que je rajoute deux champ de texte sachant que je sais pas comment on fait, ou alors je me débrouille avec les nom de fichier d'entrée et de sortie de base de l'application sachant que les méthodes et classe existent déjà : il resterait plus qu'a voir quand faire la saisie

  6. #6
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 713
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 713
    Par défaut
    Est-ce que les répertoires vont changer en fonction d'un choix de l'utilisateur ?
    Si c'est le cas, tu peux regarder du côté de JFileChooser avec l'option DIRECTORIES_ONLY si tu ne veux voir que les répertoires
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. j'ai une variable qui se réinitialise à 0
    Par maserati dans le forum Zend Framework
    Réponses: 8
    Dernier message: 03/02/2011, 02h41
  2. variable qui se réinitialise toujours à zéro
    Par ordi_pentium dans le forum Qt
    Réponses: 6
    Dernier message: 22/04/2010, 12h32
  3. Réponses: 4
    Dernier message: 11/11/2007, 09h41
  4. Variable qui évolue en fonction des choix dans formulaire
    Par stefou007 dans le forum Général JavaScript
    Réponses: 1
    Dernier message: 06/09/2005, 22h40
  5. Variable qui change après un DispatchMessage
    Par SekYo dans le forum Windows
    Réponses: 9
    Dernier message: 30/09/2004, 16h22

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