import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
+import org.simantics.databoard.util.Base64;
import org.simantics.fileimport.dropins.FileImportDropins;
+import org.simantics.utils.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Utility class for Simantics File import functions
*/
public class FileImportService {
+ private static final Logger LOGGER = LoggerFactory.getLogger(FileImportService.class);
+
private FileImportService() {}
public static final String DB_FILE = ".simanticsdb";
serviceReferences = Activator.getContext().getAllServiceReferences(IGenericFileImport.class.getName(),
null);
} catch (InvalidSyntaxException e) {
- e.printStackTrace();
+ LOGGER.error("Could not get service references for IGenericFileImport!", e);
}
if (serviceReferences.length == 0)
return Collections.emptyList();
return extensionsWithFilters;
}
+
+ private static class ConsumerHolder implements Consumer<Throwable> {
+
+ private Throwable throwable;
+
+ @Override
+ public void accept(Throwable t) {
+ throwable = t;
+ }
+
+ public Throwable getThrowable() {
+ return throwable;
+ }
+
+ }
+
+ public static String performFileImport(String base64, String name) throws Throwable {
+ byte[] bytes = Base64.decode(base64);
+ Path file = Activator.getModelsFolder().resolve(name);
+ Files.write(file, bytes);
+
+ ConsumerHolder holder = new ConsumerHolder();
+ String result = performFileImport(file, Optional.of(holder));
+ if (holder.getThrowable() != null)
+ throw holder.getThrowable();
+ return result;
+ }
/**
* Method that performs the import of the given file. This method is called when e.g. {@link FileImportDropins} watcher detects {@link java.nio.file.StandardWatchEventKinds.ENTRY_CREATE} operation
* @param file Path file to be imported
* @param callback Optional callback which can be used to catch Throwables thrown in the import process
*/
- public static void performFileImport(Path file, Optional<Consumer<Throwable>> callback) {
- if (file.getFileName().toString().equals(DB_FILE))
- return;
+ public static String performFileImport(Path file, Optional<Consumer<Throwable>> callback) {
+ if (file.getFileName().toString().equals(DB_FILE)) {
+ return null;
+ }
+ String result = "Import failed";
Optional<IGenericFileImport> serviceOp = findServiceForFileExtension(file);
- serviceOp.ifPresent(service -> {
+ if (serviceOp.isPresent()) {
+ IGenericFileImport service = serviceOp.get();
try {
Optional<String> resource = service.perform(file);
saveResourceForPath(file, resource);
+ result = resource.get();
} catch (Throwable t) {
if (callback.isPresent()) {
callback.get().accept(t);
} else {
- t.printStackTrace();
+ LOGGER.error("Could not import file " + file, t);
}
}
- });
+ } else {
+ LOGGER.warn("Could not find service for importing file " + file);
+ if (callback.isPresent())
+ callback.get().accept(new Exception("Could not find IGenericFileImport service for file " + file));
+ }
+ return result;
}