1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.project.management;
14 import java.io.BufferedInputStream;
15 import java.io.Closeable;
16 import java.io.DataInputStream;
18 import java.io.FileNotFoundException;
19 import java.io.FileOutputStream;
20 import java.io.FilenameFilter;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.UnsupportedEncodingException;
25 import java.net.URLDecoder;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Enumeration;
31 import java.util.Map.Entry;
32 import java.util.Objects;
33 import java.util.concurrent.atomic.AtomicReference;
34 import java.util.function.Supplier;
35 import java.util.jar.Attributes;
36 import java.util.jar.Manifest;
37 import java.util.stream.Collectors;
39 import org.eclipse.core.internal.runtime.PlatformActivator;
40 import org.eclipse.core.runtime.FileLocator;
41 import org.eclipse.core.runtime.Platform;
42 import org.eclipse.equinox.p2.metadata.IVersionedId;
43 import org.eclipse.equinox.p2.metadata.Version;
44 import org.eclipse.equinox.p2.metadata.VersionedId;
45 import org.osgi.framework.Bundle;
46 import org.simantics.databoard.Bindings;
47 import org.simantics.databoard.adapter.AdaptException;
48 import org.simantics.databoard.binding.mutable.Variant;
49 import org.simantics.databoard.container.DataContainer;
50 import org.simantics.databoard.container.DataContainers;
51 import org.simantics.graph.compiler.CompilationResult;
52 import org.simantics.graph.compiler.GraphCompiler;
53 import org.simantics.graph.compiler.GraphCompilerPreferences;
54 import org.simantics.graph.compiler.ValidationMode;
55 import org.simantics.graph.compiler.internal.ltk.FileSource;
56 import org.simantics.graph.compiler.internal.ltk.ISource;
57 import org.simantics.graph.compiler.internal.ltk.Problem;
58 import org.simantics.graph.representation.Extensions;
59 import org.simantics.graph.representation.TransferableGraph1;
60 import org.simantics.graph.representation.TransferableGraphFileReader;
61 import org.simantics.scl.reflection.OntologyVersions;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
66 * This class contains utilities for managing bundles in a active platform.
69 @SuppressWarnings("restriction")
70 public class PlatformUtil {
72 private static final Logger LOGGER = LoggerFactory.getLogger(PlatformUtil.class);
75 * Get all bundles in the platform.
79 public static Bundle[] getBundles() {
80 return PlatformActivator.getContext().getBundles();
84 * Get the manifest file of a bundle
86 * @param bundle bundle
87 * @return manifest or <tt>null</tt> if doesn't not exist
90 public static Manifest getManifest(Bundle bundle) throws IOException {
91 URL url = bundle.getEntry("META-INF/MANIFEST.MF");
92 if (url==null) return null;
93 try (InputStream is = url.openStream()) {
94 return new Manifest(is);
99 * Get the manifest file of a bundle
101 * @param bundle bundle
102 * @return manifest or <tt>null</tt> if doesn't not exist
103 * @throws IOException
105 public static Manifest getSimanticsManifest(Bundle bundle) throws IOException {
106 URL url = bundle.getEntry("META-INF/SIMANTICS.MF");
107 if (url==null) return null;
108 try (InputStream is = url.openStream()) {
109 return new Manifest(is);
114 * Get a list (BundleIds) of all user installable units. These are the
115 * top-level items that are visible for the end-user.
116 * The list is acquired from the bundles of the current application.
118 * @param list of simantics features URIs
119 * @throws IOException
121 public static void getUserInstallableUnits(Collection<String> list)
124 for (Bundle bundle : getBundles()) {
125 Manifest manifest = getSimanticsManifest(bundle);
126 if (manifest==null) continue;
127 Attributes attributes = manifest.getMainAttributes();
128 for (Entry<Object, Object> entry2 : attributes.entrySet()) {
129 Object key = entry2.getKey();
130 if (key.toString().contains("Installable-Unit")) {
131 String bid = entry2.getValue().toString();
139 * Get all transferable graphs in the platform
141 * @param result collection to be filled with transferable graph info
143 public static void getPlatformTGInfos(Collection<TGInfo> result) {
144 for (Bundle bundle : getBundles()) {
145 Enumeration<URL> e = bundle.findEntries("graphs/", "*.tg", false);
146 if (e==null) continue;
147 while (e.hasMoreElements()) {
148 org.osgi.framework.Version osgiVersion = bundle.getVersion();
149 Version p2Version = Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor(), osgiVersion.getMicro(), osgiVersion.getQualifier());
150 String id = bundle.getSymbolicName();
152 TGInfo info = new TGInfo();
153 info.location = e.nextElement();
154 info.bundle = bundle;
155 info.vid = new VersionedId(id, p2Version);
161 private static void uncheckedClose(Closeable closeable) {
163 if (closeable != null)
165 } catch (IOException e) {
170 private static File copyResource(URL url, File targetFile) throws IOException, FileNotFoundException {
171 FileOutputStream os = null;
172 InputStream is = null;
174 if (targetFile.exists())
177 is = url.openStream();
179 byte [] buffer = new byte [16384];
180 os = new FileOutputStream (targetFile);
181 while ((read = is.read (buffer)) != -1) {
182 os.write(buffer, 0, read);
194 private static File extractLib(URL libURL, String libName) throws FileNotFoundException, IOException {
195 String tmpDirStr = System.getProperty("java.io.tmpdir");
196 if (tmpDirStr == null)
197 throw new NullPointerException("java.io.tmpdir property is null");
198 File tmpDir = new File(tmpDirStr);
199 File libFile = new File(tmpDir, libName);
200 return copyResource(libURL, libFile);
203 private static File url2file(URL url, String fileName) {
204 if ("file".equals(url.getProtocol())) {
206 File path = new File(URLDecoder.decode(url.getPath(), "UTF-8"));
208 } catch (UnsupportedEncodingException e) {
209 LOGGER.error("Failed to decode " + url, e);
211 } else if ("jar".equals(url.getProtocol())) {
213 File libFile = extractLib(url, fileName);
215 } catch (FileNotFoundException e) {
216 LOGGER.error("Extraction to " + fileName + " failed, url not found: " + url, e);
217 } catch (IOException e) {
218 LOGGER.error("Extraction to " + fileName + " failed from url " + url, e);
221 LOGGER.error("Unsupported URL protocol '" + url + "' for reading as file '" + fileName + "'");
226 public static Collection<URL> getTGFiles(Bundle b) {
227 Enumeration<URL> enu = b.findEntries("/", "*.tg", false);
229 return Collections.emptyList();
230 if (!enu.hasMoreElements())
231 return Collections.emptyList();
232 ArrayList<URL> result = new ArrayList<>();
233 while (enu.hasMoreElements())
234 result.add(enu.nextElement());
238 public static void compile(Bundle b) throws Exception {
240 Collection<ISource> sources = new ArrayList<>();
241 Collection<TransferableGraph1> dependencies = new ArrayList<>();
243 for (Bundle b2 : getBundles()) {
244 if(b.equals(b2)) continue;
245 for (URL url : getTGFiles(b2)) {
246 File graphFile = url2file(url, b2.toString() + url.toString());
247 dependencies.add(GraphCompiler.read(graphFile));
251 File bundleFile = FileLocator.getBundleFile(b);
252 if(bundleFile.isDirectory()) {
253 File folder = new File(bundleFile, "dynamicGraph");
254 for(File f : folder.listFiles(new FilenameFilter() {
257 public boolean accept(File dir, String name) {
258 return name.endsWith(".pgraph");
262 sources.add(new FileSource(f));
266 // System.out.println("source is " + tmpFile.getAbsolutePath());
268 final StringBuilder errorStringBuilder = new StringBuilder();
269 GraphCompilerPreferences prefs = new GraphCompilerPreferences();
270 prefs.validate = true;
271 prefs.validateRelationRestrictions = ValidationMode.ERROR;
272 prefs.validateResourceHasType = ValidationMode.ERROR;
273 String currentLayer0Version = OntologyVersions.getInstance().currentOntologyVersion("http://www.simantics.org/Layer0-0.0");
274 CompilationResult result = GraphCompiler.compile(currentLayer0Version, sources, dependencies, null, prefs);
276 for(Problem problem : result.getErrors())
277 errorStringBuilder.append(problem.getLocation() + ": " + problem.getDescription() + "\n");
278 for(Problem problem : result.getWarnings())
279 errorStringBuilder.append(problem.getLocation() + ": " + problem.getDescription() + "\n");
281 if(errorStringBuilder.length() > 0) {
282 LOGGER.error(errorStringBuilder.toString());
284 GraphCompiler.write(new File(bundleFile, "graph.tg"), result.getGraph());
290 * Compile all dynamic ontologies in the Platform
293 * @throws IOException
295 public static void compileAllDynamicOntologies() {
296 for (Bundle bundle : getBundles()) {
297 if(bundle.getEntry("dynamicGraph") != null) {
299 File bundleFile = FileLocator.getBundleFile(bundle);
300 if(bundleFile.isDirectory()) {
301 File tg = new File(bundleFile, "graph.tg");
302 long tgLastModified = tg.lastModified();
303 File folder = new File(bundleFile, "dynamicGraph");
304 for(File f : folder.listFiles()) {
305 if(f.isFile() && f.getName().endsWith(".pgraph") && f.lastModified() > tgLastModified) {
311 } catch (Throwable e) {
312 LOGGER.error("Failed to compile dynamic ontologies in bundle " + bundle.getSymbolicName(), e);
319 * Get all graphs in the Platform
322 * @throws IOException
324 public static Collection<GraphBundle> getAllGraphs() throws IOException {
325 AtomicReference<IOException> problem = new AtomicReference<>();
327 Collection<GraphBundle> gbundles = Arrays.stream(getBundles())
328 // #7806: Due to databoard Binding/Serializer construction process thread-unsafety
329 // not even the DataContainer.readHeader invocations can run in parallel, most likely
330 // due to recurring serializer construction for Variant datatypes.
331 // Therefore, we must disable parallel loading for now.
335 return problem.get() == null ? getGraphs(b) : Collections.<GraphBundleEx>emptyList();
336 } catch (IOException e) {
337 if (LOGGER.isWarnEnabled())
338 LOGGER.debug("Could not get graph from bundle {}", b, e);
340 return Collections.<GraphBundleEx>emptyList();
343 .flatMap(Collection::stream)
344 .collect(Collectors.toList());
346 if (problem.get() != null)
354 * @param symbolicName
355 * @return bundle or <tt>null</tt> if there is no bundle or graph
356 * @throws IOException
358 public static GraphBundle getGraph(String symbolicName) throws IOException {
359 Bundle bundle = Platform.getBundle(symbolicName);
360 if (bundle == null) return null;
361 return getGraph( bundle );
364 public static Collection<GraphBundleEx> getGraphs(Bundle bundle) throws IOException {
365 return getTGFiles(bundle).stream()
368 GraphBundleEx result = tryGetOnDemandGraph(bundle, url);
369 return result != null ? result : getCompleteGraph(bundle, url);
370 } catch (IOException e) {
371 if (LOGGER.isWarnEnabled())
372 LOGGER.warn("Could not get graph from bundle url {}", url, e);
376 .filter(Objects::nonNull)
377 .collect(Collectors.toList());
380 private static String tgFileId(Bundle bundle, URL url) {
381 String urlString = url.toString();
382 String file = urlString.substring(urlString.lastIndexOf("/") + 1);
383 return bundle.getSymbolicName() + "_" + file;
387 * Read the graph in a graph bundle. Graph is read from "graph.tg" file in the root.
390 * @return transferable graph, or <tt>null</tt> if there is no graph in the bundle.
391 * @throws IOException
393 public static GraphBundleEx getGraph(Bundle bundle) throws IOException {
394 URL url = bundle.getEntry("graph.tg");
397 GraphBundleEx result = tryGetOnDemandGraph(bundle, url);
398 return result != null ? result : getCompleteGraph(bundle, url);
401 private static GraphBundleEx getCompleteGraph(Bundle bundle, URL url) throws IOException {
403 String id = tgFileId(bundle, url);
404 return new GraphBundleEx(
405 getBundleName(bundle, id),
407 new VersionedId(id, toP2Version(bundle)),
408 isImmutable(bundle));
409 } catch (Exception e) {
410 throw new IOException("Problem loading graph.tg from bundle " + bundle.getSymbolicName(), e);
412 LOGGER.error("Serious problem loading graph.tg from bundle " + bundle.getSymbolicName(), e);
418 * Read the graph in a graph bundle. Graph is read from "graph.tg" file in the root.
421 * @return transferable graph, or <tt>null</tt> if there is no graph in the bundle.
422 * @throws IOException
424 private static GraphBundleEx tryGetOnDemandGraph(Bundle bundle, URL url) throws IOException {
426 Integer cachedHash = readCachedHash(url);
427 if (cachedHash == null) {
428 LOGGER.info("No cached hash for " + bundle);
432 Supplier<TransferableGraph1> graphSource = () -> {
435 } catch (Exception e) {
436 throw new RuntimeException("Problem loading graph.tg from bundle " + bundle.getSymbolicName(), e);
438 LOGGER.error("Serious problem loading graph.tg from bundle " + bundle.getSymbolicName(), e);
443 String id = tgFileId(bundle, url);
445 return new GraphBundleEx(
446 getBundleName(bundle, id),
449 new VersionedId(id, toP2Version(bundle)),
450 isImmutable(bundle));
451 } catch (Exception e) {
452 throw new IOException("Problem loading graph.tg from bundle " + bundle.getSymbolicName(), e);
456 private static TransferableGraph1 readTG(URL url) throws Exception {
457 try (InputStream is = url.openStream()) {
458 return TransferableGraphFileReader.read(is);
462 private static DataContainer readHeader(URL url) throws IOException {
463 try (InputStream is = url.openStream()) {
464 return DataContainers.readHeader(new DataInputStream(new BufferedInputStream(is, 1 << 14)));
468 private static Integer readCachedHash(URL url) throws IOException, AdaptException {
469 DataContainer header = readHeader(url);
470 Variant hashCode = header.metadata.get(Extensions.CACHED_HASHCODE);
471 return hashCode != null ? (Integer) hashCode.getValue(Bindings.INTEGER) : null;
474 private static Version toP2Version(Bundle bundle) {
475 org.osgi.framework.Version osgiVersion = bundle.getVersion();
476 return Version.createOSGi(osgiVersion.getMajor(), osgiVersion.getMinor(), osgiVersion.getMicro(), osgiVersion.getQualifier());
479 private static String getBundleName(Bundle bundle, String id) {
480 String name = (String) bundle.getHeaders().get("Bundle-Name");
481 return name != null ? name : id;
484 private static boolean isImmutable(Bundle bundle) {
485 String immutable = (String) bundle.getHeaders().get("Immutable");
486 return immutable != null ? "true".equals(immutable) : true;
489 public static class TGInfo {
490 public Bundle bundle;
492 public IVersionedId vid;