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