View Javadoc
1   /*
2    * Copyright (C) 2007-2012 Argeo GmbH
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.argeo.eclipse.ui.specific;
17  
18  import static org.argeo.eclipse.ui.utils.SingleSourcingConstants.FILE_SCHEME;
19  import static org.argeo.eclipse.ui.utils.SingleSourcingConstants.SCHEME_HOST_SEPARATOR;
20  
21  import java.awt.Desktop;
22  import java.io.File;
23  import java.io.IOException;
24  
25  import org.argeo.eclipse.ui.utils.SingleSourcingConstants;
26  import org.eclipse.core.commands.AbstractHandler;
27  import org.eclipse.core.commands.ExecutionEvent;
28  import org.eclipse.core.commands.ExecutionException;
29  
30  /**
31   * RCP specific command handler to open a file.
32   * 
33   * The parameter "URI" is used to determine the correct method to open it.
34   * 
35   * Various instances of this handler with different command ID might coexist in
36   * order to provide context specific open file services.
37   * 
38   */
39  public class OpenFile extends AbstractHandler {
40  	// private final static Log log = LogFactory.getLog(OpenFile.class);
41  	public final static String ID = SingleSourcingConstants.OPEN_FILE_CMD_ID;
42  	public final static String PARAM_FILE_NAME = SingleSourcingConstants.PARAM_FILE_NAME;
43  	public final static String PARAM_FILE_URI = SingleSourcingConstants.PARAM_FILE_URI;
44  
45  	public Object execute(ExecutionEvent event) throws ExecutionException {
46  		String fileUri = event.getParameter(PARAM_FILE_URI);
47  
48  		// sanity check
49  		if (fileUri == null || "".equals(fileUri.trim()))
50  			return null;
51  
52  		Desktop desktop = null;
53  		if (Desktop.isDesktopSupported()) {
54  			desktop = Desktop.getDesktop();
55  		}
56  
57  		File file = getFileFromUri(fileUri);
58  		if (file != null)
59  			try {
60  				desktop.open(file);
61  			} catch (IOException e) {
62  				throw new SingleSourcingException("Unable to open file with URI: " + fileUri, e);
63  			}
64  		return null;
65  	}
66  
67  	protected File getFileFromUri(String uri) {
68  		if (uri.startsWith(FILE_SCHEME)) {
69  			String path = uri.substring((FILE_SCHEME + SCHEME_HOST_SEPARATOR).length());
70  			return new File(path);
71  		}
72  		return null;
73  	}
74  }