1 package org.simantics.document;
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.graphfile.ontology.GraphFileResource;
23 import org.simantics.graphfile.util.GraphFileUtil;
24 import org.simantics.layer0.Layer0;
25 import org.simantics.utils.ui.ExceptionUtils;
29 * @author Marko Luukkainen <marko.luukkainen@vtt.fi>
32 public class FileDocumentUtil {
35 * Imports file, sets its L0.hasName, and and adds it to a library
37 * Note: if library relation is L0.ConsistsOf, L0.HasName is set to next available unique name.
42 * @throws DatabaseException
44 public static Resource importFile(final String fileName, final Resource lib, final Resource rel) throws DatabaseException {
45 return Simantics.getSession().syncRequest(new WriteResultRequest<Resource>() {
47 public Resource perform(WriteGraph graph) throws DatabaseException {
48 return importFile(graph, fileName,lib,rel);
55 public static void importFileAsync(final String fileName, final Resource lib, final Resource rel) {
56 Simantics.getSession().asyncRequest(new WriteRequest() {
59 public void perform(WriteGraph graph) throws DatabaseException {
60 importFile(graph, fileName,lib,rel);
63 },new org.simantics.utils.datastructures.Callback<DatabaseException>() {
66 public void run(DatabaseException parameter) {
67 if (parameter != null)
68 ExceptionUtils.logAndShowError("Cannot import file " + fileName, parameter);
77 * Imports file, sets its L0.HasName, and and adds it to a library
79 * Note: if library relation is L0.ConsistsOf, L0.HasName is set to next available unique name.
85 * @throws DatabaseException
87 public static Resource importFile(WriteGraph graph, String fileName, Resource lib, Resource rel) throws DatabaseException{
88 Layer0 l0 = Layer0.getInstance(graph);
89 Resource fileResource = importFile(graph, fileName);
90 graph.claim(lib, rel, fileResource);
91 File file = new File(fileName);
92 String name = file.getName();
93 graph.claimLiteral(fileResource, l0.HasName, name);
94 setUniqueName(graph, fileResource, lib, rel);
98 public static Resource importFileWithName(WriteGraph graph, String fileName) throws DatabaseException{
99 Layer0 l0 = Layer0.getInstance(graph);
100 Resource fileResource = importFile(graph, fileName);
101 File file = new File(fileName);
102 String name = file.getName();
103 graph.claimLiteral(fileResource, l0.HasName, name);
108 * Imports folder of documents recursively (including all sub folders).
110 * @param folderName Name of imported folder
111 * @param lib Library, where imported folder is attached.
112 * @param folderType Type of folders
113 * @param relation Relation used to create file/folder hierarchy
114 * @return the imported folder
115 * @throws DatabaseException
117 public static Resource importFolderWithName(WriteGraph graph, String folderName, Resource lib, Resource folderType, Resource relation, IProgressMonitor monitor) throws Exception{
118 Resource folderRes = importFolderWithName(graph, folderName, folderType, relation,monitor);
119 graph.claim(lib, relation, folderRes);
120 FileDocumentUtil.createUniqueName(graph, folderRes);
125 * Imports folder of documents recursively (including all sub folders).
127 * @param folderName Name of imported folder
128 * @param folderType Type of folders
129 * @param relation Relation used to create file/folder hierarchy
130 * @param monitor ProgessMonitor or null
131 * @return the imported folder
132 * @throws DatabaseException
134 public static Resource importFolderWithName(WriteGraph graph, String folderName, Resource folderType, Resource relation, IProgressMonitor monitor) throws Exception{
135 Layer0 l0 = Layer0.getInstance(graph);
136 File folder = new File(folderName);
137 Resource rootFolderRes = graph.newResource();
138 graph.claim(rootFolderRes, l0.InstanceOf, folderType);
139 graph.claimLiteral(rootFolderRes, l0.HasName, folder.getName());
140 importFolder(graph, folder, rootFolderRes, relation, monitor);
141 return rootFolderRes;
145 * Imports folder of documents recursively (including all sub folders).
147 * @param folder Imported folder
148 * @param folderResource Resource folder matching file system folder
149 * @param relation Relation used to create file/folder hierarchy
150 * @throws DatabaseException
152 public static void importFolder(WriteGraph graph, File folder, Resource folderResource, Resource relation, IProgressMonitor monitor) throws Exception{
153 if (monitor != null) {
154 int count = _countFiles(folder);
155 monitor.beginTask("Import files", count);
157 _importFolder(graph, folder, folderResource, relation, monitor);
162 private static void _importFolder(WriteGraph graph, File folder, Resource folderResource, Resource relation, IProgressMonitor monitor) throws Exception{
163 Layer0 l0 = Layer0.getInstance(graph);
164 File files[] = folder.listFiles();
165 for (File f : files) {
166 if (f.isDirectory()) {
167 Resource newFolderRes = graph.newResource();
168 graph.claim(newFolderRes, l0.InstanceOf, graph.getSingleType(folderResource));
169 graph.claim(folderResource, relation, newFolderRes);
170 graph.claimLiteral(newFolderRes, l0.HasName, f.getName());
171 _importFolder(graph, f, newFolderRes, relation,monitor);
173 Resource fileRes = null;
176 fileRes = importURL(graph, f);
177 fileRes = importFileWithName(graph, f.getAbsolutePath());
179 graph.claim(folderResource, relation, fileRes);
186 private static int _countFiles(File folder) {
189 File files[] = folder.listFiles();
190 for (File f : files) {
191 if (f.isDirectory()) {
192 count += _countFiles(f);
201 public static void createUniqueName(WriteGraph graph, Resource document) throws DatabaseException {
202 Layer0 l0 = Layer0.getInstance(graph);
203 Resource lib = graph.getPossibleObject(document, l0.PartOf);
206 setUniqueName(graph, document, lib, l0.ConsistsOf);
209 public static void setUniqueName(WriteGraph graph, Resource res, Resource lib, Resource rel) throws DatabaseException{
210 Layer0 l0 = Layer0.getInstance(graph);
211 Set<String> names = new HashSet<String>();
212 for (Resource r : graph.getObjects(lib, rel)) {
215 names.add((String)graph.getRelatedValue(r, l0.HasName));
217 String name = graph.getRelatedValue(res, l0.HasName);
218 if (!names.contains(name))
222 String proposal = name +" (" + i +")";
223 if (!names.contains(proposal)) {
224 graph.claimLiteral(res, l0.HasName, proposal);
238 * @throws DatabaseException
240 public static Resource importFile(WriteGraph graph, String fileName) throws DatabaseException{
241 Layer0 l0 = Layer0.getInstance(graph);
242 DocumentResource doc = DocumentResource.getInstance(graph);
244 Resource fileResource = graph.newResource();
245 graph.claim(fileResource, l0.InstanceOf, doc.FileDocument);
247 GraphFileUtil.toGraph(graph,fileName, fileResource);
249 } catch (IOException e) {
250 throw new DatabaseException(e);
257 * Exports graph folder recursively to file system.
259 * @param folderResource
262 * @throws DatabaseException
264 public static void exportDocumentFolder(final Resource folderResource, final File folder, final Resource relation, boolean useResourceNames, final IProgressMonitor monitor) throws Exception{
265 Simantics.getSession().syncRequest(new ReadRequest() {
268 public void run(ReadGraph graph) throws DatabaseException {
270 exportDocumentFolder(graph, folderResource, folder, relation, useResourceNames, monitor);
271 } catch (Exception e) {
272 throw new DatabaseException(e);
281 * Exports graph folder recursively to file system.
283 * @param folderResource
286 * @throws DatabaseException
288 public static void exportDocumentFolder(ReadGraph graph, Resource folderResource, File folder, Resource relation, boolean useResourceNames, IProgressMonitor monitor) throws Exception{
289 Layer0 l0 = Layer0.getInstance(graph);
290 DocumentResource doc = DocumentResource.getInstance(graph);
291 GraphFileResource gf = GraphFileResource.getInstance(graph);
292 Set<String> names = new HashSet<String>();
293 Collection<Resource> folderType = graph.getPrincipalTypes(folderResource);
294 for (Resource r : graph.getObjects(folderResource, relation)) {
295 if (graph.isInstanceOf(r, doc.Document)) {
297 boolean canExport = false;
298 if (graph.isInstanceOf(r, doc.FileDocument)) {
299 name = graph.getRelatedValue(r, useResourceNames ? gf.HasResourceName : l0.HasName);
301 } else if (graph.isInstanceOf(r, doc.UrlDocument)) {
302 name = graph.getRelatedValue(r, l0.HasName) +".url";
306 name = resolveName(folder, name, names, true);
307 File file = new File(folder.getAbsolutePath()+"/"+name);
308 if (graph.isInstanceOf(r, doc.FileDocument)) {
309 GraphFileUtil.writeDataToFile(graph,r, file);
310 } else if (graph.isInstanceOf(r, doc.UrlDocument)) {
311 String url = graph.getRelatedValue(r, doc.HasUrl);
312 String n = graph.getRelatedValue(r, l0.HasName);
313 exportUrl(file, n, url);
320 Collection<Resource> type = graph.getPrincipalTypes(r);
321 if (type.size() == folderType.size() && folderType.containsAll(type)) {
322 String name = graph.getRelatedValue(r, l0.HasName);
323 name = resolveName(folder, name, names, false);
324 File subFolder = new File(folder.getAbsolutePath()+"/"+name);
325 if (!subFolder.exists()) {
326 if (!subFolder.mkdir()) {
331 exportDocumentFolder(graph, r, subFolder, relation, useResourceNames, monitor);
338 * Print URL to a file (Windows specific format?)
341 * @throws DatabaseException
343 private static void exportUrl(File toFile, String name, String url) throws Exception{
344 PrintStream os = new PrintStream(toFile,"UTF-8");
345 os.println("[InternetShortcut]");
346 os.println("URL="+url);
347 os.println("name="+name);
352 public static Resource importURL(WriteGraph graph, File file) throws Exception{
356 BufferedReader is = null;
358 is = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
359 while ((s = is.readLine()) != null) {
360 if (s.startsWith("URL=")) {
361 url = s.substring(4);
362 } else if (s.startsWith("name=")) {
363 name = s.substring(5);
374 Layer0 l0 = Layer0.getInstance(graph);
375 DocumentResource doc = DocumentResource.getInstance(graph);
377 Resource fileResource = graph.newResource();
378 graph.claim(fileResource, l0.InstanceOf, doc.UrlDocument);
380 name = file.getName();
381 name = unescape(name);
382 name = name.substring(0,name.length()-4);
384 graph.claimLiteral(fileResource, l0.HasName, name);
385 graph.claimLiteral(fileResource, doc.HasUrl, url);
389 private static boolean isUrl(File file) throws Exception{
390 return (file.getAbsolutePath().endsWith(".url"));
393 private static final char ESCAPE = '%';
395 private static String escape(String s) {
397 int len = s.length();
398 StringBuilder sb = new StringBuilder(len);
399 for (int i = 0; i < len; i++) {
400 char ch = s.charAt(i);
401 if (ch < ' ' || ch >= 0x7F || ch == '/' || ch == '\\' || ch == ':' || ch == ESCAPE) {
406 sb.append(Integer.toHexString(ch));
411 return sb.toString();
414 private static String unescape(String s) {
415 int len = s.length();
416 StringBuilder sb = new StringBuilder(len);
417 for (int i = 0; i < len; i++) {
418 char ch = s.charAt(i);
421 num += s.charAt(++i);
422 num += s.charAt(++i);
423 ch = (char)Integer.decode(num).intValue();
427 return sb.toString();
431 private static String resolveName(File parentFolder, String proposal, Set<String> used, boolean file) {
432 String current = escape(proposal);
437 if (used.contains(current)) {
438 current = createFileName(proposal, i);
440 File subFile = new File(parentFolder.getAbsolutePath()+"/"+current);
441 if (!subFile.exists())
443 if (subFile.exists() && subFile.isFile() && subFile.canWrite()) {
451 if (used.contains(current)) {
452 current = proposal+i;
454 File subFolder = new File(parentFolder.getAbsolutePath()+"/"+current);
455 if (!subFolder.exists())
457 if (subFolder.exists() && subFolder.isDirectory()) {
467 private static String createFileName(String original, int i) {
468 int extIndex = original.lastIndexOf(".");
471 return original.substring(0,extIndex) + i + original.substring(extIndex);