1 package org.simantics.document.ui.graphfile;
3 import java.io.BufferedReader;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.io.PrintStream;
9 import java.util.Collection;
10 import java.util.HashSet;
13 import org.eclipse.core.runtime.IProgressMonitor;
14 import org.simantics.Simantics;
15 import org.simantics.db.ReadGraph;
16 import org.simantics.db.Resource;
17 import org.simantics.db.WriteGraph;
18 import org.simantics.db.common.request.ReadRequest;
19 import org.simantics.db.common.request.WriteRequest;
20 import org.simantics.db.common.request.WriteResultRequest;
21 import org.simantics.db.exception.DatabaseException;
22 import org.simantics.document.DocumentResource;
23 import org.simantics.graphfile.ontology.GraphFileResource;
24 import org.simantics.graphfile.util.GraphFileUtil;
25 import org.simantics.layer0.Layer0;
26 import org.simantics.utils.ui.ExceptionUtils;
30 * @author Marko Luukkainen <marko.luukkainen@vtt.fi>
33 public class FileDocumentUtil {
36 * Imports file, sets its L0.hasName, and and adds it to a library
38 * Note: if library relation is L0.ConsistsOf, L0.HasName is set to next available unique name.
43 * @throws DatabaseException
45 public static Resource importFile(final String fileName, final Resource lib, final Resource rel) throws DatabaseException {
46 return Simantics.getSession().syncRequest(new WriteResultRequest<Resource>() {
48 public Resource perform(WriteGraph graph) throws DatabaseException {
49 return importFile(graph, fileName,lib,rel);
56 public static void importFileAsync(final String fileName, final Resource lib, final Resource rel) {
57 Simantics.getSession().asyncRequest(new WriteRequest() {
60 public void perform(WriteGraph graph) throws DatabaseException {
61 importFile(graph, fileName,lib,rel);
66 ExceptionUtils.logAndShowError("Cannot import file " + fileName, e);
73 * Imports file, sets its L0.HasName, and and adds it to a library
75 * Note: if library relation is L0.ConsistsOf, L0.HasName is set to next available unique name.
81 * @throws DatabaseException
83 public static Resource importFile(WriteGraph graph, String fileName, Resource lib, Resource rel) throws DatabaseException{
84 Layer0 l0 = Layer0.getInstance(graph);
85 Resource fileResource = importFile(graph, fileName);
86 graph.claim(lib, rel, fileResource);
87 File file = new File(fileName);
88 String name = file.getName();
89 graph.claimLiteral(fileResource, l0.HasName, name);
90 setUniqueName(graph, fileResource, lib, rel);
94 public static Resource importFileWithName(WriteGraph graph, String fileName) throws DatabaseException{
95 Layer0 l0 = Layer0.getInstance(graph);
96 Resource fileResource = importFile(graph, fileName);
97 File file = new File(fileName);
98 String name = file.getName();
99 graph.claimLiteral(fileResource, l0.HasName, name);
104 * Imports folder of documents recursively (including all sub folders).
106 * @param folderName Name of imported folder
107 * @param lib Library, where imported folder is attached.
108 * @param folderType Type of folders
109 * @param relation Relation used to create file/folder hierarchy
110 * @return the imported folder
111 * @throws DatabaseException
113 public static Resource importFolderWithName(WriteGraph graph, String folderName, Resource lib, Resource folderType, Resource relation, IProgressMonitor monitor) throws Exception{
114 Resource folderRes = importFolderWithName(graph, folderName, folderType, relation,monitor);
115 graph.claim(lib, relation, folderRes);
116 FileDocumentUtil.createUniqueName(graph, folderRes);
121 * Imports folder of documents recursively (including all sub folders).
123 * @param folderName Name of imported folder
124 * @param folderType Type of folders
125 * @param relation Relation used to create file/folder hierarchy
126 * @param monitor ProgessMonitor or null
127 * @return the imported folder
128 * @throws DatabaseException
130 public static Resource importFolderWithName(WriteGraph graph, String folderName, Resource folderType, Resource relation, IProgressMonitor monitor) throws Exception{
131 Layer0 l0 = Layer0.getInstance(graph);
132 File folder = new File(folderName);
133 Resource rootFolderRes = graph.newResource();
134 graph.claim(rootFolderRes, l0.InstanceOf, folderType);
135 graph.claimLiteral(rootFolderRes, l0.HasName, folder.getName());
136 importFolder(graph, folder, rootFolderRes, relation, monitor);
137 return rootFolderRes;
141 * Imports folder of documents recursively (including all sub folders).
143 * @param folder Imported folder
144 * @param folderResource Resource folder matching file system folder
145 * @param relation Relation used to create file/folder hierarchy
146 * @throws DatabaseException
148 public static void importFolder(WriteGraph graph, File folder, Resource folderResource, Resource relation, IProgressMonitor monitor) throws Exception{
149 if (monitor != null) {
150 int count = _countFiles(folder);
151 monitor.beginTask("Import files", count);
153 _importFolder(graph, folder, folderResource, relation, monitor);
158 private static void _importFolder(WriteGraph graph, File folder, Resource folderResource, Resource relation, IProgressMonitor monitor) throws Exception{
159 Layer0 l0 = Layer0.getInstance(graph);
160 File files[] = folder.listFiles();
161 for (File f : files) {
162 if (f.isDirectory()) {
163 Resource newFolderRes = graph.newResource();
164 graph.claim(newFolderRes, l0.InstanceOf, graph.getSingleType(folderResource));
165 graph.claim(folderResource, relation, newFolderRes);
166 graph.claimLiteral(newFolderRes, l0.HasName, f.getName());
167 _importFolder(graph, f, newFolderRes, relation,monitor);
169 Resource fileRes = null;
172 fileRes = importURL(graph, f);
173 fileRes = importFileWithName(graph, f.getAbsolutePath());
175 graph.claim(folderResource, relation, fileRes);
182 private static int _countFiles(File folder) {
185 File files[] = folder.listFiles();
186 for (File f : files) {
187 if (f.isDirectory()) {
188 count += _countFiles(f);
197 public static void createUniqueName(WriteGraph graph, Resource document) throws DatabaseException {
198 Layer0 l0 = Layer0.getInstance(graph);
199 Resource lib = graph.getPossibleObject(document, l0.PartOf);
202 setUniqueName(graph, document, lib, l0.ConsistsOf);
205 public static void setUniqueName(WriteGraph graph, Resource res, Resource lib, Resource rel) throws DatabaseException{
206 Layer0 l0 = Layer0.getInstance(graph);
207 Set<String> names = new HashSet<String>();
208 for (Resource r : graph.getObjects(lib, rel)) {
211 names.add((String)graph.getRelatedValue(r, l0.HasName));
213 String name = graph.getRelatedValue(res, l0.HasName);
214 if (!names.contains(name))
218 String proposal = name +" (" + i +")";
219 if (!names.contains(proposal)) {
220 graph.claimLiteral(res, l0.HasName, proposal);
234 * @throws DatabaseException
236 public static Resource importFile(WriteGraph graph, String fileName) throws DatabaseException{
237 Layer0 l0 = Layer0.getInstance(graph);
238 DocumentResource doc = DocumentResource.getInstance(graph);
240 Resource fileResource = graph.newResource();
241 graph.claim(fileResource, l0.InstanceOf, doc.FileDocument);
243 GraphFileUtil.toGraph(graph,fileName, fileResource);
245 } catch (IOException e) {
246 throw new DatabaseException(e);
253 * Exports graph folder recursively to file system.
255 * @param folderResource
258 * @throws DatabaseException
260 public static void exportDocumentFolder(final Resource folderResource, final File folder, final Resource relation, boolean useResourceNames, final IProgressMonitor monitor) throws Exception{
261 Simantics.getSession().syncRequest(new ReadRequest() {
264 public void run(ReadGraph graph) throws DatabaseException {
266 exportDocumentFolder(graph, folderResource, folder, relation, useResourceNames, monitor);
267 } catch (Exception e) {
268 throw new DatabaseException(e);
277 * Exports graph folder recursively to file system.
279 * @param folderResource
282 * @throws DatabaseException
284 public static void exportDocumentFolder(ReadGraph graph, Resource folderResource, File folder, Resource relation, boolean useResourceNames, IProgressMonitor monitor) throws Exception{
285 Layer0 l0 = Layer0.getInstance(graph);
286 DocumentResource doc = DocumentResource.getInstance(graph);
287 GraphFileResource gf = GraphFileResource.getInstance(graph);
288 Set<String> names = new HashSet<String>();
289 Collection<Resource> folderType = graph.getPrincipalTypes(folderResource);
290 for (Resource r : graph.getObjects(folderResource, relation)) {
291 if (graph.isInstanceOf(r, doc.Document)) {
293 boolean canExport = false;
294 if (graph.isInstanceOf(r, doc.FileDocument)) {
295 name = graph.getRelatedValue(r, useResourceNames ? gf.HasResourceName : l0.HasName);
297 } else if (graph.isInstanceOf(r, doc.UrlDocument)) {
298 name = graph.getRelatedValue(r, l0.HasName) +".url";
302 name = resolveName(folder, name, names, true);
303 File file = new File(folder.getAbsolutePath()+"/"+name);
304 if (graph.isInstanceOf(r, doc.FileDocument)) {
305 GraphFileUtil.writeDataToFile(graph,r, file);
306 } else if (graph.isInstanceOf(r, doc.UrlDocument)) {
307 String url = graph.getRelatedValue(r, doc.HasUrl);
308 String n = graph.getRelatedValue(r, l0.HasName);
309 exportUrl(file, n, url);
316 Collection<Resource> type = graph.getPrincipalTypes(r);
317 if (type.size() == folderType.size() && folderType.containsAll(type)) {
318 String name = graph.getRelatedValue(r, l0.HasName);
319 name = resolveName(folder, name, names, false);
320 File subFolder = new File(folder.getAbsolutePath()+"/"+name);
321 if (!subFolder.exists()) {
322 if (!subFolder.mkdir()) {
327 exportDocumentFolder(graph, r, subFolder, relation, useResourceNames, monitor);
334 * Print URL to a file (Windows specific format?)
337 * @throws DatabaseException
339 private static void exportUrl(File toFile, String name, String url) throws Exception{
340 PrintStream os = new PrintStream(toFile,"UTF-8");
341 os.println("[InternetShortcut]");
342 os.println("URL="+url);
343 os.println("name="+name);
348 public static Resource importURL(WriteGraph graph, File file) throws Exception{
352 BufferedReader is = null;
354 is = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
355 while ((s = is.readLine()) != null) {
356 if (s.startsWith("URL=")) {
357 url = s.substring(4);
358 } else if (s.startsWith("name=")) {
359 name = s.substring(5);
370 Layer0 l0 = Layer0.getInstance(graph);
371 DocumentResource doc = DocumentResource.getInstance(graph);
373 Resource fileResource = graph.newResource();
374 graph.claim(fileResource, l0.InstanceOf, doc.UrlDocument);
376 name = file.getName();
377 name = unescape(name);
378 name = name.substring(0,name.length()-4);
380 graph.claimLiteral(fileResource, l0.HasName, name);
381 graph.claimLiteral(fileResource, doc.HasUrl, url);
385 private static boolean isUrl(File file) throws Exception{
386 return (file.getAbsolutePath().endsWith(".url"));
389 private static final char ESCAPE = '%';
391 private static String escape(String s) {
393 int len = s.length();
394 StringBuilder sb = new StringBuilder(len);
395 for (int i = 0; i < len; i++) {
396 char ch = s.charAt(i);
397 if (ch < ' ' || ch >= 0x7F || ch == '/' || ch == '\\' || ch == ':' || ch == ESCAPE) {
402 sb.append(Integer.toHexString(ch));
407 return sb.toString();
410 private static String unescape(String s) {
411 int len = s.length();
412 StringBuilder sb = new StringBuilder(len);
413 for (int i = 0; i < len; i++) {
414 char ch = s.charAt(i);
417 num += s.charAt(++i);
418 num += s.charAt(++i);
419 ch = (char)Integer.decode(num).intValue();
423 return sb.toString();
427 private static String resolveName(File parentFolder, String proposal, Set<String> used, boolean file) {
428 String current = escape(proposal);
433 if (used.contains(current)) {
434 current = createFileName(proposal, i);
436 File subFile = new File(parentFolder.getAbsolutePath()+"/"+current);
437 if (!subFile.exists())
439 if (subFile.exists() && subFile.isFile() && subFile.canWrite()) {
447 if (used.contains(current)) {
448 current = proposal+i;
450 File subFolder = new File(parentFolder.getAbsolutePath()+"/"+current);
451 if (!subFolder.exists())
453 if (subFolder.exists() && subFolder.isDirectory()) {
463 private static String createFileName(String original, int i) {
464 int extIndex = original.lastIndexOf(".");
467 return original.substring(0,extIndex) + i + original.substring(extIndex);