2
* FirmarFacturaEView.java
5
package firmarfacturae;
7
import java.io.BufferedReader;
8
import java.io.FileInputStream;
9
import java.io.FileNotFoundException;
10
import java.io.FileOutputStream;
11
import java.io.IOException;
12
import java.io.InputStreamReader;
14
import java.security.cert.X509Certificate;
15
import java.text.SimpleDateFormat;
16
import java.util.Vector;
18
import org.jdesktop.application.Action;
19
import org.jdesktop.application.ResourceMap;
20
import org.jdesktop.application.SingleFrameApplication;
21
import org.jdesktop.application.FrameView;
22
import org.jdesktop.application.TaskMonitor;
24
import java.awt.event.ActionEvent;
25
import java.awt.event.ActionListener;
26
import javax.swing.Timer;
27
import javax.swing.Icon;
28
import javax.swing.JDialog;
29
import javax.swing.filechooser.FileNameExtensionFilter;
30
import javax.swing.JFrame;
33
import es.mityc.firmaJava.configuracion.Configuracion;
34
import es.mityc.firmaJava.configuracion.EnumAlmacenCertificados;
35
import es.mityc.firmaJava.libreria.errores.ClienteError;
36
import es.mityc.firmaJava.libreria.utilidades.UtilidadDNIe;
37
import es.mityc.firmaJava.libreria.utilidades.UtilidadFirmaElectronica;
38
import es.mityc.firmaJava.libreria.xades.InterfazFirma;
39
import es.mityc.firmaJava.libreria.xades.InterfazObjetoDeFirma;
40
import es.mityc.firmaJava.libreria.xades.ParametrosFirmaXML;
41
import es.mityc.firmaJava.libreria.xades.errores.FirmaXMLError;
44
* The application's main frame.
46
public class FirmarFacturaEView extends FrameView {
48
private Vector<X509Certificate> listCertificates = null;
49
private X509Certificate certificadoParaFirmar = null;
50
private String NOMBRE_FICHERO_A_FIRMAR = "";
51
private String NOMBRE_FICHERO_FIRMADO = "";
53
FileNameExtensionFilter filtro = new FileNameExtensionFilter("Xml", "xml");
55
public FirmarFacturaEView(SingleFrameApplication app) {
60
// status bar initialization - message timeout, idle icon and busy animation, etc
61
ResourceMap resourceMap = getResourceMap();
62
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
63
messageTimer = new Timer(messageTimeout, new ActionListener() {
64
public void actionPerformed(ActionEvent e) {
65
statusMessageLabel.setText("");
68
messageTimer.setRepeats(false);
69
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
70
for (int i = 0; i < busyIcons.length; i++) {
71
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
73
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
74
public void actionPerformed(ActionEvent e) {
75
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
76
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
79
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
80
statusAnimationLabel.setIcon(idleIcon);
81
progressBar.setVisible(false);
83
// connecting action tasks to status bar via TaskMonitor
84
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
85
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
86
public void propertyChange(java.beans.PropertyChangeEvent evt) {
87
String propertyName = evt.getPropertyName();
88
if ("started".equals(propertyName)) {
89
if (!busyIconTimer.isRunning()) {
90
statusAnimationLabel.setIcon(busyIcons[0]);
92
busyIconTimer.start();
94
progressBar.setVisible(true);
95
progressBar.setIndeterminate(true);
96
} else if ("done".equals(propertyName)) {
98
statusAnimationLabel.setIcon(idleIcon);
99
progressBar.setVisible(false);
100
progressBar.setValue(0);
101
} else if ("message".equals(propertyName)) {
102
String text = (String)(evt.getNewValue());
103
statusMessageLabel.setText((text == null) ? "" : text);
104
messageTimer.restart();
105
} else if ("progress".equals(propertyName)) {
106
int value = (Integer)(evt.getNewValue());
107
progressBar.setVisible(true);
108
progressBar.setIndeterminate(false);
109
progressBar.setValue(value);
114
jFileChooser1.setFileFilter(filtro);
118
public void showAboutBox() {
119
if (aboutBox == null) {
120
JFrame mainFrame = FirmarFacturaEApp.getApplication().getMainFrame();
121
aboutBox = new FirmarFacturaEAboutBox(mainFrame);
122
aboutBox.setLocationRelativeTo(mainFrame);
124
FirmarFacturaEApp.getApplication().show(aboutBox);
127
/** This method is called from within the constructor to
128
* initialize the form.
129
* WARNING: Do NOT modify this code. The content of this method is
130
* always regenerated by the Form Editor.
132
@SuppressWarnings("unchecked")
133
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
134
private void initComponents() {
136
mainPanel = new javax.swing.JPanel();
137
jTextOrigen = new javax.swing.JTextField();
138
jBtnOrigen = new javax.swing.JButton();
139
jTextDestino = new javax.swing.JTextField();
140
jBtnDestino = new javax.swing.JButton();
141
jCmbCertificados = new javax.swing.JComboBox();
142
jBtnCargar = new javax.swing.JButton();
143
jBtnFirmar = new javax.swing.JButton();
144
menuBar = new javax.swing.JMenuBar();
145
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
146
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
147
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
148
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
149
statusPanel = new javax.swing.JPanel();
150
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
151
statusMessageLabel = new javax.swing.JLabel();
152
statusAnimationLabel = new javax.swing.JLabel();
153
progressBar = new javax.swing.JProgressBar();
154
jFileChooser1 = new javax.swing.JFileChooser();
156
mainPanel.setName("mainPanel"); // NOI18N
158
jTextOrigen.setName("jTextOrigen"); // NOI18N
160
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(firmarfacturae.FirmarFacturaEApp.class).getContext().getResourceMap(FirmarFacturaEView.class);
161
jBtnOrigen.setText(resourceMap.getString("jBtnOrigen.text")); // NOI18N
162
jBtnOrigen.setActionCommand(resourceMap.getString("jBtnOrigen.actionCommand")); // NOI18N
163
jBtnOrigen.setName("jBtnOrigen"); // NOI18N
164
jBtnOrigen.addActionListener(new java.awt.event.ActionListener() {
165
public void actionPerformed(java.awt.event.ActionEvent evt) {
166
jBtnOrigenActionPerformed(evt);
170
jTextDestino.setName("jTextDestino"); // NOI18N
172
jBtnDestino.setText(resourceMap.getString("jBtnDestino.text")); // NOI18N
173
jBtnDestino.setName("jBtnDestino"); // NOI18N
174
jBtnDestino.addActionListener(new java.awt.event.ActionListener() {
175
public void actionPerformed(java.awt.event.ActionEvent evt) {
176
jBtnDestinoActionPerformed(evt);
180
jCmbCertificados.setName("jCmbCertificados"); // NOI18N
182
jBtnCargar.setText(resourceMap.getString("jBtnCargar.text")); // NOI18N
183
jBtnCargar.setName("jBtnCargar"); // NOI18N
184
jBtnCargar.addActionListener(new java.awt.event.ActionListener() {
185
public void actionPerformed(java.awt.event.ActionEvent evt) {
186
jBtnCargarActionPerformed(evt);
190
jBtnFirmar.setText(resourceMap.getString("jBtnFirmar.text")); // NOI18N
191
jBtnFirmar.setName("jBtnFirmar"); // NOI18N
192
jBtnFirmar.addActionListener(new java.awt.event.ActionListener() {
193
public void actionPerformed(java.awt.event.ActionEvent evt) {
194
jBtnFirmarActionPerformed(evt);
198
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
199
mainPanel.setLayout(mainPanelLayout);
200
mainPanelLayout.setHorizontalGroup(
201
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
202
.addGroup(mainPanelLayout.createSequentialGroup()
204
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
205
.addComponent(jTextDestino, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 345, Short.MAX_VALUE)
206
.addComponent(jTextOrigen, javax.swing.GroupLayout.DEFAULT_SIZE, 345, Short.MAX_VALUE)
207
.addGroup(mainPanelLayout.createSequentialGroup()
208
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 145, Short.MAX_VALUE)
209
.addComponent(jBtnCargar)
210
.addGap(109, 109, 109))
211
.addComponent(jCmbCertificados, javax.swing.GroupLayout.Alignment.LEADING, 0, 345, Short.MAX_VALUE))
213
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
214
.addComponent(jBtnOrigen, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
215
.addComponent(jBtnDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
216
.addGap(157, 157, 157))
217
.addGroup(mainPanelLayout.createSequentialGroup()
219
.addComponent(jBtnFirmar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
220
.addGap(486, 486, 486))
222
mainPanelLayout.setVerticalGroup(
223
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
224
.addGroup(mainPanelLayout.createSequentialGroup()
226
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
227
.addComponent(jTextOrigen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
228
.addComponent(jBtnOrigen))
230
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
231
.addComponent(jTextDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
232
.addComponent(jBtnDestino))
234
.addComponent(jCmbCertificados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
236
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
237
.addComponent(jBtnFirmar)
238
.addComponent(jBtnCargar))
239
.addContainerGap(20, Short.MAX_VALUE))
242
menuBar.setName("menuBar"); // NOI18N
244
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
245
fileMenu.setName("fileMenu"); // NOI18N
247
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(firmarfacturae.FirmarFacturaEApp.class).getContext().getActionMap(FirmarFacturaEView.class, this);
248
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
249
exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
250
exitMenuItem.setName("exitMenuItem"); // NOI18N
251
fileMenu.add(exitMenuItem);
253
menuBar.add(fileMenu);
254
fileMenu.getAccessibleContext().setAccessibleName(resourceMap.getString("fileMenu.AccessibleContext.accessibleName")); // NOI18N
256
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
257
helpMenu.setName("helpMenu"); // NOI18N
259
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
260
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
261
helpMenu.add(aboutMenuItem);
263
menuBar.add(helpMenu);
265
statusPanel.setName("statusPanel"); // NOI18N
267
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
269
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
271
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
272
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
274
progressBar.setName("progressBar"); // NOI18N
276
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
277
statusPanel.setLayout(statusPanelLayout);
278
statusPanelLayout.setHorizontalGroup(
279
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
280
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
281
.addGroup(statusPanelLayout.createSequentialGroup()
283
.addComponent(statusMessageLabel)
284
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 443, Short.MAX_VALUE)
285
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
286
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
287
.addComponent(statusAnimationLabel)
290
statusPanelLayout.setVerticalGroup(
291
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
292
.addGroup(statusPanelLayout.createSequentialGroup()
293
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
294
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
295
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
296
.addComponent(statusMessageLabel)
297
.addComponent(statusAnimationLabel)
298
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
302
jFileChooser1.setName("jFileChooser1"); // NOI18N
304
setComponent(mainPanel);
306
setStatusBar(statusPanel);
307
}// </editor-fold>//GEN-END:initComponents
309
private void jBtnOrigenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnOrigenActionPerformed
310
// TODO add your handling code here:
311
int returnVal = jFileChooser1.showDialog(mainPanel, "Fichero a Firmar");
313
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
314
jTextOrigen.setText(jFileChooser1.getSelectedFile().getPath());
316
}//GEN-LAST:event_jBtnOrigenActionPerformed
318
private void jBtnDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnDestinoActionPerformed
319
// TODO add your handling code here:
320
int returnVal = jFileChooser1.showDialog(mainPanel, "Fichero Firmado");
322
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
323
jTextDestino.setText(jFileChooser1.getSelectedFile().getPath());
325
}//GEN-LAST:event_jBtnDestinoActionPerformed
327
private void jBtnCargarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCargarActionPerformed
328
// TODO add your handling code here:
330
// Accedemos al almacén de certificados de internet explorer
331
InterfazFirma si = UtilidadFirmaElectronica.getSignatureInstance(EnumAlmacenCertificados.ALMACEN_EXPLORER);
333
listCertificates = si.getAllCertificates("My");
334
} catch (FirmaXMLError e1) {
335
e1.printStackTrace();
338
mostrarInformacionCertificados(listCertificates);
340
}//GEN-LAST:event_jBtnCargarActionPerformed
342
private void jBtnFirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnFirmarActionPerformed
343
// TODO add your handling code here:
344
NOMBRE_FICHERO_A_FIRMAR = jTextOrigen.getText();
345
NOMBRE_FICHERO_FIRMADO = jTextDestino.getText();
346
System.out.println(jCmbCertificados.getSelectedIndex());
347
certificadoParaFirmar = (X509Certificate) listCertificates.get(jCmbCertificados.getSelectedIndex());
350
} catch (Exception e) {
353
}//GEN-LAST:event_jBtnFirmarActionPerformed
355
private void finalizarFirma() throws Exception {
357
// Instanciamos la estructura de datos que almacenará el resultado de la firma
358
byte[] resultadoFirma = null;
360
// Instanciamos la clase Configuracion de Libreriaconfiguracion
361
Configuracion configuracion = new Configuracion();
362
// Cargamos el valor de los parámetros contenidos en el fichero SignXML.properties
363
configuracion.cargarConfiguracion();
365
// Se lee el fichero a firmar
366
String rutaFicheroAFirmar = NOMBRE_FICHERO_A_FIRMAR;
367
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(rutaFicheroAFirmar), "UTF-8"));
369
// Atención!!! aquí cambiamos los saltos de carro del fichero original para facilitar la lectura del ejemplo
370
// Si se ha de firmar exactamente el mismo fichero de entrada la lectura no ha de modificar el resultado.
371
StringBuffer xmlToSign = new StringBuffer();
373
xmlToSign.append(in.readLine());
376
// Nodos que contendrán las firmas del fichero (se incluye Certificate1 porque será donde irá el certificado de firma)
377
String nodesToSign = "Certificate1,";
378
configuracion.setValor("xmlNodeToSign", nodesToSign);
380
// Para firmar con un certificado del almacén de Internet Explorer
381
InterfazObjetoDeFirma soi = UtilidadFirmaElectronica.getSignatureObject(EnumAlmacenCertificados.ALMACEN_EXPLORER,
382
certificadoParaFirmar,
386
// Para firmar con un certificado del almacén de Mozilla
387
//InterfazObjetoDeFirma soi = UtilidadFirmaElectronica.getSignatureObject(EnumAlmacenCertificados.ALMACEN_EXPLORER,
388
// cert.getSerialNumber(),
389
// cert.getIssuerDN().toString(),
390
// "Poner aqui la ruta al perfil de Mozilla",
393
// Se prepara e inicializa el interfaz de firma
396
} catch (ClienteError e1) {
397
e1.printStackTrace();
400
// Se realiza la firma
402
resultadoFirma = soi.sign(xmlToSign.toString());
403
} catch (ClienteError e) {
407
if (resultadoFirma != null) {
408
System.out.println("\n\nLa firma se creo correctamente. Se salva con el nombre " + NOMBRE_FICHERO_FIRMADO);
410
// Una vez finalizada la firma, escribimos el resultado en el fichero de salida
411
grabarAFichero(resultadoFirma);
413
// Si se quiere continuar realizando validaciones o firmas es necesario inicializar esta estructura
414
ParametrosFirmaXML.initialize();
416
System.out.println("\n\nLa firma NO se creo correctamente");
419
private void grabarAFichero(byte[] firmaXADESByte) {
421
FileOutputStream fos = null;
423
String rutaFicheroFirmado = NOMBRE_FICHERO_FIRMADO;
424
fos = new FileOutputStream(rutaFicheroFirmado);
425
fos.write(firmaXADESByte);
426
} catch (FileNotFoundException e) {
428
} catch (IOException e) {
434
} catch (IOException e) {
440
private void mostrarInformacionCertificados(Vector<X509Certificate> listCertificates) {
442
for (int a = 0; a < listCertificates.size(); a++) {
443
X509Certificate certTemp = (X509Certificate) listCertificates.get(a);
445
jCmbCertificados.addItem(UtilidadDNIe.getCN(certTemp, UtilidadDNIe.SUBJECT_OR_ISSUER.SUBJECT));
449
// Variables declaration - do not modify//GEN-BEGIN:variables
450
private javax.swing.JButton jBtnCargar;
451
private javax.swing.JButton jBtnDestino;
452
private javax.swing.JButton jBtnFirmar;
453
private javax.swing.JButton jBtnOrigen;
454
private javax.swing.JComboBox jCmbCertificados;
455
private javax.swing.JFileChooser jFileChooser1;
456
private javax.swing.JTextField jTextDestino;
457
private javax.swing.JTextField jTextOrigen;
458
private javax.swing.JPanel mainPanel;
459
private javax.swing.JMenuBar menuBar;
460
private javax.swing.JProgressBar progressBar;
461
private javax.swing.JLabel statusAnimationLabel;
462
private javax.swing.JLabel statusMessageLabel;
463
private javax.swing.JPanel statusPanel;
464
// End of variables declaration//GEN-END:variables
466
private final Timer messageTimer;
467
private final Timer busyIconTimer;
468
private final Icon idleIcon;
469
private final Icon[] busyIcons = new Icon[15];
470
private int busyIconIndex = 0;
472
private JDialog aboutBox;