package afryca.consensusmodel.command; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.io.IOUtils; import org.eclipse.core.commands.ExecutionException; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.core.services.log.ILoggerProvider; import org.eclipse.e4.core.services.log.Logger; import org.eclipse.e4.core.services.nls.Translation; import afryca.consensusmodel.Configuration; import afryca.consensusmodel.l10n.Messages; /** * Command for open consensus model configuration * * @author Sinbad² * @version 3.0 */ @SuppressWarnings("restriction") public class OpenConfiguration { public static final String ID = "afryca.consensusmodel.command.open_configuration"; //$NON-NLS-1$ public static final String FILE_PARAMETER = "file"; //$NON-NLS-1$ private Logger logger; @Inject @Translation Messages messages; @Inject public void instantiateLogger(ILoggerProvider loggerProvider) { logger = loggerProvider.getClassLogger(this.getClass()); } @Execute public Configuration execute(@Named(FILE_PARAMETER) String file) throws Exception { logger.info(messages.command_executed, ID); return readConfiguration(file); } private Configuration readConfiguration(String file) throws ExecutionException { Configuration configuration = null; if (file != null) { InputStream inputStream = null; try { if (isValidFile(file)) { inputStream = new FileInputStream(file); } else if (isValidURL(file)) { inputStream = new URL(file).openStream(); } else { throw new ExecutionException(messages.wrong_file); } configuration = Configuration.parseConfiguration(IOUtils.toString(inputStream, "UTF-8")); //$NON-NLS-1$ configuration.setFile(file); inputStream.close(); } catch (IOException es) { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { } } throw new ExecutionException(messages.wrong_file); } } return configuration; } private static boolean isValidFile(String fileName) { File file = new File(fileName); return (file.exists() && file.canRead()); } private static boolean isValidURL(String url) { URL u = null; try { u = new URL(url); } catch (MalformedURLException e) { return false; } try { u.toURI(); } catch (URISyntaxException e) { return false; } return true; } }