]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.project/src/org/simantics/project/management/ServerManagerFactory.java
444585bbdc1463265815a479f75179393fb65b03
[simantics/platform.git] / bundles / org.simantics.project / src / org / simantics / project / management / ServerManagerFactory.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.project.management;
13
14 import java.io.File;
15 import java.io.FileOutputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.lang.reflect.InvocationTargetException;
19 import java.lang.reflect.Method;
20 import java.net.URL;
21 import java.net.URLDecoder;
22 import java.util.zip.ZipEntry;
23 import java.util.zip.ZipInputStream;
24
25 import org.simantics.db.DatabaseUserAgent;
26 import org.simantics.db.Driver;
27 import org.simantics.db.Manager;
28 import org.simantics.db.exception.DatabaseException;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 public class ServerManagerFactory {
33     private static final Logger LOGGER = LoggerFactory.getLogger(ServerManagerFactory.class);
34
35     public static ServerManager create(String databaseDriverId, String address) throws IOException, DatabaseException {
36         Driver driver = Manager.getDriver(databaseDriverId);
37         if (driver == null)
38             throw new IllegalArgumentException("Database driver with ID " + databaseDriverId + " could not be found!");
39         LOGGER.info("ServerManagerFactory.create called with id {}, driver is {}.", databaseDriverId, driver);
40         DatabaseUserAgent agent = Manager.getUserAgent(databaseDriverId);
41         if (agent != null)
42             driver.setDatabaseUserAgent(address, agent);
43         return new ServerManager(driver);
44     }
45         /**
46          * Create a server manager in OSGi platform.
47          *
48          * @return
49          * @throws IOException
50          * @throws ClassNotFoundException
51          * @throws RuntimeException unexpected problem with OSGi environment
52          */
53         public static ServerManager createOSGI() throws IOException, RuntimeException {
54                 try {
55                         ClassLoader cl = ServerManager.class.getClassLoader();
56
57                         // Object bundle = Platform.getBundle("org.simantics.db.build");
58                         Class<?> Platform_class = cl.loadClass("org.eclipse.core.runtime.Platform");
59                         Method Platform_getBundle = Platform_class.getMethod("getBundle", String.class);
60                         Object bundle = Platform_getBundle.invoke(null, "org.simantics.db.build");
61                         if (bundle==null) throw new RuntimeException("Bundle org.simantics.db.build not found.");
62
63                         // URL db_build_url = bundle.getEntry("/");
64                         Class<?> Bundle_class = cl.loadClass("org.osgi.framework.Bundle");
65                         Method Bundle_getEntry = Bundle_class.getMethod("getEntry", String.class);
66                         URL db_build_url = (URL) Bundle_getEntry.invoke(bundle, "/");
67
68                 // URL db_build_file_url = FileLocator.toFileURL( db_build_url );
69                         Class<?> FileLocator_class = cl.loadClass("org.eclipse.core.runtime.FileLocator");
70                         Method FileLocator_toFileURL = FileLocator_class.getMethod("toFileURL", URL.class);
71                         URL db_build_file_url = (URL) FileLocator_toFileURL.invoke(null, db_build_url);
72
73                         @SuppressWarnings("unused")
74             String buildFile = URLDecoder.decode(db_build_file_url.getPath(), "UTF-8");
75
76 //              File db_build_file = new File( buildFile );
77                 //return new ServerManager( db_build_file );
78                 throw new RuntimeException("ServerManager.createOSGI not implemented.");
79                 } catch( ClassNotFoundException e ) {
80                         throw new RuntimeException(e);
81                 } catch (SecurityException e) {
82                         throw new RuntimeException(e);
83                 } catch (NoSuchMethodException e) {
84                         throw new RuntimeException(e);
85                 } catch (IllegalArgumentException e) {
86                         throw new RuntimeException(e);
87                 } catch (IllegalAccessException e) {
88                         throw new RuntimeException(e);
89                 } catch (InvocationTargetException e) {
90                         throw new RuntimeException(e.getCause());
91                 }
92         }
93
94         /**
95          * Create a server manager in an POJO environment.
96          *
97          * @return
98          * @throws IOException
99          */
100         public static ServerManager createPOJO() throws IOException {
101                 String tempPath = System.getenv("tmp");
102                 if (tempPath==null) tempPath = "c:/temp/";
103                 File driverDir = new File(tempPath+"/core_drivers");
104                 if (!driverDir.exists()) {
105                         System.out.println("Extracting Core drivers to "+driverDir);
106                         driverDir.mkdirs();
107                         ServerManagerFactory.extractDrivers(driverDir);
108                 } else {
109                         System.out.println("Loading Core drivers from "+driverDir);
110                 }
111                 //return new ServerManager(driverDir);
112         throw new RuntimeException("ServerManager.createPOJO not implemented.");
113         }
114
115     public static ServerManager createPOJO(File driverDir) throws IOException {
116         //return new ServerManager(driverDir);
117         throw new RuntimeException("ServerManager.createPOJO not implemented.");
118     }
119
120     static ServerManager cached;
121
122     public static boolean isOSGi() {
123         try {
124                 ServerManager.class.getClassLoader().loadClass("org.osgi.framework.Bundle");
125                 return true;
126         } catch (ClassNotFoundException e) {
127                 return false;
128         }
129     }
130
131     public synchronized static ServerManager getServerManager() {
132         if (cached!=null) return cached;
133         try {
134                 try {
135                         return createOSGI();
136                 } catch(RuntimeException e) {
137                         return createPOJO();
138                 }
139         } catch (IOException e) {
140                 throw new RuntimeException(e);
141         }
142     }
143
144
145     /**
146      * Extracts drivers files to a location.
147      *
148      * @param path location where to extract application files
149      * @throws IOException
150      */
151         public static void extractDrivers(File path)
152         throws IOException
153         {
154                 // Extract org.simantics.db.build.zip to workspace
155                 InputStream is = ServerManager.class.getResource("org.simantics.db.build.zip").openStream();
156                 try {
157                         extractZip(is, path);
158                 } finally {
159                         is.close();
160                 }
161         }
162
163     /**
164      * Extract a zip file into a directory
165      *
166      * @param zipInput
167      * @param dst directory
168      * @throws IOException
169      */
170     private static void extractZip(InputStream zipInput, File dst) throws IOException {
171         byte[] buf = new byte[8192];
172         ZipInputStream zis = new ZipInputStream(zipInput);
173         ZipEntry entry;
174
175         entry = zis.getNextEntry();
176         while (entry != null) {
177             // for each entry to be extracted
178             String name = entry.getName();
179             LOGGER.debug("Extracting "+name);
180             File file = new File(dst, name);
181
182             if (entry.isDirectory())
183             {
184                 if ( !file.exists() ) file.mkdirs();
185             } else {
186                 File parent = file.getParentFile();
187                 if (!parent.exists()) parent.mkdirs();
188                 if (!file.exists()) file.createNewFile();
189
190                 FileOutputStream fileoutputstream = new FileOutputStream(file);
191                 try {
192                     int n = 0;
193                     while ((n = zis.read(buf, 0, buf.length)) > -1)
194                         fileoutputstream.write(buf, 0, n);
195                 } finally {
196                     fileoutputstream.close();
197                 }
198             }
199
200             zis.closeEntry();
201             entry = zis.getNextEntry();
202         }// while
203
204         zis.close();
205     }
206
207
208 }
209