package org.simantics.fileimport.ui; import java.nio.file.Paths; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import javax.inject.Named; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.e4.core.di.annotations.CanExecute; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; import org.simantics.db.Resource; import org.simantics.fileimport.FileImportService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ImportFileHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ImportFileHandler.class); @CanExecute public boolean canExecute() { return !FileImportService.supportedExtensionsWithFilters().isEmpty(); } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) ISelection selection, @Named(IServiceConstants.ACTIVE_SHELL) Shell shell) { Map extensions = FileImportService.supportedExtensionsWithFilters(); String[] filterExtensions = (String[]) extensions.keySet().toArray(new String[extensions.keySet().size()]); String[] filterNames = (String[]) extensions.values().toArray(new String[extensions.values().size()]); // Sanity check for (int i = 0; i < filterExtensions.length; i++) { String extension = filterExtensions[i]; if (!extension.startsWith("*.")) { //$NON-NLS-1$ System.err.println("Invalid extension filter provied: " + extension); //$NON-NLS-1$ } } FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setText(Messages.ImportFileHandler_ChooseFile); dialog.setFilterExtensions(filterExtensions); dialog.setFilterNames(filterNames); final String fileName = dialog.open(); if (fileName == null) return; Resource selectedResource = null; try { if(selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection)selection; Object elem = structuredSelection.getFirstElement(); IAdaptable a = (IAdaptable)elem; selectedResource = a.getAdapter(Resource.class); } } catch(NullPointerException | ClassCastException npe) { LOGGER.warn("Failed to find selection, passing null to file importer", npe); //$NON-NLS-1$ } FileImportService.performFileImport(Paths.get(fileName), Optional.of(selectedResource), Optional.of((Consumer) t -> { LOGGER.error("Could not import file " + fileName, t); //$NON-NLS-1$ })); } }