View Javadoc

1   package org.eparapher.rcp.actions;
2   
3   import java.io.File;
4   import java.util.ArrayList;
5   import java.util.Iterator;
6   
7   import org.apache.log4j.Logger;
8   import org.eclipse.core.runtime.IProgressMonitor;
9   import org.eclipse.core.runtime.IStatus;
10  import org.eclipse.core.runtime.Status;
11  import org.eclipse.core.runtime.jobs.IJobChangeEvent;
12  import org.eclipse.core.runtime.jobs.Job;
13  import org.eclipse.core.runtime.jobs.JobChangeAdapter;
14  import org.eclipse.jface.action.Action;
15  import org.eclipse.jface.viewers.ISelection;
16  import org.eclipse.jface.viewers.IStructuredSelection;
17  import org.eclipse.jface.viewers.TreeViewer;
18  import org.eclipse.jface.window.Window;
19  import org.eclipse.jface.wizard.WizardDialog;
20  import org.eclipse.swt.SWT;
21  import org.eclipse.swt.widgets.Display;
22  import org.eclipse.ui.IWorkbenchWindow;
23  import org.eclipse.ui.PlatformUI;
24  import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
25  import org.eparapher.core.crypto.EPKeystoreManager;
26  import org.eparapher.core.crypto.keystore.IUserKeystore;
27  import org.eparapher.rcp.tools.GUIIcons;
28  import org.eparapher.rcp.tools.eParapherTools;
29  import org.eparapher.rcp.views.documents.SecuredDocumentsView.TreeObject;
30  import org.eparapher.rcp.views.documents.SecuredDocumentsView.TreeParent;
31  import org.eparapher.rcp.wizards.CMSSigningWizard;
32  import org.eparapher.core.signature.CMSSignatureParameters;
33  import org.eparapher.core.signature.CMSSigner;
34  
35  public class CMSSignDocumentAction extends Action implements IWorkbenchAction {
36  
37  	private static Logger log = Logger.getLogger(CMSSignDocumentAction.class);
38  	
39  	private TreeViewer viewer;
40  	private boolean usewizard;
41  	private IWorkbenchWindow window;
42  	
43  	public CMSSignDocumentAction() {
44  		this(null,true);
45  	}
46  
47  	public CMSSignDocumentAction(TreeViewer mviewer, boolean museWizard) {
48  		super();
49  		viewer = mviewer;
50  		usewizard = museWizard;
51  		window=null;
52  		this.setId("CMSSignDocumentAction");
53  		this.setImageDescriptor(GUIIcons.SIGNATURE_ICON);
54  		if (!usewizard) {
55  			this.setText("CMS Digital Signature");
56  			this.setToolTipText("Sign your document(s) in CMS format with default parameters");
57  			this.setAccelerator(SWT.CTRL | 'R');
58  		} else {
59  			this.setText("CMS Digital Signature (wizard)");
60  			this.setToolTipText("Sign your document(s) in CMS format with a wizard");
61  			this.setAccelerator(SWT.CTRL | 'T');
62  		}
63  	}
64  
65  	public CMSSignDocumentAction(IWorkbenchWindow mwindow) {
66  		this();
67  		window=mwindow;
68  	}
69  
70  	public void run() {
71  		CMSSigningJob job = new CMSSigningJob();
72  		if (job.isSigningPrivateKeyLoaded) {
73  			job.setUser(true);
74  			job.schedule();
75  		}
76  	}
77  
78  	private CMSSignatureParameters getSignatureParameters() {
79  
80  		CMSSignatureParameters cmssignparams = new CMSSignatureParameters();
81  		cmssignparams.setCMSSignatureParamsFromPreferences();
82  		if (viewer != null)
83  			cmssignparams.setFileSelectiontoSign(getFileSelectionFromView());
84  		
85  		if (usewizard) {
86  			//Launch Wizard to get CMS Signature Parameters
87  			CMSSigningWizard cmsWizard = new CMSSigningWizard(cmssignparams);
88  			if (window==null)
89  				window=PlatformUI.getWorkbench().getActiveWorkbenchWindow();
90  			WizardDialog dialog = new WizardDialog(window.getShell(), cmsWizard);
91  			try {
92  			if ( dialog.open() != Window.OK ) {
93  				log.warn("CMS signing wizard cancelled");
94  				return null;
95  			}
96  			} catch (Exception e) {
97  				log.debug("Problem while invoking the CMS Settings Signature Wizard",e);
98  			}
99  			//recover params from wizard
100 			cmssignparams = cmsWizard.getCMSSignatureParams();
101 		}
102 		return cmssignparams;
103 	}
104 
105 	private File[] getFileSelectionFromView() {
106 
107 		ArrayList<File> fileList = new ArrayList<File>();
108 
109 		if (viewer.getSelection()!=null && !viewer.getSelection().isEmpty()) {
110 			// Iterate over selected file in view
111 			ISelection selection = viewer.getSelection();
112 			IStructuredSelection structselection = (IStructuredSelection) selection;
113 			
114 			//Build File Array from Table Selection
115 			for (Iterator<Object> iterator = structselection.iterator(); iterator.hasNext();) {
116 				Object obj =  iterator.next();
117 				if (obj instanceof TreeParent)
118 					//TODO : sign all files in a directory (if confirm?)
119 					eParapherTools.debugMessage("Cannot sign a directory!");
120 				else {
121 					TreeObject to = (TreeObject) obj;
122 					File f = new File(to.getFilePath());
123 					if (!f.exists())
124 						log.error("file " + to.getFilePath() + " has been deleted");
125 					else
126 						fileList.add(f);
127 				}
128 			}
129 		}
130 		return fileList.toArray(new File[] {});
131 	}
132 
133 	public void dispose() {
134 		
135 	}
136 
137 	class CMSSigningJob extends Job {
138 
139 		private CMSSignatureParameters cmssignparams;
140 		
141 		private CMSSigner cmssigner;
142 
143 		private String originalAlias;
144 		protected boolean isSigningPrivateKeyLoaded;
145 
146 		protected CMSSigningJob() {
147 
148 			super("CMS Signer job");
149 			
150 			//this.setUser(true);
151 			//this.setSystem(true);
152 			// Getting signature settings (with wizard if needed)
153 			cmssignparams = getSignatureParameters();
154 			if (cmssignparams.getFileSelectiontoSign().length==0) {
155 				log.info("Nothing to sign");
156 				return;
157 			}
158 			
159 			IUserKeystore userpkandcert = EPKeystoreManager.getInstance().getUserkeystore();
160 			
161 			if (cmssignparams != null ) {
162 				
163 				// Set the alias keystore to use
164 				originalAlias = userpkandcert.getDefaultAlias();
165 				if (cmssignparams.getSignatureAlias()!=null
166 					&& userpkandcert.containsAlias(cmssignparams.getSignatureAlias()) )
167 					userpkandcert.setDefaultAlias(cmssignparams.getSignatureAlias());
168 				
169 				//Load the private key (Ask PIN or Passphrase)
170 				isSigningPrivateKeyLoaded = userpkandcert.loadPrivateKey();
171 				
172 				if (isSigningPrivateKeyLoaded) {
173 					cmssigner = new CMSSigner();
174 					
175 					//End Job Listener
176 					this.addJobChangeListener(new JobChangeAdapter() {
177 						public void done(IJobChangeEvent event) {
178 							if (event.getResult().isOK())
179 								log.info("CMS Signing Job completed successfully");
180 							else
181 								log.warn("CMS Signing Job did not complete successfully");
182 						}
183 					});
184 				}
185 			}
186 		}
187 		
188 		@SuppressWarnings("unchecked")
189 		@Override
190 		protected IStatus run(IProgressMonitor monitor) {
191 			
192 			if ( cmssignparams != null && isSigningPrivateKeyLoaded) {
193 				monitor.beginTask("CMS Signing", cmssignparams.getFileSelectiontoSign().length );
194 				File[] f2s = cmssignparams.getFileSelectiontoSign();
195 				for (int i = 0; i < f2s.length; i++) {
196 					
197 					monitor.subTask("Signing "+f2s[i].getName());
198 					cmssigner.sign( f2s[i].getAbsolutePath(), cmssignparams);
199 					monitor.worked(1);
200 
201 					//refresh the view
202 					Display.getDefault().asyncExec(new Runnable() {
203 						public void run() {	if (viewer != null) viewer.refresh(); }
204 					});
205 				}
206 				monitor.done();
207 			}
208 			if (originalAlias!=null)
209 				EPKeystoreManager.getInstance().getUserkeystore().setDefaultAlias(originalAlias);
210 
211 			return Status.OK_STATUS;
212 		}
213 	}
214 
215 }