From: Tuukka Lehtonen Date: Wed, 21 Aug 2019 09:49:28 +0000 (+0000) Subject: Merge "Initialize new cache in flush instead of setting it null" X-Git-Tag: v1.43.0~136^2~106 X-Git-Url: https://gerrit.simantics.org/r/gitweb?p=simantics%2Fplatform.git;a=commitdiff_plain;h=c00d1429bda8dc27461e1576f4be028b43149758;hp=3672d0143a9bdf4bc620bac25c92f20ce85fab92 Merge "Initialize new cache in flush instead of setting it null" --- diff --git a/bundles/org.simantics.action.ontology/graph/Action.pgraph b/bundles/org.simantics.action.ontology/graph/Action.pgraph index 3b0cb14c0..11205dacc 100644 --- a/bundles/org.simantics.action.ontology/graph/Action.pgraph +++ b/bundles/org.simantics.action.ontology/graph/Action.pgraph @@ -4,6 +4,6 @@ ACT = : L0.Ontology @L0.new L0.HasResourceClass "org.simantics.action.ontology.ActionResource" -ACT.Action Binding mapping. + */ + bindingRepository.registerClassMapping(Datatype.class, DATATYPE); } } diff --git a/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/factory/BindingRepository.java b/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/factory/BindingRepository.java index ba2435371..5a0239f26 100644 --- a/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/factory/BindingRepository.java +++ b/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/factory/BindingRepository.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2018 Association for Decentralized Information Management in + * Copyright (c) 2007, 2019 Association for Decentralized Information Management in * Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -8,7 +8,7 @@ * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation - * Semantum Oy - gitlab #82 + * Semantum Oy - gitlab #82, gitlab #313 *******************************************************************************/ package org.simantics.databoard.binding.factory; @@ -18,10 +18,12 @@ import java.util.Map.Entry; import org.simantics.databoard.binding.Binding; import org.simantics.databoard.binding.reflection.BindingRequest; -import org.simantics.databoard.type.Datatype; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class BindingRepository { - + + private static final Logger LOGGER = LoggerFactory.getLogger(BindingRepository.class); /** * This map contains all the bindings */ @@ -41,7 +43,7 @@ public class BindingRepository { this.requestMap = requests; for (Entry e : requests.entrySet()) { if ( isClassRequest( e.getKey() ) ) { - classMap.put(e.getKey().getClazz(), e.getValue()); + registerClassMapping(e.getKey().getClazz(), e.getValue()); } } } @@ -76,11 +78,15 @@ public class BindingRepository { */ public synchronized void put( BindingRequest request, Binding binding ) { if ( isClassRequest(request) ) { - classMap.put( request.getClazz(), binding ); + registerClassMapping(request.getClazz(), binding); + } + Binding existing = requestMap.put( request, binding ); + if (existing != null && !existing.equals(binding)) { + LOGGER.error("Replacing existing binding with a different one! {} {} {}", request, binding, existing); } - requestMap.put( request, binding ); } - + + @SuppressWarnings("unlikely-arg-type") public synchronized void remove(Binding binding) { for (Entry e : requestMap.entrySet()) { if (e.getValue() == binding) { @@ -116,20 +122,15 @@ public class BindingRepository { classMap.clear(); } - /** - * {@link Datatype} class has annotations but it can be considered a "class - * request" as it is a fundamental building block of Databoard and it has a - * fixed structure. Therefore {@link #classMap} is allowed to contain a cached - * Datatype.class -> Binding mapping. - */ - private static final String DATATYPE_CLASS_NAME = Datatype.class.getName(); + boolean isClassRequest(BindingRequest request) { + return (request.className != null && (request.annotations == null || request.annotations.length == 0)); + } - boolean isClassRequest( BindingRequest request ) - { - return (request.className != null - && ((request.annotations==null || request.annotations.length==0) - || DATATYPE_CLASS_NAME.equals(request.className)) - ); + public void registerClassMapping(Class clazz, Binding binding) { + Binding previous = classMap.putIfAbsent(clazz, binding); + if (previous != null) { + LOGGER.warn("WARN: Can not put same key again to classMap! {} mapping {} not replaced by {}", clazz, previous, binding); + } } } diff --git a/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/reflection/BindingRequest.java b/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/reflection/BindingRequest.java index 51feb39c3..55f809f51 100644 --- a/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/reflection/BindingRequest.java +++ b/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/reflection/BindingRequest.java @@ -8,12 +8,13 @@ * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation - * Semantum Oy - gitlab #82 + * Semantum Oy - gitlab #82, gitlab #313 *******************************************************************************/ package org.simantics.databoard.binding.reflection; import java.lang.annotation.Annotation; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -44,6 +45,13 @@ public class BindingRequest { return new BindingRequest(fieldClass, annotations); } + public static BindingRequest create( Method method ) + { + Annotation[] annotations = ClassBindingFactory.getMethodAnnotations(method); + Class valueClass = method.getReturnType(); + return new BindingRequest(valueClass, annotations); + } + /** Requested class */ private Class clazz; private ClassLoader cl; @@ -60,6 +68,23 @@ public class BindingRequest { transient int hash; + /** + * Cloning constructor with replacement annotations. + * + * @param other the request to clone + * @param annotations the annotations to use while cloning + */ + private BindingRequest(BindingRequest other, Annotation...annotations) + { + this.clazz = other.clazz; + this.cl = other.cl; + this.annotations = annotations; + this.className = other.className; + this.signature = other.signature; + this.descriptor = other.descriptor; + hash = calcHash(clazz.getName()); + } + /** * Create BindingRequest that creates class lazily. * @@ -76,10 +101,7 @@ public class BindingRequest { this.signature = classSignature; this.annotations = annotations; this.descriptor = classDescriptor; - hash = className.hashCode(); - for (Annotation a : annotations) { - hash = 7*hash + a.hashCode(); - } + hash = calcHash(className); } /** @@ -114,17 +136,23 @@ public class BindingRequest { className = clazz.getCanonicalName(); signature = getSignature(clazz); - List> args = createArgsList(); - StringBuilder desc = new StringBuilder(); - _buildDescriptor(desc, clazz, args, new MutableInteger(0)); - descriptor = desc.toString(); - hash = clazz.getName().hashCode(); - for (Annotation a : annotations) { - hash = 7*hash + a.hashCode(); + descriptor = _buildDescriptor(new StringBuilder(), clazz, createArgsList(), new MutableInteger(0)).toString(); + hash = calcHash(clazz.getName()); + } + + public BindingRequest withAnnotations(Annotation... newAnnotations) { + return new BindingRequest(this, newAnnotations); + } + + private int calcHash(String className) { + int hash = className.hashCode(); + for (Annotation a : this.annotations) { + hash += a.hashCode(); } + return hash; } - - private void _buildDescriptor(StringBuilder sb, Class c, List> classes, MutableInteger pos) + + private StringBuilder _buildDescriptor(StringBuilder sb, Class c, List> classes, MutableInteger pos) { int genericCount = c.getTypeParameters().length; int genericsLeft = classes.size()-pos.value; @@ -142,6 +170,7 @@ public class BindingRequest { } else { sb.append( getSignature(c) ); } + return sb; } public BindingRequest(Class clazz, List annotations) diff --git a/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/reflection/ClassBindingFactory.java b/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/reflection/ClassBindingFactory.java index 8d29ad70c..ac860d392 100644 --- a/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/reflection/ClassBindingFactory.java +++ b/bundles/org.simantics.databoard/src/org/simantics/databoard/binding/reflection/ClassBindingFactory.java @@ -1,3 +1,15 @@ +/******************************************************************************* + * Copyright (c) 2019 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + * Semantum Oy - gitlab #313 + *******************************************************************************/ package org.simantics.databoard.binding.reflection; import java.lang.annotation.Annotation; @@ -6,6 +18,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; @@ -200,8 +213,7 @@ public class ClassBindingFactory { if(request.hasAnnotation(Optional.class)) { Optional optional = request.getAnnotation(Optional.class); - Annotation[] newAnnotations = ArrayUtils.dropElements(request.annotations, optional); - BindingRequest componentRequest = new BindingRequest(request.getClazz(), newAnnotations); + BindingRequest componentRequest = request.withAnnotations(ArrayUtils.dropElements(request.annotations, optional)); OptionalType type = new OptionalType(); OptionalBinding binding = new OptionalBindingDefault(type, null); inprogress.put(request, binding); @@ -209,6 +221,7 @@ public class ClassBindingFactory { type.componentType = binding.componentBinding.type(); inprogress.remove(request); + repository.put(request, binding); return binding; } @@ -570,7 +583,7 @@ public class ClassBindingFactory { Identifier idAnnotation = componentRequest.getAnnotation( Identifier.class ); if ( idAnnotation!=null ) { - componentRequest.dropAnnotations(1, idAnnotation); + componentRequest = componentRequest.withAnnotations(componentRequest.dropAnnotations(1, idAnnotation)); identifierIndices.add( i ); } Binding componentBinding = componentBindings[i] = construct( componentRequest ); @@ -602,8 +615,6 @@ public class ClassBindingFactory { binding = defaultBinding; } - repository.put(request, binding); - return binding; } catch (RangeException e) { inprogress.remove( request ); @@ -719,7 +730,23 @@ public class ClassBindingFactory { Class fieldClass = list.remove(0); Class[] parameterClasses = list.isEmpty() ? NO_CLASSES : list.toArray( NO_CLASSES ); - if (Set.class.isAssignableFrom(fieldClass) && parameterClasses!=null &¶meterClasses.length==1) { + return getTypeAnnotations(annotations, fieldClass, parameterClasses); + } + + public static Annotation[] getMethodAnnotations(Method method) + { + Annotation[] annotations = method.getAnnotations().clone(); + ArrayList> list = new ArrayList>(); + getTypes( method.getGenericReturnType(), list ); + Class valueClass = list.remove(0); + Class[] parameterClasses = list.isEmpty() ? NO_CLASSES : list.toArray( NO_CLASSES ); + + return getTypeAnnotations(annotations, valueClass, parameterClasses); + } + + private static Annotation[] getTypeAnnotations(Annotation[] annotations, Class fieldClass, + Class[] parameterClasses) { + if (Set.class.isAssignableFrom(fieldClass) && parameterClasses!=null &¶meterClasses.length==1) { Annotation[] a2 = new Annotation[annotations.length+1]; System.arraycopy(annotations, 0, a2, 0, annotations.length); diff --git a/bundles/org.simantics.db.common/META-INF/MANIFEST.MF b/bundles/org.simantics.db.common/META-INF/MANIFEST.MF index c45b276d7..27e433851 100644 --- a/bundles/org.simantics.db.common/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.db.common/META-INF/MANIFEST.MF @@ -15,7 +15,9 @@ Require-Bundle: org.simantics.db;bundle-version="1.1.0";visibility:=reexport, org.simantics.user.ontology;bundle-version="1.0.0", org.simantics.layer0x.ontology;bundle-version="1.0.0", org.simantics.issues.ontology;bundle-version="1.2.0", - org.slf4j.api + org.slf4j.api, + org.simantics.db.management;bundle-version="1.1.0", + org.simantics.scl.osgi Export-Package: org.simantics.db.common, org.simantics.db.common.adaption, org.simantics.db.common.auth, diff --git a/bundles/org.simantics.db.common/src/org/simantics/db/common/SimanticsInternal.java b/bundles/org.simantics.db.common/src/org/simantics/db/common/SimanticsInternal.java new file mode 100644 index 000000000..e59e36ffa --- /dev/null +++ b/bundles/org.simantics.db.common/src/org/simantics/db/common/SimanticsInternal.java @@ -0,0 +1,157 @@ +/******************************************************************************* + * Copyright (c) 2007, 2010 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * VTT Technical Research Centre of Finland - initial API and implementation + *******************************************************************************/ +package org.simantics.db.common; + +import java.util.concurrent.TimeUnit; + +import org.simantics.db.Session; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.management.ISessionContext; +import org.simantics.db.management.ISessionContextProvider; +import org.simantics.db.management.ISessionContextProviderSource; +import org.simantics.db.request.ReadInterface; +import org.simantics.db.request.WriteInterface; +import org.simantics.layer0.Layer0; +import org.simantics.operation.Layer0X; +import org.simantics.utils.threads.ThreadUtils; + +/** + * An internal facade for accessing basic Simantics platform services. + * Usable without a graphical UI, i.e. in headless contexts. + * + * Use org.simantics.Simantics instead where ever possible. + */ +public class SimanticsInternal { + + private static ISessionContextProviderSource providerSource = null; + + /** + * Queue execution of a runnable. + * + * @param runnable + */ + public static void async(Runnable runnable) { + ThreadUtils.getBlockingWorkExecutor().execute(runnable); + } + + public static void async(Runnable runnable, int delay, TimeUnit unit) { + ThreadUtils.getTimer().schedule(runnable, delay, unit); + } + + /** + * Queue execution of a non-blocking runnable. Use this method with caution. + * A non-blocking runnable nevers locks anything, No Locks, No semaphores, + * No Object.wait(), No synchronized() {} blocks. + * + * @param runnable a non-blocking runnable + */ + public static void asyncNonblocking(Runnable runnable) { + ThreadUtils.getNonBlockingWorkExecutor().execute(runnable); + } + + /** + * Schedule execution of a non-blocking runnable. Use this method with caution. + * A non-blocking runnable never locks anything, No Locks, No semaphores, + * No Object,wait(), No synchronized() {} blocks. + * + * @param runnable a non-blocking runnable + * @param initialDelay + * @param period + */ + public static void asyncNonblocking(Runnable runnable, int initialDelay, int period) { + ThreadUtils.getNonBlockingWorkExecutor().scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.MILLISECONDS); + } + + public static synchronized ISessionContext setSessionContext(ISessionContext ctx) { + return getSessionContextProvider().setSessionContext(ctx); + } + + public static void setSessionContextProviderSource(ISessionContextProviderSource source) { + if (source == null) + throw new IllegalArgumentException("null provider source"); + providerSource = source; + } + + public static ISessionContextProviderSource getProviderSource() { + if (providerSource == null) + throw new IllegalStateException( + "providerSource must be initialized by the application before using class Simantics"); + return providerSource; + } + + public static ISessionContextProvider getSessionContextProvider() { + return getProviderSource().getActive(); + } + + /** + * Returns the database session context associated with the currently active + * context. This method should be used to retrieve session contexts only + * when the client is sure that the correct context is active. + * + * @return the session context associated with the currently active context + * or null if the context has no session context + */ + public static ISessionContext getSessionContext() { + ISessionContextProvider provider = getSessionContextProvider(); + return provider != null ? provider.getSessionContext() : null; + } + + /** + * Returns the database Session bound to the currently active context. + * + *

+ * The method always returns a non-null Session or produces an + * IllegalStateException if a Session was not attainable. + *

+ * + * @return the Session bound to the currently active workbench window + * @throws IllegalStateException if no Session was available + */ + public static Session getSession() { + ISessionContext ctx = getSessionContext(); + if (ctx == null) + throw new IllegalStateException("Session unavailable, no database session open"); + return ctx.getSession(); + } + + /** + * Returns the database Session bound to the currently active context. + * Differently from {@link #getSession()}, this method returns + * null if there is no current Session available. + * + * @see #getSession() + * @return the Session bound to the currently active context or + * null + */ + public static Session peekSession() { + ISessionContext ctx = getSessionContext(); + return ctx == null ? null : ctx.peekSession(); + } + + public static Layer0 getLayer0() throws DatabaseException { + return Layer0.getInstance(getSession()); + } + + public static Layer0X getLayer0X() throws DatabaseException { + return Layer0X.getInstance(getSession()); + } + + + public static T sync(ReadInterface r) throws DatabaseException { + return getSession().sync(r); + } + + public static T sync(WriteInterface r) throws DatabaseException { + return getSession().sync(r); + } + +} diff --git a/bundles/org.simantics.db.common/src/org/simantics/db/common/request/RuntimeEnvironmentRequest.java b/bundles/org.simantics.db.common/src/org/simantics/db/common/request/RuntimeEnvironmentRequest.java new file mode 100644 index 000000000..24a5c10c9 --- /dev/null +++ b/bundles/org.simantics.db.common/src/org/simantics/db/common/request/RuntimeEnvironmentRequest.java @@ -0,0 +1,153 @@ +package org.simantics.db.common.request; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.common.SimanticsInternal; +import org.simantics.db.common.utils.CommonDBUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.procedure.Listener; +import org.simantics.db.request.Read; +import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification; +import org.simantics.scl.compiler.module.repository.ImportFailureException; +import org.simantics.scl.compiler.module.repository.UpdateListener; +import org.simantics.scl.compiler.runtime.RuntimeEnvironment; +import org.simantics.scl.osgi.SCLOsgi; +import org.simantics.scl.runtime.SCLContext; + +/** + * Finds the runtime environment of a model or other index root. + * + * @author Hannu Niemistö + * @author Antti Villberg + */ +public class RuntimeEnvironmentRequest extends UnaryRead { + + public RuntimeEnvironmentRequest(Resource parameter) { + super(parameter); + } + + protected void fillEnvironmentSpecification(EnvironmentSpecification environmentSpecification) { + } + + static class UpdateListenerImpl extends UpdateListener { + + final EnvironmentSpecification environmentSpecification; + final Listener callback; + + UpdateListenerImpl(EnvironmentSpecification environmentSpecification, Listener callback) { + this.environmentSpecification = environmentSpecification; + this.callback = callback; + } + + @Override + public void notifyAboutUpdate() { + if(callback.isDisposed()) { + stopListening(); + return; + } + getRuntimeEnvironment(environmentSpecification, callback, this); + } + }; + + public static void getRuntimeEnvironment(EnvironmentSpecification environmentSpecification, Listener callback, UpdateListenerImpl listener) { + + try { + + SCLContext context = SCLContext.getCurrent(); + + RuntimeEnvironment env; + Object graph = context.get("graph"); + if(graph == null) + try { + env = SimanticsInternal.getSession().syncRequest(new Read() { + @Override + public RuntimeEnvironment perform(ReadGraph graph) throws DatabaseException { + + SCLContext sclContext = SCLContext.getCurrent(); + Object oldGraph = sclContext.get("graph"); + try { + sclContext.put("graph", graph); + return SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment( + environmentSpecification, + callback.getClass().getClassLoader(), listener); + } catch (ImportFailureException e) { + throw new DatabaseException(e); + } catch (Throwable t) { + throw new DatabaseException(t); + } finally { + sclContext.put("graph", oldGraph); + } + } + }); + } catch (DatabaseException e) { + callback.exception(e); + return; + } + else + env = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment( + environmentSpecification, + callback.getClass().getClassLoader(), listener); + callback.execute(env); + } catch (ImportFailureException e) { + callback.exception(new DatabaseException(e)); + } + + } + + @Override + public RuntimeEnvironment perform(ReadGraph graph) + throws DatabaseException { + final EnvironmentSpecification environmentSpecification = EnvironmentSpecification.of( + "Builtin", "", + "StandardLibrary", "", + "Simantics/All", ""); + fillEnvironmentSpecification(environmentSpecification); + + Resource mainModule = CommonDBUtils.getPossibleChild(graph, parameter, "SCLMain"); + String mainModuleUri; + if(mainModule != null) { + mainModuleUri = graph.getURI(mainModule); + environmentSpecification.importModule(mainModuleUri, ""); + } + else + mainModuleUri = graph.getURI(parameter) + "/#"; // Add something dummy to the model uri that cannot be in a real URI + + return graph.syncRequest(new ParametrizedPrimitiveRead(mainModuleUri) { + + UpdateListenerImpl sclListener; + + @Override + public void register(ReadGraph graph, Listener procedure) { + + SCLContext context = SCLContext.getCurrent(); + Object oldGraph = context.put("graph", graph); + try { + + if(procedure.isDisposed()) { + getRuntimeEnvironment(environmentSpecification, procedure, null); + } else { + sclListener = new UpdateListenerImpl(environmentSpecification, procedure); + sclListener.notifyAboutUpdate(); + } + + } finally { + context.put("graph", oldGraph); + } + + } + + @Override + public void unregistered() { + if(sclListener != null) + sclListener.stopListening(); + } + + }); + } + + @Override + public int hashCode() { + return 31*getClass().hashCode() + super.hashCode(); + } + +} diff --git a/bundles/org.simantics.db.common/src/org/simantics/db/common/utils/CommonDBUtils.java b/bundles/org.simantics.db.common/src/org/simantics/db/common/utils/CommonDBUtils.java index a07d42519..dcd3939a4 100644 --- a/bundles/org.simantics.db.common/src/org/simantics/db/common/utils/CommonDBUtils.java +++ b/bundles/org.simantics.db.common/src/org/simantics/db/common/utils/CommonDBUtils.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; @@ -16,8 +15,10 @@ import org.simantics.db.WriteGraph; import org.simantics.db.common.procedure.adapter.DirectStatementProcedure; import org.simantics.db.common.request.IsParent; import org.simantics.db.common.request.ObjectsWithType; +import org.simantics.db.common.request.PossibleChild; import org.simantics.db.common.request.PossibleObjectWithType; import org.simantics.db.common.request.PossibleOwner; +import org.simantics.db.common.request.RuntimeEnvironmentRequest; import org.simantics.db.exception.DatabaseException; import org.simantics.db.exception.InvalidResourceReferenceException; import org.simantics.db.service.ClusterUID; @@ -26,6 +27,10 @@ import org.simantics.db.service.DirectQuerySupport; import org.simantics.db.service.SerialisationSupport; import org.simantics.db.service.XSupport; import org.simantics.layer0.Layer0; +import org.simantics.scl.compiler.environment.Environments; +import org.simantics.scl.compiler.runtime.RuntimeEnvironment; +import org.simantics.scl.compiler.top.SCLExpressionCompilationException; +import org.simantics.scl.compiler.types.Type; import org.simantics.utils.datastructures.collections.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -313,5 +318,32 @@ public class CommonDBUtils { return xs.isClusterLoaded(clusterUID); } + public static Type getSCLType(ReadGraph graph, RuntimeEnvironment runtimeEnvironment, String typeText) throws DatabaseException { + try { + return Environments.getType(runtimeEnvironment.getEnvironment(), typeText); + } catch (SCLExpressionCompilationException e) { + throw new DatabaseException(e); + } + } + + public static Type getSCLType(ReadGraph graph, Resource resource, String typeText) throws DatabaseException { + try { + RuntimeEnvironment runtimeEnvironment = graph.syncRequest(new RuntimeEnvironmentRequest(resource)); + return Environments.getType(runtimeEnvironment.getEnvironment(), typeText); + } catch (SCLExpressionCompilationException e) { + throw new DatabaseException(e); + } + } + + public static Resource getPossibleChild(ReadGraph graph, Resource resource, String name) throws DatabaseException { + return graph.sync(new PossibleChild(resource, name)); + } + + public static Resource getPossibleChild(ReadGraph graph, Resource resource, Resource type, String name) throws DatabaseException { + Resource child = graph.sync(new PossibleChild(resource, name)); + if(child == null) return null; + if(!graph.isInstanceOf(child, type)) return null; + return child; + } } diff --git a/bundles/org.simantics.db.common/src/org/simantics/db/common/utils/ListUtils.java b/bundles/org.simantics.db.common/src/org/simantics/db/common/utils/ListUtils.java index a197de880..656dfeb27 100644 --- a/bundles/org.simantics.db.common/src/org/simantics/db/common/utils/ListUtils.java +++ b/bundles/org.simantics.db.common/src/org/simantics/db/common/utils/ListUtils.java @@ -55,9 +55,14 @@ public class ListUtils { */ public static Resource create(WriteGraph g, Iterable elements) throws DatabaseException { Layer0 L0 = Layer0.getInstance(g); - return ListUtils.create(g,L0.List, L0.List_ElementWithInverse, L0.List_ElementWithInverse_Inverse, elements); + return ListUtils.create(g,L0.List, L0.List_Element, null, elements); } - + + public static Resource createWithInverses(WriteGraph g, Iterable elements) throws DatabaseException { + Layer0 L0 = Layer0.getInstance(g); + return ListUtils.create(g,L0.ListWithInverses, L0.List_ElementWithInverse, L0.List_ElementWithInverse_Inverse, elements); + } + /** * Creates a list of the given list type containing the given {@code elements}. */ @@ -85,6 +90,8 @@ public class ListUtils { Layer0 L0 = g.getService(Layer0.class); Resource list = g.newResource(); g.claim(list, L0.InstanceOf, null, type); + if (!elementPredicate.equals(L0.List_Element)) + g.claim(list, L0.List_ElementPredicate, L0.List_ElementPredicate_Inverse, elementPredicate); createExisting(g, list, elementPredicate, elementPredicateInverse, elements); return list; } diff --git a/bundles/org.simantics.db.common/src/org/simantics/db/common/validation/L0Validations.java b/bundles/org.simantics.db.common/src/org/simantics/db/common/validation/L0Validations.java index a1ed10e77..99ef91b7a 100644 --- a/bundles/org.simantics.db.common/src/org/simantics/db/common/validation/L0Validations.java +++ b/bundles/org.simantics.db.common/src/org/simantics/db/common/validation/L0Validations.java @@ -3,41 +3,50 @@ package org.simantics.db.common.validation; import org.simantics.databoard.Bindings; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; +import org.simantics.db.common.utils.CommonDBUtils; import org.simantics.db.common.utils.NameUtils; import org.simantics.db.exception.DatabaseException; import org.simantics.layer0.Layer0; +import org.simantics.scl.compiler.types.Type; public class L0Validations { public static String checkValueType(ReadGraph graph, Resource subject, Resource predicate) throws DatabaseException { + if (subject == null) return null; if (predicate == null) return null; Layer0 L0 = Layer0.getInstance(graph); - if(graph.isSubrelationOf(predicate, L0.HasProperty)) { + if(graph.isSubrelationOf(predicate, L0.HasProperty)) { Resource object = graph.getPossibleObject(subject, predicate); if(object == null) return null; - String valueType = graph.getPossibleRelatedValue(predicate, L0.RequiresValueType, Bindings.STRING); - if(valueType != null) { - String valueType2 = graph.getPossibleRelatedValue(object, L0.HasValueType, Bindings.STRING); - if(!valueType.equals(valueType2)) { - StringBuilder sb = new StringBuilder() - .append("The value type ") - .append(valueType) - .append(" of predicate ") - .append(NameUtils.getSafeName(graph, predicate, true)) - .append(" does not match the value type ") - .append(valueType2) - .append(" of object ") - .append(NameUtils.getSafeName(graph, object, true)) - .append("."); - return sb.toString(); - } - } - } - return null; + String valueTypeText = graph.getPossibleRelatedValue(predicate, L0.RequiresValueType, Bindings.STRING); + if(valueTypeText != null) { + Type valueType = CommonDBUtils.getSCLType(graph, subject, valueTypeText); + String valueTypeText2 = graph.getPossibleRelatedValue(object, L0.HasValueType, Bindings.STRING); + if(valueTypeText2 != null) { + Type valueType2 = CommonDBUtils.getSCLType(graph, subject, valueTypeText2); + if(!valueType.equals(valueType2)) { + StringBuilder sb = new StringBuilder() + .append("The value type ") + .append(valueType) + .append(" of predicate ") + .append(NameUtils.getSafeName(graph, predicate, true)) + .append(" does not match the value type ") + .append(valueType2) + .append(" of object ") + .append(NameUtils.getSafeName(graph, object, true)) + .append("."); + return sb.toString(); + } + } + } + } + + return null; + } } diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/DebugPolicy.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/DebugPolicy.java deleted file mode 100644 index 752991c48..000000000 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/DebugPolicy.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.simantics.db.impl; - - -/** - * @author Antti Villberg - */ -public final class DebugPolicy { - - public static final boolean QUERY_STATE = false; - - public static final boolean PERFORM = false; - - public static final boolean DEPENDENCIES = false; - - public static final boolean RECOMPUTE = false; - - public static final boolean CHANGES = false; - - public static final boolean LISTENER = false; - - public static final boolean SCHEDULE = false; - - public static final boolean COLLECT = false; - - public static final boolean VERBOSE = false; - -} diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/ResourceImpl.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/ResourceImpl.java index 3406d6700..78dacb98f 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/ResourceImpl.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/ResourceImpl.java @@ -11,6 +11,7 @@ *******************************************************************************/ package org.simantics.db.impl; +import org.simantics.db.DevelopmentKeys; import org.simantics.db.Resource; import org.simantics.db.impl.support.ResourceSupport; import org.simantics.db.service.ClusterUID; @@ -84,7 +85,7 @@ final public class ResourceImpl implements Resource { StringBuilder sb = new StringBuilder(32); try { long rid = getResourceId(); - if(DebugPolicy.VERBOSE) { + if(DevelopmentKeys.VERBOSE) { sb.append("[id="); sb.append(id); sb.append(" - rid="); @@ -111,7 +112,7 @@ final public class ResourceImpl implements Resource { public String toString(ClusterSupport support) { StringBuilder sb = new StringBuilder(32); long rid = getResourceId(); - if (DebugPolicy.VERBOSE) { + if (DevelopmentKeys.VERBOSE) { sb.append("[id="); sb.append(id); sb.append(" - rid="); diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/DelayedWriteGraph.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/DelayedWriteGraph.java index f8797b251..84dd871c0 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/DelayedWriteGraph.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/DelayedWriteGraph.java @@ -36,6 +36,7 @@ import org.simantics.databoard.binding.error.BindingConstructionException; import org.simantics.databoard.serialization.Serializer; import org.simantics.databoard.type.Datatype; import org.simantics.databoard.util.binary.RandomAccessBinary; +import org.simantics.db.DevelopmentKeys; import org.simantics.db.Metadata; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; @@ -54,7 +55,6 @@ import org.simantics.db.exception.ManyObjectsForFunctionalRelationException; import org.simantics.db.exception.NoSingleResultException; import org.simantics.db.exception.ResourceNotFoundException; import org.simantics.db.exception.ServiceException; -import org.simantics.db.impl.DebugPolicy; import org.simantics.db.impl.ResourceImpl; import org.simantics.db.request.DelayedWrite; import org.simantics.db.request.WriteOnly; @@ -199,7 +199,7 @@ public class DelayedWriteGraph extends ReadGraphImpl implements WriteGraph, Byte @Override public String toString() { StringBuilder sb = new StringBuilder(32); - if(DebugPolicy.VERBOSE) { + if(DevelopmentKeys.VERBOSE) { sb.append("[delayed id="); sb.append(id); sb.append("]"); diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/ReadGraphImpl.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/ReadGraphImpl.java index 79fe97464..cffbba51c 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/ReadGraphImpl.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/ReadGraphImpl.java @@ -6181,11 +6181,12 @@ public class ReadGraphImpl implements AsyncReadGraph { @Override public T getRelatedValue2(Resource subject, Resource relation, Object context) throws DatabaseException { if(Development.DEVELOPMENT) { - String error = L0Validations.checkValueType(this, subject, relation); - if(error != null) { - Logger.defaultLogError(new ValidationException(error)); - //throw new ValidationException(error); - new ValidationException(error).printStackTrace(); + if(Development.getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) { + String error = L0Validations.checkValueType(this, subject, relation); + if(error != null) { + Logger.defaultLogError(new ValidationException(error)); + throw new ValidationException(error); + } } } return getValue2(getSingleObject(subject, relation), context); @@ -6194,12 +6195,13 @@ public class ReadGraphImpl implements AsyncReadGraph { @Override public Variant getRelatedVariantValue2(Resource subject, Resource relation, Object context) throws DatabaseException { if(Development.DEVELOPMENT) { - String error = L0Validations.checkValueType(this, subject, relation); - if(error != null) { - Logger.defaultLogError(new ValidationException(error)); - //throw new ValidationException(error); - new ValidationException(error).printStackTrace(); - } + if(Development.getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) { + String error = L0Validations.checkValueType(this, subject, relation); + if(error != null) { + Logger.defaultLogError(new ValidationException(error)); + throw new ValidationException(error); + } + } } return getVariantValue2(getSingleObject(subject, relation), context); } diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncMultiReadEntry.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncMultiReadEntry.java index bc3cf0a4f..ea88d1791 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncMultiReadEntry.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncMultiReadEntry.java @@ -27,26 +27,26 @@ final public class AsyncMultiReadEntry extends CacheEntryBase request; + protected AsyncMultiRead id; AsyncMultiReadEntry(AsyncMultiRead request) { - this.request = request; + this.id = request; } @Override int makeHash() { - return request.hashCode(); + return id.hashCode(); } @Override public Object getOriginalRequest() { - return request; + return id; } @Override public void discard() { super.discard(); - request = null; + id = null; setResult(null); } @@ -111,9 +111,9 @@ final public class AsyncMultiReadEntry extends CacheEntryBase extends CacheEntryBase extends CacheEntryBase procedure) throws DatabaseException { - return graph.processor.cache.performQuery(graph, request, this, procedure); + return graph.processor.cache.performQuery(graph, id, this, procedure); } } diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncReadEntry.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncReadEntry.java index 972bd381f..72582ee60 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncReadEntry.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncReadEntry.java @@ -11,16 +11,18 @@ *******************************************************************************/ package org.simantics.db.impl.query; +import org.simantics.databoard.Bindings; import org.simantics.db.AsyncReadGraph; +import org.simantics.db.DevelopmentKeys; import org.simantics.db.exception.DatabaseException; import org.simantics.db.impl.BlockingAsyncProcedure; -import org.simantics.db.impl.DebugPolicy; import org.simantics.db.impl.graph.AsyncBarrierImpl; import org.simantics.db.impl.graph.BarrierTracing; import org.simantics.db.impl.graph.ReadGraphImpl; import org.simantics.db.impl.query.QueryProcessor.SessionTask; import org.simantics.db.procedure.AsyncProcedure; import org.simantics.db.request.AsyncRead; +import org.simantics.utils.Development; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,22 +30,25 @@ final public class AsyncReadEntry extends CacheEntryBase> i private static final Logger LOGGER = LoggerFactory.getLogger(AsyncReadEntry.class); - protected AsyncRead request; + protected AsyncRead id; AsyncReadEntry(AsyncRead request) { - this.request = request; - if (DebugPolicy.QUERY_STATE) - System.out.println("[QUERY STATE]: created " + this); + this.id = request; + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) { + System.err.println("[QUERY STATE]: created " + this); + } + } } @Override int makeHash() { - return request.hashCode(); + return id.hashCode(); } @Override public Object getOriginalRequest() { - return request; + return id; } @Override @@ -85,9 +90,9 @@ final public class AsyncReadEntry extends CacheEntryBase> i except(t); } - }, request); + }, id); - request.perform(graph, proc); + id.perform(graph, proc); proc.get(); @@ -104,17 +109,17 @@ final public class AsyncReadEntry extends CacheEntryBase> i @Override public int type() { - return request.getFlags(); + return id.getFlags(); } @Override public String toString() { - if (request == null) + if (id == null) return "DISCARDED"; else if (isExcepted()) - return request.toString() + " " + getResult(); + return id.toString() + " " + getResult(); else - return request.toString() + " " + statusOrException; + return id.toString() + " " + statusOrException; } }; @@ -237,11 +242,11 @@ final public class AsyncReadEntry extends CacheEntryBase> i @Override public String toString() { if (isDiscarded()) - return "DISCARDED " + request.toString(); + return "DISCARDED " + id.toString(); else if (isExcepted()) - return request.toString() + " " + getResult(); + return id.toString() + " " + getResult(); else - return request.toString() + " " + statusOrException; + return id.toString() + " " + statusOrException; } @Override diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntry.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntry.java index 848925622..1cdcbde9d 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntry.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntry.java @@ -29,7 +29,7 @@ public abstract class CacheEntry { abstract void setReady(); abstract void refute(); - abstract void setPending(); + abstract void setPending(QuerySupport querySupport); abstract void discard(); abstract void except(Throwable t); abstract void clearResult(QuerySupport support); diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntryBase.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntryBase.java index 7fc0432f8..e79f99dea 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntryBase.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntryBase.java @@ -14,10 +14,12 @@ package org.simantics.db.impl.query; import java.util.ArrayList; import java.util.Iterator; +import org.simantics.databoard.Bindings; +import org.simantics.db.DevelopmentKeys; import org.simantics.db.exception.DatabaseException; -import org.simantics.db.impl.DebugPolicy; import org.simantics.db.impl.graph.ReadGraphImpl; import org.simantics.db.impl.procedure.InternalProcedure; +import org.simantics.utils.Development; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -85,7 +87,11 @@ public abstract class CacheEntryBase extends CacheEntry { @Override public void discard() { - if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: discarded " + this); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) { + System.err.println("[QUERY STATE]: discarded " + this); + } + } statusOrException = DISCARDED; } @@ -96,7 +102,11 @@ public abstract class CacheEntryBase extends CacheEntry { @Override final public void refute() { - if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: refuted " + this); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) { + System.err.println("[QUERY STATE]: refuted " + this); + } + } statusOrException = REQUIRES_COMPUTATION; } @@ -107,7 +117,11 @@ public abstract class CacheEntryBase extends CacheEntry { @Override public void except(Throwable throwable) { - if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: excepted " + this); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) { + System.err.println("[QUERY STATE]: excepted " + this); + } + } if(statusOrException != DISCARDED) { statusOrException = EXCEPTED; result = throwable; @@ -131,8 +145,9 @@ public abstract class CacheEntryBase extends CacheEntry { } @Override - public void setPending() { - statusOrException = PENDING; + public void setPending(QuerySupport querySupport) { + statusOrException = PENDING; + clearResult(querySupport); } @Override @@ -425,8 +440,7 @@ public abstract class CacheEntryBase extends CacheEntry { @Override void prepareRecompute(QuerySupport querySupport) { - setPending(); - clearResult(querySupport); + setPending(querySupport); } @Override diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CodeGen.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CodeGen.java index 8661428cb..66ee865a6 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CodeGen.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CodeGen.java @@ -11,203 +11,246 @@ import org.simantics.utils.FileUtils; public class CodeGen { - int indent = 4; - - String[] signatureR1RelationInfo = { "int r", "r", "keyR", "long", "InternalProcedure", "entry.id" }; - String[] signatureR1Bytes = { "int r", "r", "keyR", "long", "InternalProcedure", "entry.id" }; - String[] signatureR1IntSet = { "int r", "r", "keyR", "long", "InternalProcedure", "entry.id" }; - String[] signatureR1IP = { "int r", "r", "keyR", "long", "IntProcedure", "entry.id" }; - String[] signatureR2IP = { "int r1, int r2", "r1,r2", "keyR2", "long", "IntProcedure", "entry.id" }; - String[] signatureR2TIP = { "int r1, int r2", "r1,r2", "keyR2", "long", "TripleIntProcedure", "entry.id" }; - String[] signatureID1 = { "String id", "id", "keyID", "String", "InternalProcedure", "entry.id" }; - String[] signatureID2 = { "String id", "id", "keyID", "String", "InternalProcedure>", "entry.id" }; - String[] signatureChildMap = { "int r", "r", "keyR", "long", "InternalProcedure>", "entry.id" }; - String[] signatureRead = { "Read r", "r", "id", "long", "AsyncProcedure", "entry.request" }; - String[] signatureAsyncRead = { "AsyncRead r", "r", "id", "long", "AsyncProcedure", "entry.request" }; - String[] signatureMultiRead = { "MultiRead r", "r", "id", "long", "SyncMultiProcedure", "entry.request" }; - String[] signatureAsyncMultiRead = { "AsyncMultiRead r", "r", "id", "long", "AsyncMultiProcedure", "entry.request" }; - String[] signatureExternalRead = { "ExternalRead r", "r", "id", "long", "AsyncProcedure", "entry.request" }; - - private void line(StringBuilder content, String line) { - for(int i=0;i", "", false ); + GenerationInfo signatureR1Bytes = new GenerationInfo ( "int r", "r", "keyR", "long", "InternalProcedure", "", false ); + GenerationInfo signatureR1IntSet = new GenerationInfo ( "int r", "r", "keyR", "long", "InternalProcedure", "", false ); + GenerationInfo signatureR1IP = new GenerationInfo ( "int r", "r", "keyR", "long", "IntProcedure", "", false ); + GenerationInfo signatureR2IP = new GenerationInfo ( "int r1, int r2", "r1,r2", "keyR2", "long", "IntProcedure", "", false ); + GenerationInfo signatureR2TIP = new GenerationInfo ( "int r1, int r2", "r1,r2", "keyR2", "long", "TripleIntProcedure", "", false ); + GenerationInfo signatureID1 = new GenerationInfo ( "String id", "id", "keyID", "String", "InternalProcedure", "", false ); + GenerationInfo signatureID2 = new GenerationInfo ( "String id", "id", "keyID", "String", "InternalProcedure>", "", false ); + GenerationInfo signatureChildMap = new GenerationInfo ( "int r", "r", "keyR", "long", "InternalProcedure>", "", false ); + GenerationInfo signatureRead = new GenerationInfo ( "Read r", "r", "id", "long", "AsyncProcedure", "", true ); + GenerationInfo signatureAsyncRead = new GenerationInfo ( "AsyncRead r", "r", "id", "long", "AsyncProcedure", "", true ); + GenerationInfo signatureMultiRead = new GenerationInfo ( "MultiRead r", "r", "id", "long", "SyncMultiProcedure", "", false ); + GenerationInfo signatureAsyncMultiRead = new GenerationInfo ( "AsyncMultiRead r", "r", "id", "long", "AsyncMultiProcedure", "", false ); + GenerationInfo signatureExternalRead = new GenerationInfo ( "ExternalRead r", "r", "id", "long", "AsyncProcedure", ", graph", false ); + + private void line(StringBuilder content, String line) { + for(int i=0;i extends CacheEntryBase> implements Listener { final LinkedList items = new LinkedList(); - protected ExternalRead request; + protected ExternalRead id; protected ReadGraphImpl graph; protected boolean registered = false; @Override int makeHash() { - return request.hashCode(); + return id.hashCode(); } @Override public Object getOriginalRequest() { - return request; + return id; } @Override @@ -45,14 +47,14 @@ final public class ExternalReadEntry extends CacheEntryBase @Override public void discard() { - request.unregistered(); - request = null; + id.unregistered(); + id = null; graph = null; super.discard(); } @Override - public void setPending() { + public void setPending(QuerySupport querySupport) { //if(result != NO_RESULT) { //new Exception("result = " + result).printStackTrace(); //} @@ -62,14 +64,19 @@ final public class ExternalReadEntry extends CacheEntryBase public ExternalReadEntry(ExternalRead request, ReadGraphImpl graph) { assert request != null; - this.request = request; + this.id = request; this.graph = graph; } @Override public void except(Throwable t) { - if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: excepted " + this); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) { + System.err.println("[QUERY STATE]: excepted " + this); + } + } + if(statusOrException != DISCARDED) { statusOrException = EXCEPTED; result = t; @@ -112,7 +119,7 @@ final public class ExternalReadEntry extends CacheEntryBase } // Reschedule if(!items.isEmpty()) { - graph.processor.updatePrimitive(request); + graph.processor.updatePrimitive(id); } } @@ -131,8 +138,8 @@ final public class ExternalReadEntry extends CacheEntryBase @Override public String toString() { - if(request == null) return "DISCARDED ExternalRead"; - else return request.toString(); + if(id == null) return "DISCARDED ExternalRead"; + else return id.toString(); } }; @@ -141,8 +148,8 @@ final public class ExternalReadEntry extends CacheEntryBase @Override public String toString() { - if(request == null) return "DISCARDED ExternalRead " + System.identityHashCode(this); - else return request.toString() + " " + + System.identityHashCode(this); + if(id == null) return "DISCARDED ExternalRead " + System.identityHashCode(this); + else return id.toString() + " " + + System.identityHashCode(this); } @Override @@ -176,11 +183,11 @@ final public class ExternalReadEntry extends CacheEntryBase ReadGraphImpl queryGraph = graph.withParent(this); if(!registered) { - request.register(graph, this); + id.register(graph, this); registered = true; } - queryGraph.asyncBarrier.waitBarrier(request, graph); + queryGraph.asyncBarrier.waitBarrier(id, graph); } catch (Throwable t) { @@ -206,7 +213,7 @@ final public class ExternalReadEntry extends CacheEntryBase synchronized(items) { items.addLast(result); - graph.processor.updatePrimitive(request); + graph.processor.updatePrimitive(id); // TODO: implement flags/logic in ExternalRead to state that all but the latest request result can be evaporated // In some cases where data is produced really fast this might be necessary but currently this queueing will do. } diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/MultiReadEntry.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/MultiReadEntry.java index 6b7415c97..77e3b8d0f 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/MultiReadEntry.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/MultiReadEntry.java @@ -29,26 +29,26 @@ public final class MultiReadEntry extends CacheEntryBase request; + protected MultiRead id; MultiReadEntry(MultiRead request) { - this.request = request; + this.id = request; } @Override int makeHash() { - return request.hashCode(); + return id.hashCode(); } @Override public Object getOriginalRequest() { - return request; + return id; } @Override public void discard() { super.discard(); - request = null; + id = null; setResult(null); } @@ -86,7 +86,7 @@ public final class MultiReadEntry extends CacheEntryBase() { + id.perform(graph , new SyncMultiProcedure() { @Override public void execute(ReadGraph graph, T result) { @@ -123,8 +123,8 @@ public final class MultiReadEntry extends CacheEntryBase extends CacheEntryBase procedure) throws DatabaseException { - return graph.processor.cache.performQuery(graph, request, this, procedure); + return graph.processor.cache.performQuery(graph, id, this, procedure); } } diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCache.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCache.java index 48d5646c2..06882a489 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCache.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCache.java @@ -19,9 +19,8 @@ import org.simantics.db.request.Read; public class QueryCache extends QueryCacheBase { - // Using QueryChaching breaks Diagram Editor (and probably something else). - private static final boolean SINGLE = false; - + private static final boolean SINGLE = false; + public QueryCache(QuerySupport querySupport, int threads) { super(querySupport, threads); } @@ -32,18 +31,19 @@ public class QueryCache extends QueryCacheBase { existing = (Objects)objectsMap.get(r1,r2); if(existing == null) { existing = new Objects(r1,r2); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); objectsMap.put(keyR2(r1,r2), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -89,18 +89,19 @@ public class QueryCache extends QueryCacheBase { existing = (Statements)statementsMap.get(r1,r2); if(existing == null) { existing = new Statements(r1,r2); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); statementsMap.put(keyR2(r1,r2), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -146,18 +147,19 @@ public class QueryCache extends QueryCacheBase { existing = (DirectObjects)directObjectsMap.get(r1,r2); if(existing == null) { existing = new DirectObjects(r1,r2); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); directObjectsMap.put(keyR2(r1,r2), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -203,18 +205,19 @@ public class QueryCache extends QueryCacheBase { existing = (RelationInfoQuery)relationInfoQueryMap.get(r); if(existing == null) { existing = new RelationInfoQuery(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); relationInfoQueryMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -260,18 +263,19 @@ public class QueryCache extends QueryCacheBase { existing = (URIToResource)uRIToResourceMap.get(id); if(existing == null) { existing = new URIToResource(id); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); uRIToResourceMap.put(keyID(id), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -317,18 +321,19 @@ public class QueryCache extends QueryCacheBase { existing = (ValueQuery)valueQueryMap.get(r); if(existing == null) { existing = new ValueQuery(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); valueQueryMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -374,18 +379,19 @@ public class QueryCache extends QueryCacheBase { existing = (OrderedSet)orderedSetMap.get(r); if(existing == null) { existing = new OrderedSet(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); orderedSetMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -431,18 +437,19 @@ public class QueryCache extends QueryCacheBase { existing = (PrincipalTypes)principalTypesMap.get(r); if(existing == null) { existing = new PrincipalTypes(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); principalTypesMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -488,18 +495,19 @@ public class QueryCache extends QueryCacheBase { existing = (DirectPredicates)directPredicatesMap.get(r); if(existing == null) { existing = new DirectPredicates(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); directPredicatesMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -545,18 +553,19 @@ public class QueryCache extends QueryCacheBase { existing = (Predicates)predicatesMap.get(r); if(existing == null) { existing = new Predicates(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); predicatesMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -602,32 +611,33 @@ public class QueryCache extends QueryCacheBase { existing = (ReadEntry)readEntryMap.get(r); if(existing == null) { existing = new ReadEntry(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); readEntryMap.put(id(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } if(existing.isPending()) { - if(needsToBlock) waitPending(graph, existing); - else return null; + if(needsToBlock) + waitPending(graph, existing); + else { + return null; + } } return existing; } - void remove(ReadEntry entry) { synchronized(readEntryMap) { - readEntryMap.remove(entry.request); + readEntryMap.remove(entry.id); } } - public static Object runnerReadEntry(ReadGraphImpl graph, Read r, CacheEntry parent, ListenerBase listener, final AsyncProcedure procedure, final boolean needsToBlock) throws DatabaseException { + public static Object runnerReadEntry(ReadGraphImpl graph, Read r, CacheEntry parent, ListenerBase listener, final AsyncProcedure procedure, boolean needsToBlock) throws DatabaseException { QueryCache cache = graph.processor.cache; if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) { if (SINGLE) { @@ -636,33 +646,32 @@ public class QueryCache extends QueryCacheBase { return e.performFromCache(graph, procedure); } } - return ReadEntry.computeForEach(graph, r, null, procedure); + return ReadEntry.computeForEach(graph, r, null, procedure, needsToBlock); } ReadEntry entry = (ReadEntry)cache.getOrCreateReadEntry(graph, r, needsToBlock); if(entry == null) { - graph.processor.schedule(new SessionTask(graph) { - @Override - public void run0(int thread) { - try { - runnerReadEntry(graph, r, parent, listener, procedure, needsToBlock); - } catch (DatabaseException e) { - Logger.defaultLogError(e); - } - } - }); - return null; + graph.processor.schedule(new SessionTask(graph) { + @Override + public void run0(int thread) { + try { + runnerReadEntry(graph, r, parent, listener, procedure, needsToBlock); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } + } + }); + return null; } AsyncProcedure procedure_ = procedure != null ? procedure : emptyProcedureReadEntry; ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false); if(entry.isReady()) return entry.performFromCache(graph, procedure_); else { assert(entry.isPending()); - Object result = ReadEntry.computeForEach(graph, r, entry, procedure_); + Object result = ReadEntry.computeForEach(graph, r, entry, procedure_, needsToBlock); if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult()); return result; } } - private ReadEntry peekReadEntry(Read r) { synchronized(readEntryMap) { @@ -676,32 +685,33 @@ public class QueryCache extends QueryCacheBase { existing = (AsyncReadEntry)asyncReadEntryMap.get(r); if(existing == null) { existing = new AsyncReadEntry(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); asyncReadEntryMap.put(id(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } if(existing.isPending()) { - if(needsToBlock) waitPending(graph, existing); - else return null; + if(needsToBlock) + waitPending(graph, existing); + else { + return null; + } } return existing; } - void remove(AsyncReadEntry entry) { synchronized(asyncReadEntryMap) { - asyncReadEntryMap.remove(entry.request); + asyncReadEntryMap.remove(entry.id); } } - public static Object runnerAsyncReadEntry(ReadGraphImpl graph, AsyncRead r, CacheEntry parent, ListenerBase listener, final AsyncProcedure procedure, final boolean needsToBlock) throws DatabaseException { + public static Object runnerAsyncReadEntry(ReadGraphImpl graph, AsyncRead r, CacheEntry parent, ListenerBase listener, final AsyncProcedure procedure, boolean needsToBlock) throws DatabaseException { QueryCache cache = graph.processor.cache; if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) { if (SINGLE) { @@ -714,17 +724,17 @@ public class QueryCache extends QueryCacheBase { } AsyncReadEntry entry = (AsyncReadEntry)cache.getOrCreateAsyncReadEntry(graph, r, needsToBlock); if(entry == null) { - graph.processor.schedule(new SessionTask(graph) { - @Override - public void run0(int thread) { - try { - runnerAsyncReadEntry(graph, r, parent, listener, procedure, needsToBlock); - } catch (DatabaseException e) { - Logger.defaultLogError(e); - } - } - }); - return null; + graph.processor.schedule(new SessionTask(graph) { + @Override + public void run0(int thread) { + try { + runnerAsyncReadEntry(graph, r, parent, listener, procedure, needsToBlock); + } catch (DatabaseException e) { + Logger.defaultLogError(e); + } + } + }); + return null; } AsyncProcedure procedure_ = procedure != null ? procedure : emptyProcedureAsyncReadEntry; ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false); @@ -736,7 +746,6 @@ public class QueryCache extends QueryCacheBase { return result; } } - private AsyncReadEntry peekAsyncReadEntry(AsyncRead r) { synchronized(asyncReadEntryMap) { @@ -750,18 +759,19 @@ public class QueryCache extends QueryCacheBase { existing = (Types)typesMap.get(r); if(existing == null) { existing = new Types(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); typesMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -807,18 +817,19 @@ public class QueryCache extends QueryCacheBase { existing = (ChildMap)childMapMap.get(r); if(existing == null) { existing = new ChildMap(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); childMapMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -864,18 +875,19 @@ public class QueryCache extends QueryCacheBase { existing = (TypeHierarchy)typeHierarchyMap.get(r); if(existing == null) { existing = new TypeHierarchy(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); typeHierarchyMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -921,18 +933,19 @@ public class QueryCache extends QueryCacheBase { existing = (SuperTypes)superTypesMap.get(r); if(existing == null) { existing = new SuperTypes(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); superTypesMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -978,18 +991,19 @@ public class QueryCache extends QueryCacheBase { existing = (SuperRelations)superRelationsMap.get(r); if(existing == null) { existing = new SuperRelations(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); superRelationsMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -1035,18 +1049,19 @@ public class QueryCache extends QueryCacheBase { existing = (AssertedPredicates)assertedPredicatesMap.get(r); if(existing == null) { existing = new AssertedPredicates(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); assertedPredicatesMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -1081,18 +1096,19 @@ public class QueryCache extends QueryCacheBase { existing = (AssertedStatements)assertedStatementsMap.get(r1,r2); if(existing == null) { existing = new AssertedStatements(r1,r2); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); assertedStatementsMap.put(keyR2(r1,r2), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -1127,18 +1143,19 @@ public class QueryCache extends QueryCacheBase { existing = (DirectSuperRelations)directSuperRelationsMap.get(r); if(existing == null) { existing = new DirectSuperRelations(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); directSuperRelationsMap.put(keyR(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } @@ -1173,24 +1190,25 @@ public class QueryCache extends QueryCacheBase { existing = (MultiReadEntry)multiReadEntryMap.get(r); if(existing == null) { existing = new MultiReadEntry(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); multiReadEntryMap.put(id(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } void remove(MultiReadEntry entry) { synchronized(multiReadEntryMap) { - multiReadEntryMap.remove(entry.request); + multiReadEntryMap.remove(entry.id); } } @@ -1219,24 +1237,25 @@ public class QueryCache extends QueryCacheBase { existing = (AsyncMultiReadEntry)asyncMultiReadEntryMap.get(r); if(existing == null) { existing = new AsyncMultiReadEntry(r); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); asyncMultiReadEntryMap.put(id(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } void remove(AsyncMultiReadEntry entry) { synchronized(asyncMultiReadEntryMap) { - asyncMultiReadEntryMap.remove(entry.request); + asyncMultiReadEntryMap.remove(entry.id); } } @@ -1265,25 +1284,25 @@ public class QueryCache extends QueryCacheBase { existing = (ExternalReadEntry)externalReadEntryMap.get(r); if(existing == null) { existing = new ExternalReadEntry(r, graph); - existing.clearResult(querySupport); - existing.setPending(); + existing.setPending(querySupport); externalReadEntryMap.put(id(r), existing); size++; return existing; } if(existing.requiresComputation()) { - existing.setPending(); + existing.setPending(querySupport); return existing; } } - if(existing.isPending()) waitPending(graph, existing); + if(existing.isPending()) { + waitPending(graph, existing); + } return existing; } - void remove(ExternalReadEntry entry) { synchronized(externalReadEntryMap) { - externalReadEntryMap.remove(entry.request); + externalReadEntryMap.remove(entry.id); } } diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCacheBase.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCacheBase.java index 6abaf6b65..446e9c641 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCacheBase.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCacheBase.java @@ -3,21 +3,19 @@ package org.simantics.db.impl.query; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicBoolean; +import org.simantics.databoard.Bindings; import org.simantics.db.AsyncReadGraph; +import org.simantics.db.DevelopmentKeys; import org.simantics.db.ObjectResourceIdMap; import org.simantics.db.ReadGraph; import org.simantics.db.RelationInfo; import org.simantics.db.common.utils.Logger; import org.simantics.db.exception.DatabaseException; -import org.simantics.db.impl.DebugPolicy; import org.simantics.db.impl.graph.ReadGraphImpl; import org.simantics.db.impl.procedure.InternalProcedure; -import org.simantics.db.impl.query.QueryProcessor.SessionTask; import org.simantics.db.procedure.AsyncMultiProcedure; import org.simantics.db.procedure.AsyncProcedure; -import org.simantics.db.procedure.Listener; import org.simantics.db.procedure.ListenerBase; import org.simantics.db.procedure.Procedure; import org.simantics.db.procedure.SyncMultiProcedure; @@ -26,6 +24,7 @@ import org.simantics.db.request.AsyncRead; import org.simantics.db.request.ExternalRead; import org.simantics.db.request.MultiRead; import org.simantics.db.request.Read; +import org.simantics.utils.Development; import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.TObjectIntHashMap; @@ -328,7 +327,11 @@ public class QueryCacheBase { } catch (DatabaseException e) { Logger.defaultLogError(e); } - if(DebugPolicy.DEPENDENCIES) System.out.println(child + " -> " + parent); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_DEPENDENCIES, Bindings.BOOLEAN)) { + System.err.println(child + " -> " + parent); + } + } } if (listener != null) { @@ -376,9 +379,11 @@ public class QueryCacheBase { list.add(result); } - if(DebugPolicy.LISTENER) { - new Exception().printStackTrace(); - System.out.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + new Exception().printStackTrace(); + System.err.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure); + } } return result; diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCollectorImpl2.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCollectorImpl2.java index 84273b81d..0efa49f56 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCollectorImpl2.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCollectorImpl2.java @@ -6,9 +6,10 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import org.simantics.databoard.Bindings; import org.simantics.databoard.util.IdentityHashSet; +import org.simantics.db.DevelopmentKeys; import org.simantics.db.common.exception.DebugException; -import org.simantics.db.impl.DebugPolicy; import org.simantics.db.impl.query.QueryProcessor.QueryCollectorSupport; import org.simantics.utils.Development; @@ -28,21 +29,29 @@ class QueryCollectorImpl2 implements QueryProcessor.QueryCollector { private boolean findCollectables(CacheEntry entry, Map collectables, ArrayList result) { if (entry.isDiscarded()) { - if(DebugPolicy.COLLECT && DebugPolicy.VERBOSE) - System.out.println("GC: discarded entry " + entry); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + System.err.println("GC: discarded entry " + entry); + } + } return true; } if (entry.isPending()) { - if(DebugPolicy.COLLECT && DebugPolicy.VERBOSE) - System.out.println("GC: pending entry " + entry + " was not collected."); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + System.err.println("GC: pending entry " + entry + " was not collected."); + } + } collectables.remove(entry); return false; } if (this.queryProcessor.hasListenerAfterDisposing(entry)) { - if (DebugPolicy.COLLECT && DebugPolicy.VERBOSE) { - System.out.println("GC: listened entry " + entry + " was not collected. Entry=" + entry); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + System.err.println("GC: listened entry " + entry + " was not collected. Entry=" + entry); + } } collectables.remove(entry); return false; @@ -60,8 +69,11 @@ class QueryCollectorImpl2 implements QueryProcessor.QueryCollector { } if(!parentIsCollectable) { - if(DebugPolicy.COLLECT && DebugPolicy.VERBOSE) - System.out.println("GC: due to bound parent " + parent + " the entry + " + entry + " was not collected."); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + System.err.println("GC: due to bound parent " + parent + " the entry + " + entry + " was not collected."); + } + } collectables.remove(entry); return false; } @@ -109,8 +121,11 @@ class QueryCollectorImpl2 implements QueryProcessor.QueryCollector { // Compute amount of free queries int freeCount = collectables.size(); - if(DebugPolicy.COLLECT) - System.out.println("collector found " + freeCount + " free queries."); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + System.err.println("collector found " + freeCount + " free queries."); + } + } lastKnownFixedSize = currentSize - freeCount; @@ -119,8 +134,13 @@ class QueryCollectorImpl2 implements QueryProcessor.QueryCollector { int target = freeCount - maxNumberOfCollectableQueries/2; - if(DebugPolicy.COLLECT) - System.out.println("collector removes " + target + " free queries."); + + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + System.err.println("collector found " + freeCount + " free queries."); + System.err.println("collector removes " + target + " free queries."); + } + } for(CacheEntry entry : collectables) { if(queryProcessor.removeQuery(entry)) @@ -139,8 +159,11 @@ class QueryCollectorImpl2 implements QueryProcessor.QueryCollector { removals.clear(); } - if(DebugPolicy.COLLECT) { - System.out.println("collect found " + freeCount + " collectable entries."); + + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + System.err.println("collect found " + freeCount + " collectable entries."); + } } return; @@ -152,24 +175,34 @@ class QueryCollectorImpl2 implements QueryProcessor.QueryCollector { try { - int current = support.calculateCurrentSize(); - if(DebugPolicy.COLLECT) - new DebugException("checking the need for collecting queries (current=" + current + " , lastKnownFixedSize=" + lastKnownFixedSize + " max free=" + 0 + ")").printStackTrace(); + int current = support.calculateCurrentSize(); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + new DebugException("checking the need for collecting queries (current=" + current + " , lastKnownFixedSize=" + lastKnownFixedSize + " max free=" + 0 + ")").printStackTrace(); + } + } + queryProcessor.cache.collecting = true; long start = System.nanoTime(); doCollect(current, 0); - if(DebugPolicy.COLLECT) - System.out.println("collect finished with " + support.calculateCurrentSize() + " entries (lastKnownFixedSize=" + lastKnownFixedSize + ")."); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + System.err.println("collect finished with " + support.calculateCurrentSize() + " entries (lastKnownFixedSize=" + lastKnownFixedSize + ")."); + } + } long duration = System.nanoTime() - start; - if(DebugPolicy.COLLECT) - System.err.println("Collect took " + 1e-9*duration + "s."); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) { + System.err.println("Collect took " + 1e-9*duration + "s."); + } + } } catch (Throwable t) { t.printStackTrace(); diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryIdentityHash.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryIdentityHash.java index 6db4726ac..c2b21444f 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryIdentityHash.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryIdentityHash.java @@ -131,7 +131,7 @@ abstract public class QueryIdentityHash extends THash { } @Override - public void setPending() { + public void setPending(QuerySupport querySupport) { // TODO Auto-generated method stub } diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryProcessor.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryProcessor.java index 5a37257e2..9b54d15f6 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryProcessor.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryProcessor.java @@ -49,7 +49,6 @@ import org.simantics.db.exception.DatabaseException; import org.simantics.db.exception.ManyObjectsForFunctionalRelationException; import org.simantics.db.exception.NoInverseException; import org.simantics.db.exception.ResourceNotFoundException; -import org.simantics.db.impl.DebugPolicy; import org.simantics.db.impl.ResourceImpl; import org.simantics.db.impl.graph.BarrierTracing; import org.simantics.db.impl.graph.ReadGraphImpl; @@ -713,7 +712,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } catch (DatabaseException e) { Logger.defaultLogError(e); } - if(DebugPolicy.DEPENDENCIES) System.out.println(child + " -> " + parent); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_DEPENDENCIES, Bindings.BOOLEAN)) { + System.out.println(child + " -> " + parent); + } + } } if (listener != null) { @@ -963,9 +966,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap list.add(result); } - if(DebugPolicy.LISTENER) { - new Exception().printStackTrace(); - System.out.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + new Exception().printStackTrace(); + System.err.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure); + } } return result; @@ -974,7 +979,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap private void scheduleListener(ListenerEntry entry) { assert (entry != null); - if(DebugPolicy.LISTENER) System.out.println("Scheduled " + entry.procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + System.err.println("Scheduled " + entry.procedure); + } + } scheduledListeners.add(entry); } @@ -1257,11 +1266,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap for(CacheEntry entry : workarea.keySet()) { Class clazz = entry.getClass(); - if(entry instanceof ReadEntry) clazz = ((ReadEntry)entry).request.getClass(); - else if(entry instanceof MultiReadEntry) clazz = ((MultiReadEntry)entry).request.getClass(); - else if(entry instanceof AsyncReadEntry) clazz = ((AsyncReadEntry)entry).request.getClass(); - else if(entry instanceof AsyncMultiReadEntry) clazz = ((AsyncMultiReadEntry)entry).request.getClass(); - else if(entry instanceof ExternalReadEntry) clazz = ((ExternalReadEntry)entry).request.getClass(); + if(entry instanceof ReadEntry) clazz = ((ReadEntry)entry).id.getClass(); + else if(entry instanceof MultiReadEntry) clazz = ((MultiReadEntry)entry).id.getClass(); + else if(entry instanceof AsyncReadEntry) clazz = ((AsyncReadEntry)entry).id.getClass(); + else if(entry instanceof AsyncMultiReadEntry) clazz = ((AsyncMultiReadEntry)entry).id.getClass(); + else if(entry instanceof ExternalReadEntry) clazz = ((ExternalReadEntry)entry).id.getClass(); Integer c = counts.get(clazz); if(c == null) counts.put(clazz, -1); else counts.put(clazz, c-1); @@ -1426,8 +1435,6 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap CacheEntry entry = e.entry; - //System.err.println("updateQuery " + entry); - /* * If the dependency graph forms a DAG, some entries are inserted in the * todo list many times. They only need to be processed once though. @@ -1435,32 +1442,32 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap if (entry.isDiscarded()) { if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("D"); + System.err.print("D"); for (int i = 0; i < e.indent; i++) - System.out.print(" "); - System.out.println(entry.getQuery()); + System.err.print(" "); + System.err.println(entry.getQuery()); } } // System.err.println(" => DISCARDED"); return false; } - if (entry.isRefuted()) { - if (Development.DEVELOPMENT) { - if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("R"); - for (int i = 0; i < e.indent; i++) - System.out.print(" "); - System.out.println(entry.getQuery()); - } - } - return false; - } +// if (entry.isRefuted()) { +// if (Development.DEVELOPMENT) { +// if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { +// System.err.print("R"); +// for (int i = 0; i < e.indent; i++) +// System.err.print(" "); +// System.err.println(entry.getQuery()); +// } +// } +// return false; +// } if (entry.isExcepted()) { if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("E"); + System.err.print("E"); } } } @@ -1468,7 +1475,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap if (entry.isPending()) { if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("P"); + System.err.print("P"); } } } @@ -1477,10 +1484,10 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.out.print("U "); + System.err.print("U "); for (int i = 0; i < e.indent; i++) - System.out.print(" "); - System.out.print(entry.getQuery()); + System.err.print(" "); + System.err.print(entry.getQuery()); } } @@ -1492,9 +1499,9 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap if (Development.DEVELOPMENT) { if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { if(hasListener(entry)) { - System.out.println(" (L)"); + System.err.println(" (L)"); } else { - System.out.println(""); + System.err.println(""); } } } @@ -1616,7 +1623,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap Query query = entry.getQuery(); - if(DebugPolicy.RECOMPUTE) System.out.println("R " + query); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_RECOMPUTE, Bindings.BOOLEAN)) { + System.err.println("R " + query); + } + } entry.prepareRecompute(querySupport); @@ -1629,10 +1640,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap Object newValue = entry.getResult(); if (ListenerEntry.NO_VALUE == oldValue) { - if(DebugPolicy.CHANGES) { - System.out.println("C " + query); - System.out.println("- " + oldValue); - System.out.println("- " + newValue); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_CHANGES, Bindings.BOOLEAN)) { + System.out.println("C " + query); + System.out.println("- " + oldValue); + System.out.println("- " + newValue); + } } return newValue; } @@ -1648,10 +1661,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap } else changed = (oldValue != null); - if(DebugPolicy.CHANGES && changed) { - System.out.println("C " + query); - System.out.println("- " + oldValue); - System.out.println("- " + newValue); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_CHANGES, Bindings.BOOLEAN)) { + System.err.println("C " + query); + System.err.println("- " + oldValue); + System.err.println("- " + newValue); + } } return changed ? newValue : ListenerEntry.NOT_CHANGED; @@ -1696,7 +1711,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap for (ListenerEntry listenerEntry : entries) { if (pruneListener(listenerEntry)) { - if(DebugPolicy.LISTENER) System.out.println("Pruned " + listenerEntry.procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + new Exception().printStackTrace(); + System.err.println("Pruned " + listenerEntry.procedure); + } + } continue; } @@ -1706,8 +1726,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap Object newValue = compareTo(graph, entry, listenerEntry.getLastKnown()); if (newValue != ListenerEntry.NOT_CHANGED) { - if(DebugPolicy.LISTENER) - System.out.println("Add to schedule " + listenerEntry.procedure + " with " + newValue); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + new Exception().printStackTrace(); + System.err.println("Add to schedule " + listenerEntry.procedure + " with " + newValue); + } + } schedule.add(listenerEntry); listenerEntry.setLastKnown(entry.getResult()); } @@ -1716,11 +1740,17 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap for(ListenerEntry listenerEntry : schedule) { final CacheEntry entry = listenerEntry.entry; - if(DebugPolicy.LISTENER) - System.out.println("Firing " + listenerEntry.procedure); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + System.err.println("Firing " + listenerEntry.procedure); + } + } try { - if(DebugPolicy.LISTENER) - System.out.println("Firing " + listenerEntry.procedure + " for " + listenerEntry.entry); + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) { + System.err.println("Firing " + listenerEntry.procedure + " for " + listenerEntry.entry); + } + } entry.performFromCache(graph, listenerEntry.procedure); } catch (Throwable t) { t.printStackTrace(); @@ -1821,6 +1851,22 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap private Object primitiveUpdateLock = new Object(); private THashSet scheduledPrimitiveUpdates = new THashSet(); + private ArrayList refutations = new ArrayList<>(); + + private void markForUpdate(ReadGraphImpl graph, CacheEntry e) { + e.refute(); + refutations.add(e); + } + + private void updateRefutations(ReadGraphImpl graph) { + + for(CacheEntry e : refutations) + update(graph, e); + + refutations.clear(); + + } + public void performDirtyUpdates(final ReadGraphImpl graph) { cache.dirty = false; @@ -1840,28 +1886,37 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap final int subject = (int)(arg0 >>> 32); final int predicate = (int)(arg0 & 0xffffffff); - for(Objects o : QueryCache.entriesObjects(QueryProcessor.this, subject)) update(graph, o); - for(DirectObjects o : QueryCache.entriesDirectObjects(QueryProcessor.this, subject)) update(graph, o); - for(Statements o : QueryCache.entriesStatements(QueryProcessor.this, subject)) update(graph, o); + for(Objects o : QueryCache.entriesObjects(QueryProcessor.this, subject)) markForUpdate(graph, o); + for(DirectObjects o : QueryCache.entriesDirectObjects(QueryProcessor.this, subject)) markForUpdate(graph, o); + for(Statements o : QueryCache.entriesStatements(QueryProcessor.this, subject)) markForUpdate(graph, o); if(predicate == instanceOf || predicate == inherits || predicate == subrelationOf) { PrincipalTypes principalTypes = QueryCache.entryPrincipalTypes(QueryProcessor.this, subject); - if(principalTypes != null) update(graph, principalTypes); + if(principalTypes != null) markForUpdate(graph, principalTypes); Types types = QueryCache.entryTypes(QueryProcessor.this, subject); - if(types != null) update(graph, types); + if(types != null) markForUpdate(graph, types); } if(predicate == subrelationOf) { SuperRelations superRelations = SuperRelations.entry(QueryProcessor.this, subject); - if(superRelations != null) update(graph, superRelations); + if(superRelations != null) markForUpdate(graph, superRelations); } DirectPredicates dp = QueryCache.entryDirectPredicates(QueryProcessor.this, subject); - if(dp != null) update(graph, dp); + if(dp != null) markForUpdate(graph, dp); OrderedSet os = QueryCache.entryOrderedSet(QueryProcessor.this, predicate); - if(os != null) update(graph, os); + if(os != null) markForUpdate(graph, os); + updateRefutations(graph); + scheduledObjectUpdates.clear(); + + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { + System.err.println("== Query update ends =="); + } + } + return; } @@ -1872,9 +1927,18 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap int arg0 = scheduledValueUpdates.getFirst(); ValueQuery valueQuery = QueryCache.entryValueQuery(QueryProcessor.this, arg0); - if(valueQuery != null) update(graph, valueQuery); + if(valueQuery != null) markForUpdate(graph, valueQuery); + + updateRefutations(graph); scheduledValueUpdates.clear(); + + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { + System.err.println("== Query update ends =="); + } + } + return; } @@ -1888,30 +1952,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap scheduledPrimitiveUpdates = new THashSet(); } - primitiveUpdates.forEach(new TObjectProcedure() { - - @Override - public boolean execute(Object arg0) { - - ExternalReadEntry query = (ExternalReadEntry)cache.externalReadEntryMap.get(arg0); - if (query != null) { - boolean listening = update(graph, query); - if (!listening && !query.hasParents()) { - cache.externalReadEntryMap.remove(arg0); - query.discard(); - } - } - return true; - } - - }); - scheduledValueUpdates.forEach(new TIntProcedure() { @Override public boolean execute(int arg0) { ValueQuery valueQuery = QueryCache.entryValueQuery(QueryProcessor.this, arg0); - if(valueQuery != null) update(graph, valueQuery); + if(valueQuery != null) markForUpdate(graph, valueQuery); return true; } @@ -1923,15 +1969,15 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap public boolean execute(int resource) { ValueQuery valueQuery = QueryCache.entryValueQuery(QueryProcessor.this, resource); - if(valueQuery != null) update(graph, valueQuery); + if(valueQuery != null) markForUpdate(graph, valueQuery); PrincipalTypes principalTypes = QueryCache.entryPrincipalTypes(QueryProcessor.this, resource); - if(principalTypes != null) update(graph, principalTypes); + if(principalTypes != null) markForUpdate(graph, principalTypes); Types types = QueryCache.entryTypes(QueryProcessor.this, resource); - if(types != null) update(graph, types); + if(types != null) markForUpdate(graph, types); SuperRelations superRelations = SuperRelations.entry(QueryProcessor.this, resource); - if(superRelations != null) update(graph, superRelations); + if(superRelations != null) markForUpdate(graph, superRelations); predicates.add(resource); @@ -1950,14 +1996,14 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap if(predicate == instanceOf || predicate == inherits || predicate == subrelationOf) { PrincipalTypes principalTypes = QueryCache.entryPrincipalTypes(QueryProcessor.this, subject); - if(principalTypes != null) update(graph, principalTypes); + if(principalTypes != null) markForUpdate(graph, principalTypes); Types types = QueryCache.entryTypes(QueryProcessor.this, subject); - if(types != null) update(graph, types); + if(types != null) markForUpdate(graph, types); } if(predicate == subrelationOf) { SuperRelations superRelations = SuperRelations.entry(QueryProcessor.this, subject); - if(superRelations != null) update(graph, superRelations); + if(superRelations != null) markForUpdate(graph, superRelations); } predicates.add(subject); @@ -1974,12 +2020,12 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap @Override public boolean execute(final int subject) { - for(Objects o : QueryCache.entriesObjects(QueryProcessor.this, subject)) update(graph, o); - for(DirectObjects o : QueryCache.entriesDirectObjects(QueryProcessor.this, subject)) update(graph, o); - for(Statements o : QueryCache.entriesStatements(QueryProcessor.this, subject)) update(graph, o); + for(Objects o : QueryCache.entriesObjects(QueryProcessor.this, subject)) markForUpdate(graph, o); + for(DirectObjects o : QueryCache.entriesDirectObjects(QueryProcessor.this, subject)) markForUpdate(graph, o); + for(Statements o : QueryCache.entriesStatements(QueryProcessor.this, subject)) markForUpdate(graph, o); DirectPredicates entry = QueryCache.entryDirectPredicates(QueryProcessor.this, subject); - if(entry != null) update(graph, entry); + if(entry != null) markForUpdate(graph, entry); return true; @@ -1993,7 +2039,7 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap public boolean execute(int orderedSet) { OrderedSet entry = QueryCache.entryOrderedSet(QueryProcessor.this, orderedSet); - if(entry != null) update(graph, entry); + if(entry != null) markForUpdate(graph, entry); return true; @@ -2001,21 +2047,35 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap }); - // for (Integer subject : predicates) { - // DirectPredicates entry = DirectPredicates.entry(QueryProcessor.this, subject); - // if(entry != null) update(graph, entry); - // } + updateRefutations(graph); + + primitiveUpdates.forEach(new TObjectProcedure() { + @Override + public boolean execute(Object arg0) { - if (Development.DEVELOPMENT) { - if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { - System.err.println("== Query update ends =="); + ExternalReadEntry query = (ExternalReadEntry)cache.externalReadEntryMap.get(arg0); + if (query != null) { + boolean listening = update(graph, query); + if (!listening && !query.hasParents()) { + cache.externalReadEntryMap.remove(arg0); + query.discard(); + } + } + return true; } - } + }); + scheduledValueUpdates.clear(); scheduledObjectUpdates.clear(); scheduledInvalidates.clear(); + + if (Development.DEVELOPMENT) { + if(Development.getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) { + System.err.println("== Query update ends =="); + } + } } diff --git a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/ReadEntry.java b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/ReadEntry.java index 1ceca45a5..72f132288 100644 --- a/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/ReadEntry.java +++ b/bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/ReadEntry.java @@ -25,20 +25,20 @@ public final class ReadEntry extends CacheEntryBase> implem private static final Logger LOGGER = LoggerFactory.getLogger(ReadEntry.class); - protected Read request; + protected Read id; public ReadEntry(Read request) { - this.request = request; + this.id = request; } @Override int makeHash() { - return request.hashCode(); + return id.hashCode(); } @Override public Object getOriginalRequest() { - return request; + return id; } @Override @@ -57,7 +57,7 @@ public final class ReadEntry extends CacheEntryBase> implem try { - T result = request.perform(graph); + T result = id.perform(graph); setResult(result); setReady(); @@ -76,8 +76,8 @@ public final class ReadEntry extends CacheEntryBase> implem @Override public int type() { - if (request instanceof ReadExt) { - return ((ReadExt) request).getType(); + if (id instanceof ReadExt) { + return ((ReadExt) id).getType(); } else { return RequestFlags.INVALIDATE; } @@ -85,10 +85,10 @@ public final class ReadEntry extends CacheEntryBase> implem @Override public String toString() { - if (request == null) + if (id == null) return "DISCARDED"; else - return request.toString() + statusOrException; + return id.toString() + statusOrException; } }; @@ -96,7 +96,7 @@ public final class ReadEntry extends CacheEntryBase> implem } public static T computeForEach(ReadGraphImpl graph, Read request, ReadEntry entry, - AsyncProcedure procedure_) throws DatabaseException { + AsyncProcedure procedure_, boolean needsToBlock) throws DatabaseException { AsyncProcedure procedure = entry != null ? entry : procedure_; @@ -181,10 +181,10 @@ public final class ReadEntry extends CacheEntryBase> implem @Override public String toString() { - if (request == null) + if (id == null) return "DISCARDED"; else - return request.toString() + " - " + statusOrException; + return id.toString() + " - " + statusOrException; } public Object get(ReadGraphImpl graph, AsyncProcedure procedure) throws DatabaseException { @@ -196,8 +196,8 @@ public final class ReadEntry extends CacheEntryBase> implem @Override boolean isImmutable(ReadGraphImpl graph) throws DatabaseException { - if (request instanceof ReadExt) { - return ((ReadExt) request).isImmutable(graph); + if (id instanceof ReadExt) { + return ((ReadExt) id).isImmutable(graph); } return false; } diff --git a/bundles/org.simantics.db.layer0/adapters.xml b/bundles/org.simantics.db.layer0/adapters.xml index 0aabf0b35..11a3ff235 100644 --- a/bundles/org.simantics.db.layer0/adapters.xml +++ b/bundles/org.simantics.db.layer0/adapters.xml @@ -234,7 +234,12 @@ - + + + + + diff --git a/bundles/org.simantics.db.layer0/build.properties b/bundles/org.simantics.db.layer0/build.properties index f686835b4..edf9665de 100644 --- a/bundles/org.simantics.db.layer0/build.properties +++ b/bundles/org.simantics.db.layer0/build.properties @@ -15,4 +15,5 @@ exclude.. = org/simantics/db/layer0/spm/org.simantics.db.build.zip bin.includes = META-INF/,\ .,\ plugin.xml,\ - adapters.xml + adapters.xml,\ + scl/ diff --git a/bundles/org.simantics.db.layer0/scl/Simantics/Layer0.scl b/bundles/org.simantics.db.layer0/scl/Simantics/Layer0.scl new file mode 100644 index 000000000..0b034a14d --- /dev/null +++ b/bundles/org.simantics.db.layer0/scl/Simantics/Layer0.scl @@ -0,0 +1,9 @@ +include "Simantics/DB" +include "Simantics/Issue" + +importJava "org.simantics.db.layer0.function.All" where + uriValidator :: Resource -> [Issue] + valueValidator :: Resource -> [Issue] + relationValidator :: Resource -> [Issue] + propertyValidator :: Resource -> [Issue] + clusterValidator :: Resource -> [Issue] \ No newline at end of file diff --git a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/internal/SimanticsInternal.java b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/internal/SimanticsInternal.java index 8ae309e68..d30be8ffc 100644 --- a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/internal/SimanticsInternal.java +++ b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/internal/SimanticsInternal.java @@ -12,22 +12,12 @@ package org.simantics.db.layer0.internal; import java.io.File; -import java.util.concurrent.TimeUnit; import org.eclipse.core.runtime.Platform; import org.simantics.db.Resource; -import org.simantics.db.Session; -import org.simantics.db.exception.DatabaseException; import org.simantics.db.layer0.util.SimanticsClipboard; import org.simantics.db.layer0.util.SimanticsKeys; import org.simantics.db.management.ISessionContext; -import org.simantics.db.management.ISessionContextProvider; -import org.simantics.db.management.ISessionContextProviderSource; -import org.simantics.db.request.ReadInterface; -import org.simantics.db.request.WriteInterface; -import org.simantics.layer0.Layer0; -import org.simantics.operation.Layer0X; -import org.simantics.utils.threads.ThreadUtils; /** * An internal facade for accessing basic Simantics platform services. @@ -35,112 +25,7 @@ import org.simantics.utils.threads.ThreadUtils; * * Use org.simantics.Simantics instead where ever possible. */ -public class SimanticsInternal { - - private static ISessionContextProviderSource providerSource = null; - - /** - * Queue execution of a runnable. - * - * @param runnable - */ - public static void async(Runnable runnable) { - ThreadUtils.getBlockingWorkExecutor().execute(runnable); - } - - public static void async(Runnable runnable, int delay, TimeUnit unit) { - ThreadUtils.getTimer().schedule(runnable, delay, unit); - } - - /** - * Queue execution of a non-blocking runnable. Use this method with caution. - * A non-blocking runnable nevers locks anything, No Locks, No semaphores, - * No Object.wait(), No synchronized() {} blocks. - * - * @param runnable a non-blocking runnable - */ - public static void asyncNonblocking(Runnable runnable) { - ThreadUtils.getNonBlockingWorkExecutor().execute(runnable); - } - - /** - * Schedule execution of a non-blocking runnable. Use this method with caution. - * A non-blocking runnable never locks anything, No Locks, No semaphores, - * No Object,wait(), No synchronized() {} blocks. - * - * @param runnable a non-blocking runnable - * @param initialDelay - * @param period - */ - public static void asyncNonblocking(Runnable runnable, int initialDelay, int period) { - ThreadUtils.getNonBlockingWorkExecutor().scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.MILLISECONDS); - } - - public static synchronized ISessionContext setSessionContext(ISessionContext ctx) { - return getSessionContextProvider().setSessionContext(ctx); - } - - public static void setSessionContextProviderSource(ISessionContextProviderSource source) { - if (source == null) - throw new IllegalArgumentException("null provider source"); - providerSource = source; - } - - public static ISessionContextProviderSource getProviderSource() { - if (providerSource == null) - throw new IllegalStateException( - "providerSource must be initialized by the application before using class Simantics"); - return providerSource; - } - - public static ISessionContextProvider getSessionContextProvider() { - return getProviderSource().getActive(); - } - - /** - * Returns the database session context associated with the currently active - * context. This method should be used to retrieve session contexts only - * when the client is sure that the correct context is active. - * - * @return the session context associated with the currently active context - * or null if the context has no session context - */ - public static ISessionContext getSessionContext() { - ISessionContextProvider provider = getSessionContextProvider(); - return provider != null ? provider.getSessionContext() : null; - } - - /** - * Returns the database Session bound to the currently active context. - * - *

- * The method always returns a non-null Session or produces an - * IllegalStateException if a Session was not attainable. - *

- * - * @return the Session bound to the currently active workbench window - * @throws IllegalStateException if no Session was available - */ - public static Session getSession() { - ISessionContext ctx = getSessionContext(); - if (ctx == null) - throw new IllegalStateException("Session unavailable, no database session open"); - return ctx.getSession(); - } - - /** - * Returns the database Session bound to the currently active context. - * Differently from {@link #getSession()}, this method returns - * null if there is no current Session available. - * - * @see #getSession() - * @return the Session bound to the currently active context or - * null - */ - public static Session peekSession() { - ISessionContext ctx = getSessionContext(); - return ctx == null ? null : ctx.peekSession(); - } +public class SimanticsInternal extends org.simantics.db.common.SimanticsInternal { /** * @return the currently open and active project as an IProject @@ -179,23 +64,6 @@ public class SimanticsInternal { return clipboard; } - public static Layer0 getLayer0() throws DatabaseException { - return Layer0.getInstance(getSession()); - } - - public static Layer0X getLayer0X() throws DatabaseException { - return Layer0X.getInstance(getSession()); - } - - - public static T sync(ReadInterface r) throws DatabaseException { - return getSession().sync(r); - } - - public static T sync(WriteInterface r) throws DatabaseException { - return getSession().sync(r); - } - public static File getTemporaryDirectory() { File workspace = Platform.getLocation().toFile(); File temp = new File(workspace, "tempFiles"); diff --git a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/scl/SCLAction.java b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/scl/SCLAction.java new file mode 100644 index 000000000..b2225f7c9 --- /dev/null +++ b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/scl/SCLAction.java @@ -0,0 +1,73 @@ +package org.simantics.db.layer0.scl; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.common.request.ResourceRead; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.adapter.ActionFactory; +import org.simantics.db.layer0.internal.SimanticsInternal; +import org.simantics.db.layer0.util.DatabaseExceptionUtils; +import org.simantics.db.layer0.variable.Variable; +import org.simantics.db.layer0.variable.Variables; +import org.simantics.layer0.Layer0; +import org.simantics.scl.runtime.function.Function1; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SCLAction implements ActionFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(SCLAction.class); + + private final Resource rule; + + public SCLAction(ReadGraph graph, Resource rule) throws DatabaseException { + this.rule = rule; + } + + static class RuleFunctionRequest extends ResourceRead> { + + protected RuleFunctionRequest(Resource rule) { + super(rule); + } + + @Override + public Function1 perform(ReadGraph graph) throws DatabaseException { + Variable ruleVariable = Variables.getVariable(graph, resource); + Layer0 L0 = Layer0.getInstance(graph); + return ruleVariable.getPossiblePropertyValue(graph, L0.SCLAction_action); + } + + } + + static class SCLActionRunnable implements Runnable { + + public final Resource rule; + public final Resource target; + + public SCLActionRunnable(Resource rule, Resource target) { + this.rule = rule; + this.target = target; + } + + @Override + public void run() { + Session s = SimanticsInternal.getSession(); + Resource resource = (Resource) target; + s.markUndoPoint(); + try { + Function1 function = s.syncRequest(new RuleFunctionRequest(rule)); + function.apply(resource); + } catch (DatabaseException e) { + LOGGER.error("Error while executing action " + DatabaseExceptionUtils.showResource(s, resource), e); + } + } + + } + + @Override + public Runnable create(final Object target) { + return new SCLActionRunnable(rule, (Resource) target); + } + +} diff --git a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/DatabaseExceptionUtils.java b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/DatabaseExceptionUtils.java new file mode 100644 index 000000000..236871354 --- /dev/null +++ b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/DatabaseExceptionUtils.java @@ -0,0 +1,36 @@ +package org.simantics.db.layer0.util; + +import org.simantics.db.ReadGraph; +import org.simantics.db.RequestProcessor; +import org.simantics.db.Resource; +import org.simantics.db.common.request.UniqueRead; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.db.layer0.internal.SimanticsInternal; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DatabaseExceptionUtils { + + private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseExceptionUtils.class); + + public static String showResource(Resource resource) { + return showResource(SimanticsInternal.getSession(), resource); + } + + public static String showResource(RequestProcessor processor, Resource resource) { + try { + return processor.syncRequest(new UniqueRead() { + + @Override + public String perform(ReadGraph graph) throws DatabaseException { + return NameUtils.getURIOrSafeNameInternal(graph, resource); + } + }); + } catch (DatabaseException e) { + LOGGER.error("Unknown error while evaluating debug name for a resource " + resource, e); + return resource.toString(); + } + } + +} diff --git a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/Layer0Utils.java b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/Layer0Utils.java index 62c7093da..610c8c8bd 100644 --- a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/Layer0Utils.java +++ b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/Layer0Utils.java @@ -74,6 +74,7 @@ import org.simantics.db.common.request.ObjectsWithType; import org.simantics.db.common.request.PossibleChild; import org.simantics.db.common.request.PossibleIndexRoot; import org.simantics.db.common.request.WriteRequest; +import org.simantics.db.common.utils.CommonDBUtils; import org.simantics.db.common.utils.NameUtils; import org.simantics.db.event.ChangeListener; import org.simantics.db.exception.CancelTransactionException; @@ -353,13 +354,9 @@ public class Layer0Utils { throw new IllegalArgumentException("Unable to convert datatype into SCL type: " + type); } - + @Deprecated public static Type getSCLType(ReadGraph graph, RuntimeEnvironment runtimeEnvironment, String typeText) throws DatabaseException { - try { - return Environments.getType(runtimeEnvironment.getEnvironment(), typeText); - } catch (SCLExpressionCompilationException e) { - throw new DatabaseException(e); - } + return CommonDBUtils.getSCLType(graph, runtimeEnvironment, typeText); } public static Type getSCLType(ReadGraph graph, Variable property) throws DatabaseException { @@ -646,15 +643,14 @@ public class Layer0Utils { return graph.getPossibleResource(graph.getURI(root) + suffix); } + @Deprecated public static Resource getPossibleChild(ReadGraph graph, Resource resource, String name) throws DatabaseException { - return graph.sync(new PossibleChild(resource, name)); + return CommonDBUtils.getPossibleChild(graph, resource, name); } + @Deprecated public static Resource getPossibleChild(ReadGraph graph, Resource resource, Resource type, String name) throws DatabaseException { - Resource child = graph.sync(new PossibleChild(resource, name)); - if(child == null) return null; - if(!graph.isInstanceOf(child, type)) return null; - return child; + return CommonDBUtils.getPossibleChild(graph, resource, type, name); } public static RelationContext relationContext(ReadGraph graph, Resource subject, Resource predicate) throws DatabaseException { diff --git a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/RuntimeEnvironmentRequest.java b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/RuntimeEnvironmentRequest.java index 9f6b8fe53..17fbf1e7c 100644 --- a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/RuntimeEnvironmentRequest.java +++ b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/RuntimeEnvironmentRequest.java @@ -1,19 +1,6 @@ package org.simantics.db.layer0.util; -import org.simantics.db.ReadGraph; import org.simantics.db.Resource; -import org.simantics.db.common.request.ParametrizedPrimitiveRead; -import org.simantics.db.common.request.UnaryRead; -import org.simantics.db.exception.DatabaseException; -import org.simantics.db.layer0.internal.SimanticsInternal; -import org.simantics.db.procedure.Listener; -import org.simantics.db.request.Read; -import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification; -import org.simantics.scl.compiler.module.repository.ImportFailureException; -import org.simantics.scl.compiler.module.repository.UpdateListener; -import org.simantics.scl.compiler.runtime.RuntimeEnvironment; -import org.simantics.scl.osgi.SCLOsgi; -import org.simantics.scl.runtime.SCLContext; /** * Finds the runtime environment of a model or other index root. @@ -21,134 +8,11 @@ import org.simantics.scl.runtime.SCLContext; * @author Hannu Niemistö * @author Antti Villberg */ -public class RuntimeEnvironmentRequest extends UnaryRead { +@Deprecated +public class RuntimeEnvironmentRequest extends org.simantics.db.common.request.RuntimeEnvironmentRequest { public RuntimeEnvironmentRequest(Resource parameter) { super(parameter); } - protected void fillEnvironmentSpecification(EnvironmentSpecification environmentSpecification) { - } - - static class UpdateListenerImpl extends UpdateListener { - - final EnvironmentSpecification environmentSpecification; - final Listener callback; - - UpdateListenerImpl(EnvironmentSpecification environmentSpecification, Listener callback) { - this.environmentSpecification = environmentSpecification; - this.callback = callback; - } - - @Override - public void notifyAboutUpdate() { - if(callback.isDisposed()) { - stopListening(); - return; - } - getRuntimeEnvironment(environmentSpecification, callback, this); - } - }; - - public static void getRuntimeEnvironment(EnvironmentSpecification environmentSpecification, Listener callback, UpdateListenerImpl listener) { - - try { - - SCLContext context = SCLContext.getCurrent(); - - RuntimeEnvironment env; - Object graph = context.get("graph"); - if(graph == null) - try { - env = SimanticsInternal.getSession().syncRequest(new Read() { - @Override - public RuntimeEnvironment perform(ReadGraph graph) throws DatabaseException { - - SCLContext sclContext = SCLContext.getCurrent(); - Object oldGraph = sclContext.get("graph"); - try { - sclContext.put("graph", graph); - return SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment( - environmentSpecification, - callback.getClass().getClassLoader(), listener); - } catch (ImportFailureException e) { - throw new DatabaseException(e); - } catch (Throwable t) { - throw new DatabaseException(t); - } finally { - sclContext.put("graph", oldGraph); - } - } - }); - } catch (DatabaseException e) { - callback.exception(e); - return; - } - else - env = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment( - environmentSpecification, - callback.getClass().getClassLoader(), listener); - callback.execute(env); - } catch (ImportFailureException e) { - callback.exception(new DatabaseException(e)); - } - - } - - @Override - public RuntimeEnvironment perform(ReadGraph graph) - throws DatabaseException { - final EnvironmentSpecification environmentSpecification = EnvironmentSpecification.of( - "Builtin", "", - "StandardLibrary", "", - "Simantics/All", ""); - fillEnvironmentSpecification(environmentSpecification); - - Resource mainModule = Layer0Utils.getPossibleChild(graph, parameter, "SCLMain"); - String mainModuleUri; - if(mainModule != null) { - mainModuleUri = graph.getURI(mainModule); - environmentSpecification.importModule(mainModuleUri, ""); - } - else - mainModuleUri = graph.getURI(parameter) + "/#"; // Add something dummy to the model uri that cannot be in a real URI - - return graph.syncRequest(new ParametrizedPrimitiveRead(mainModuleUri) { - - UpdateListenerImpl sclListener; - - @Override - public void register(ReadGraph graph, Listener procedure) { - - SCLContext context = SCLContext.getCurrent(); - Object oldGraph = context.put("graph", graph); - try { - - if(procedure.isDisposed()) { - getRuntimeEnvironment(environmentSpecification, procedure, null); - } else { - sclListener = new UpdateListenerImpl(environmentSpecification, procedure); - sclListener.notifyAboutUpdate(); - } - - } finally { - context.put("graph", oldGraph); - } - - } - - @Override - public void unregistered() { - if(sclListener != null) - sclListener.stopListening(); - } - - }); - } - - @Override - public int hashCode() { - return 31*getClass().hashCode() + super.hashCode(); - } - } diff --git a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/validation/ValidationUtils.java b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/validation/ValidationUtils.java index 673eeaee5..47c829cd8 100644 --- a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/validation/ValidationUtils.java +++ b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/validation/ValidationUtils.java @@ -1,7 +1,6 @@ package org.simantics.db.layer0.validation; -import gnu.trove.set.hash.THashSet; - +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; @@ -18,6 +17,8 @@ import org.simantics.db.layer0.util.DomainProcessor3; import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest; import org.simantics.layer0.Layer0; +import gnu.trove.set.hash.THashSet; + public class ValidationUtils { /** @@ -62,7 +63,7 @@ public class ValidationUtils { return validateConstraints(graph, r, null); } - public static Set validateConstraintsForDomain(ReadGraph graph, Resource r) throws DatabaseException { + public static List validateConstraintsForDomain(ReadGraph graph, Resource r) throws DatabaseException { Set result = null; DomainProcessor3 dp = ModelTransferableGraphSourceRequest.getDomainOnly(graph, null, r); @@ -75,7 +76,7 @@ public class ValidationUtils { } } - return result != null ? result : Collections.emptySet(); + return result != null ? new ArrayList(result) : Collections.emptyList(); } } diff --git a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/variable/StandardGraphPropertyVariable.java b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/variable/StandardGraphPropertyVariable.java index 9b0befc78..ed58556c7 100644 --- a/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/variable/StandardGraphPropertyVariable.java +++ b/bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/variable/StandardGraphPropertyVariable.java @@ -11,6 +11,7 @@ import org.simantics.databoard.accessor.reference.ChildReference; import org.simantics.databoard.binding.Binding; import org.simantics.databoard.binding.impl.ObjectVariantBinding; import org.simantics.databoard.type.Datatype; +import org.simantics.db.DevelopmentKeys; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; @@ -19,7 +20,6 @@ import org.simantics.db.common.validation.L0Validations; import org.simantics.db.exception.DatabaseException; import org.simantics.db.exception.DatatypeNotFoundException; import org.simantics.db.exception.ValidationException; -import org.simantics.db.exception.VariableException; import org.simantics.db.layer0.exception.InvalidVariableException; import org.simantics.db.layer0.exception.MissingVariableValueException; import org.simantics.db.layer0.exception.PendingVariableException; @@ -122,10 +122,12 @@ public class StandardGraphPropertyVariable extends AbstractPropertyVariable { public T getValue(ReadGraph graph) throws DatabaseException { if(Development.DEVELOPMENT) { - String error = L0Validations.checkValueType(graph, parentResource, property.predicate); - if(error != null) { - LOGGER.error(error); - //throw new ValidationException(error); + if(Development.getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) { + String error = L0Validations.checkValueType(graph, parentResource, property.predicate); + if(error != null) { + LOGGER.error(error); + throw new ValidationException(error); + } } } @@ -141,10 +143,12 @@ public class StandardGraphPropertyVariable extends AbstractPropertyVariable { return getValue(graph); if(Development.DEVELOPMENT) { - String error = L0Validations.checkValueType(graph, parentResource, property.predicate); - if(error != null) { - LOGGER.error(error); - throw new ValidationException(error); + if(Development.getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) { + String error = L0Validations.checkValueType(graph, parentResource, property.predicate); + if(error != null) { + LOGGER.error(error); + throw new ValidationException(error); + } } } @@ -180,10 +184,12 @@ public class StandardGraphPropertyVariable extends AbstractPropertyVariable { public void setValue(WriteGraph graph, Object value, Binding binding) throws DatabaseException { if(Development.DEVELOPMENT) { - String error = L0Validations.checkValueType(graph, parentResource, property.predicate); - if(error != null) { - LOGGER.error(error); - //throw new ValidationException(error); + if(Development.getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) { + String error = L0Validations.checkValueType(graph, parentResource, property.predicate); + if(error != null) { + LOGGER.error(error); + throw new ValidationException(error); + } } } @@ -195,10 +201,12 @@ public class StandardGraphPropertyVariable extends AbstractPropertyVariable { public void setValue(WriteGraph graph, Object value) throws DatabaseException { if(Development.DEVELOPMENT) { - String error = L0Validations.checkValueType(graph, parentResource, property.predicate); - if(error != null) { - LOGGER.error(error); - throw new ValidationException(error); + if(Development.getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) { + String error = L0Validations.checkValueType(graph, parentResource, property.predicate); + if(error != null) { + LOGGER.error(error); + throw new ValidationException(error); + } } } diff --git a/bundles/org.simantics.db.management/META-INF/MANIFEST.MF b/bundles/org.simantics.db.management/META-INF/MANIFEST.MF index ecf2439e8..75fdb8b6f 100644 --- a/bundles/org.simantics.db.management/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.db.management/META-INF/MANIFEST.MF @@ -5,9 +5,9 @@ Bundle-SymbolicName: org.simantics.db.management Bundle-Version: 1.1.0.qualifier Bundle-Activator: org.simantics.db.management.internal.Activator Bundle-Vendor: VTT Technical Research Centre of Finland -Require-Bundle: org.simantics.db.services;bundle-version="0.8.0", - org.simantics.db.procore;bundle-version="0.8.0", - org.eclipse.core.runtime;bundle-version="3.5.0" +Require-Bundle: org.eclipse.core.runtime;bundle-version="3.5.0", + org.simantics.utils;bundle-version="1.1.0", + org.simantics.layer0;bundle-version="1.1.0" Bundle-ActivationPolicy: lazy Export-Package: org.simantics.db.management, org.simantics.db.management.discovery diff --git a/bundles/org.simantics.db.management/src/org/simantics/db/management/SessionContext.java b/bundles/org.simantics.db.management/src/org/simantics/db/management/SessionContext.java index dae8bea75..88293f42b 100644 --- a/bundles/org.simantics.db.management/src/org/simantics/db/management/SessionContext.java +++ b/bundles/org.simantics.db.management/src/org/simantics/db/management/SessionContext.java @@ -16,19 +16,14 @@ import java.util.Arrays; import java.util.UUID; import java.util.concurrent.TimeoutException; -import org.eclipse.core.runtime.IStatus; import org.simantics.db.Disposable; import org.simantics.db.ReadGraph; import org.simantics.db.Session; import org.simantics.db.VirtualGraph; -import org.simantics.db.common.processor.MergingDelayedWriteProcessor; -import org.simantics.db.common.processor.MergingGraphRequestProcessor; -import org.simantics.db.common.request.ReadRequest; import org.simantics.db.exception.DatabaseException; -import org.simantics.db.management.internal.Activator; +import org.simantics.db.request.Read; import org.simantics.db.service.LifecycleSupport; import org.simantics.db.service.VirtualGraphSupport; -import org.simantics.db.services.GlobalServiceInitializer; import org.simantics.layer0.Layer0; import org.simantics.utils.datastructures.disposable.DisposeState; import org.simantics.utils.datastructures.disposable.IDisposable; @@ -46,16 +41,11 @@ import org.simantics.utils.threads.SyncListenerList; * @author Tuukka Lehtonen */ public class SessionContext extends HintContext implements ISessionContext, Disposable { - private static final boolean SESSION_DEBUG = false; -// private final IServerAddress address; + private static final boolean SESSION_DEBUG = false; private Session session; - private boolean servicesRegistered = false; - - private IStatus servicesRegisteredStatus = null; - public static SessionContext create(Session session, boolean initialize) throws DatabaseException { return new SessionContext(session, initialize); } @@ -67,40 +57,21 @@ public class SessionContext extends HintContext implements ISessionContext, Disp } private void initializeSession(Session s) throws DatabaseException { - s.registerService(MergingGraphRequestProcessor.class, new MergingGraphRequestProcessor("SessionService", s, 20)); - s.registerService(MergingDelayedWriteProcessor.class, new MergingDelayedWriteProcessor(s, 20)); s.registerService(VirtualGraph.class, s.getService(VirtualGraphSupport.class).getMemoryPersistent(UUID.randomUUID().toString())); // Builtins needs to be initialized for the new session before // anything useful can be done with it. - s.syncRequest(new ReadRequest() { + s.syncRequest(new Read() { @Override - public void run(ReadGraph g) { + public Object perform(ReadGraph g) { // Registers Builtins with the ServiceLocator of the Graph's session. Layer0.getInstance(g); + return null; } }); + } - public void registerServices() { - if (servicesRegistered) - return; - - // Register any services available for the SessionLocator of the new - // Session. - servicesRegisteredStatus = new GlobalServiceInitializer().initialize(session); - if (!servicesRegisteredStatus.isOK()) { - Activator.getDefault().getLog().log(servicesRegisteredStatus); - } - - servicesRegistered = true; - } - -// @Override -// public IServerAddress getAddress() { -// return address; -// } - @Override public Session getSession() { if (session == null) diff --git a/bundles/org.simantics.db.management/src/org/simantics/db/management/internal/SessionManagerProvider.java b/bundles/org.simantics.db.management/src/org/simantics/db/management/internal/SessionManagerProvider.java deleted file mode 100644 index 81967124d..000000000 --- a/bundles/org.simantics.db.management/src/org/simantics/db/management/internal/SessionManagerProvider.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2011 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.management.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Properties; - -import org.eclipse.core.runtime.Platform; -import org.osgi.framework.Bundle; -import org.simantics.db.SessionManager; -import org.simantics.utils.FileUtils; - -import fi.vtt.simantics.procore.SessionManagerSource; - -/** - * Complete hack for the time being. Simply provides the SessionManager behind - * procore's SessionManagerSource with proper initialization. - */ -public final class SessionManagerProvider { - - // TODO: move this into BundleContext as a service ? - private static SessionManagerProvider provider; - - private SessionManager sessionManager; - - public static SessionManagerProvider getInstance() { - if (provider == null) - provider = new SessionManagerProvider(); - return provider; - } - - public SessionManager getSessionManager() throws IOException { - if (sessionManager == null) { - sessionManager = SessionManagerSource.getSessionManager(loadProperties()); - } - return sessionManager; - } - - private Properties loadProperties() { - Bundle procore = Platform.getBundle("org.simantics.db.procore"); - URL url = procore.getResource("log4j.properties"); - if (url != null) { - InputStream in = null; - try { - in = url.openStream(); - Properties props = new Properties(); - props.load(in); - return props; - } catch (Exception e) { - } finally { - FileUtils.uncheckedClose(in); - } - } - return null; - } - -} diff --git a/bundles/org.simantics.db.procore.server.environment/.classpath b/bundles/org.simantics.db.procore.server.environment/.classpath deleted file mode 100644 index eca7bdba8..000000000 --- a/bundles/org.simantics.db.procore.server.environment/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/bundles/org.simantics.db.procore.server.environment/.project b/bundles/org.simantics.db.procore.server.environment/.project deleted file mode 100644 index 4a0c12be4..000000000 --- a/bundles/org.simantics.db.procore.server.environment/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - org.simantics.db.procore.server.environment - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.pde.ManifestBuilder - - - - - org.eclipse.pde.SchemaBuilder - - - - - - org.eclipse.pde.PluginNature - org.eclipse.jdt.core.javanature - - diff --git a/bundles/org.simantics.db.procore.server.environment/.settings/org.eclipse.jdt.core.prefs b/bundles/org.simantics.db.procore.server.environment/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 0c68a61dc..000000000 --- a/bundles/org.simantics.db.procore.server.environment/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,7 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/bundles/org.simantics.db.procore.server.environment/META-INF/MANIFEST.MF b/bundles/org.simantics.db.procore.server.environment/META-INF/MANIFEST.MF deleted file mode 100644 index af12d597a..000000000 --- a/bundles/org.simantics.db.procore.server.environment/META-INF/MANIFEST.MF +++ /dev/null @@ -1,16 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: ProCore Database Server Environment Checking Utilities -Bundle-SymbolicName: org.simantics.db.procore.server.environment -Bundle-Version: 1.1.0.qualifier -Bundle-RequiredExecutionEnvironment: JavaSE-1.8 -Export-Package: org.simantics.db.procore.server.environment, - org.simantics.db.procore.server.environment.windows -Bundle-Vendor: Semantum Oy -Require-Bundle: org.eclipse.core.runtime;bundle-version="3.6.0" -Bundle-NativeCode: msijni.dll; - processor=x86; osname=win32, - msijni64.dll; - processor=x86_64; osname=win32, - * -Automatic-Module-Name: org.simantics.db.procore.server.environment diff --git a/bundles/org.simantics.db.procore.server.environment/VC90.2008.SP1.KB2467174.redist.x64.exe b/bundles/org.simantics.db.procore.server.environment/VC90.2008.SP1.KB2467174.redist.x64.exe deleted file mode 100644 index 5ecef5ec5..000000000 Binary files a/bundles/org.simantics.db.procore.server.environment/VC90.2008.SP1.KB2467174.redist.x64.exe and /dev/null differ diff --git a/bundles/org.simantics.db.procore.server.environment/VC90.2008.SP1.KB2467174.redist.x86.exe b/bundles/org.simantics.db.procore.server.environment/VC90.2008.SP1.KB2467174.redist.x86.exe deleted file mode 100644 index 823345da7..000000000 Binary files a/bundles/org.simantics.db.procore.server.environment/VC90.2008.SP1.KB2467174.redist.x86.exe and /dev/null differ diff --git a/bundles/org.simantics.db.procore.server.environment/build.properties b/bundles/org.simantics.db.procore.server.environment/build.properties deleted file mode 100644 index a64b63b7b..000000000 --- a/bundles/org.simantics.db.procore.server.environment/build.properties +++ /dev/null @@ -1,20 +0,0 @@ -############################################################################### -# Copyright (c) 2007, 2010 Association for Decentralized Information Management -# in Industry THTH ry. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# VTT Technical Research Centre of Finland - initial API and implementation -############################################################################### -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - msijni.dll,\ - msijni64.dll,\ - VC90.2008.SP1.KB2467174.redist.x64.exe,\ - VC90.2008.SP1.KB2467174.redist.x86.exe -src.includes = native/ diff --git a/bundles/org.simantics.db.procore.server.environment/msijni.dll b/bundles/org.simantics.db.procore.server.environment/msijni.dll deleted file mode 100644 index 8009884ed..000000000 Binary files a/bundles/org.simantics.db.procore.server.environment/msijni.dll and /dev/null differ diff --git a/bundles/org.simantics.db.procore.server.environment/msijni64.dll b/bundles/org.simantics.db.procore.server.environment/msijni64.dll deleted file mode 100644 index df7497910..000000000 Binary files a/bundles/org.simantics.db.procore.server.environment/msijni64.dll and /dev/null differ diff --git a/bundles/org.simantics.db.procore.server.environment/native/compile.bat b/bundles/org.simantics.db.procore.server.environment/native/compile.bat deleted file mode 100644 index 47efc2f66..000000000 --- a/bundles/org.simantics.db.procore.server.environment/native/compile.bat +++ /dev/null @@ -1,12 +0,0 @@ -@rem *************************************************************************** -@rem Copyright (c) 2007, 2010 Association for Decentralized Information Management -@rem in Industry THTH ry. -@rem All rights reserved. This program and the accompanying materials -@rem are made available under the terms of the Eclipse Public License v1.0 -@rem which accompanies this distribution, and is available at -@rem http://www.eclipse.org/legal/epl-v10.html -@rem -@rem Contributors: -@rem VTT Technical Research Centre of Finland - initial API and implementation -@rem *************************************************************************** -gcc -mno-cygwin "-I%JAVA_HOME%/include" "-I%JAVA_HOME%/include/win32" -Wl,--add-stdcall-alias -shared -o ../msijni.dll msijni.c diff --git a/bundles/org.simantics.db.procore.server.environment/native/compile.sh b/bundles/org.simantics.db.procore.server.environment/native/compile.sh deleted file mode 100644 index aa239f6be..000000000 --- a/bundles/org.simantics.db.procore.server.environment/native/compile.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh - -# *************************************************************************** -# Copyright (c) 2007, 2010 Association for Decentralized Information Management -# in Industry THTH ry. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# VTT Technical Research Centre of Finland - initial API and implementation -# *************************************************************************** - -gcc "-I%JAVA_HOME%/include" "-I%JAVA_HOME%/include/win32" -Wl,--add-stdcall-alias -shared -o ../msijni.dll msijni.c diff --git a/bundles/org.simantics.db.procore.server.environment/native/compile_x64.bat b/bundles/org.simantics.db.procore.server.environment/native/compile_x64.bat deleted file mode 100644 index 0a34900dc..000000000 --- a/bundles/org.simantics.db.procore.server.environment/native/compile_x64.bat +++ /dev/null @@ -1,13 +0,0 @@ -@rem *************************************************************************** -@rem Copyright (c) 2007, 2010 Association for Decentralized Information Management -@rem in Industry THTH ry. -@rem All rights reserved. This program and the accompanying materials -@rem are made available under the terms of the Eclipse Public License v1.0 -@rem which accompanies this distribution, and is available at -@rem http://www.eclipse.org/legal/epl-v10.html -@rem -@rem Contributors: -@rem VTT Technical Research Centre of Finland - initial API and implementation -@rem *************************************************************************** -cl /O2 /Oi /GL "-I%JAVA_HOME%/include" "-I%JAVA_HOME%/include/win32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_USRDLL" /D "MSIJNI_EXPORTS" /D "_WINDLL" /D "_UNICODE" /D "UNICODE" /LD /FD /Gy /W3 /nologo /c /Zi /TC /errorReport:prompt /Fomsijni.obj msijni.c -link /OUT:"..\src\msijni64.dll" /DLL /MACHINE:X64 Msi.lib msijni.obj diff --git a/bundles/org.simantics.db.procore.server.environment/native/compile_x86.bat b/bundles/org.simantics.db.procore.server.environment/native/compile_x86.bat deleted file mode 100644 index fab911fc8..000000000 --- a/bundles/org.simantics.db.procore.server.environment/native/compile_x86.bat +++ /dev/null @@ -1,13 +0,0 @@ -@rem *************************************************************************** -@rem Copyright (c) 2007, 2010 Association for Decentralized Information Management -@rem in Industry THTH ry. -@rem All rights reserved. This program and the accompanying materials -@rem are made available under the terms of the Eclipse Public License v1.0 -@rem which accompanies this distribution, and is available at -@rem http://www.eclipse.org/legal/epl-v10.html -@rem -@rem Contributors: -@rem VTT Technical Research Centre of Finland - initial API and implementation -@rem *************************************************************************** -cl /O2 /Oi /GL "-I%JAVA_HOME%/include" "-I%JAVA_HOME%/include/win32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_USRDLL" /D "MSIJNI_EXPORTS" /D "_WINDLL" /D "_UNICODE" /D "UNICODE" /LD /FD /Gy /W3 /nologo /c /Zi /TC /errorReport:prompt /Fomsijni.obj msijni.c -link /OUT:"..\src\msijni.dll" /DLL /MACHINE:X86 Msi.lib msijni.obj diff --git a/bundles/org.simantics.db.procore.server.environment/native/msijni.c b/bundles/org.simantics.db.procore.server.environment/native/msijni.c deleted file mode 100644 index fe60d35a1..000000000 --- a/bundles/org.simantics.db.procore.server.environment/native/msijni.c +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -#define WIN32_LEAN_AND_MEAN -#include -#include -#include "jni.h" - -JNIEXPORT jint JNICALL Java_org_simantics_db_procore_server_environment_windows_Msi_MsiQueryProductState0( - JNIEnv* env, jclass clazz, jstring productCode -) { - int result; - const jchar* lpProductCode; - - lpProductCode = (*env)->GetStringChars(env, productCode, NULL); - if (lpProductCode == 0) - return 0; - - result = MsiQueryProductState((LPCTSTR) lpProductCode); - - (*env)->ReleaseStringChars(env, productCode, lpProductCode); - - return (jint) result; -} diff --git a/bundles/org.simantics.db.procore.server.environment/native/vs2008/msijni.sln b/bundles/org.simantics.db.procore.server.environment/native/vs2008/msijni.sln deleted file mode 100644 index ddbe9d1c0..000000000 --- a/bundles/org.simantics.db.procore.server.environment/native/vs2008/msijni.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "msijni", "msijni.vcproj", "{2C249AD2-A0AE-4A88-8DCD-71F96133690E}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2C249AD2-A0AE-4A88-8DCD-71F96133690E}.Debug|Win32.ActiveCfg = Debug|Win32 - {2C249AD2-A0AE-4A88-8DCD-71F96133690E}.Debug|Win32.Build.0 = Debug|Win32 - {2C249AD2-A0AE-4A88-8DCD-71F96133690E}.Debug|x64.ActiveCfg = Debug|x64 - {2C249AD2-A0AE-4A88-8DCD-71F96133690E}.Debug|x64.Build.0 = Debug|x64 - {2C249AD2-A0AE-4A88-8DCD-71F96133690E}.Release|Win32.ActiveCfg = Release|Win32 - {2C249AD2-A0AE-4A88-8DCD-71F96133690E}.Release|Win32.Build.0 = Release|Win32 - {2C249AD2-A0AE-4A88-8DCD-71F96133690E}.Release|x64.ActiveCfg = Release|x64 - {2C249AD2-A0AE-4A88-8DCD-71F96133690E}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/bundles/org.simantics.db.procore.server.environment/native/vs2008/msijni.vcproj b/bundles/org.simantics.db.procore.server.environment/native/vs2008/msijni.vcproj deleted file mode 100644 index cec55e0d3..000000000 --- a/bundles/org.simantics.db.procore.server.environment/native/vs2008/msijni.vcproj +++ /dev/null @@ -1,354 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ARCHType.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ARCHType.java deleted file mode 100644 index 67fbee589..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ARCHType.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment; - -/** - * @author Tuukka Lehtonen - */ -public enum ARCHType { - PPC, PPC_64, SPARC, X86, X86_64, UNKNOWN -} \ No newline at end of file diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ExecutionEnvironment.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ExecutionEnvironment.java deleted file mode 100644 index 10831342a..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ExecutionEnvironment.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment; - - -/** - * @author Tuukka Lehtonen - */ -public final class ExecutionEnvironment { - - public final OSType os; - public final ARCHType arch; - - private ExecutionEnvironment(OSType os, ARCHType arch) { - this.os = os; - this.arch = arch; - } - - public static ExecutionEnvironment calculate() { - return new ExecutionEnvironment(calculateOS(), calculateArch()); - } - - public static ARCHType calculateArch() { - String osArch = System.getProperty("os.arch", ""); - osArch = osArch.toLowerCase(); - if (osArch.equals("i386") || osArch.equals("i586") || osArch.equals("i686") || osArch.equals("x86")) - return ARCHType.X86; - if (osArch.startsWith("amd64") || osArch.startsWith("x86_64")) - return ARCHType.X86_64; - if (osArch.equals("ppc")) - return ARCHType.PPC; - if (osArch.startsWith("ppc")) - return ARCHType.PPC_64; - if (osArch.startsWith("sparc")) - return ARCHType.SPARC; - return ARCHType.UNKNOWN; - } - - public static OSType calculateOS() { - String osName = System.getProperty("os.name", ""); - osName = osName.toLowerCase(); - if (osName.startsWith("mac os x")) - return OSType.APPLE; - if (osName.startsWith("windows")) - return OSType.WINDOWS; - if (osName.startsWith("linux")) - return OSType.LINUX; - if (osName.startsWith("sun")) - return OSType.SUN; - return OSType.UNKNOWN; - } - -} diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ExecutionEnvironmentException.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ExecutionEnvironmentException.java deleted file mode 100644 index 5630a0914..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ExecutionEnvironmentException.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment; - -import java.util.List; - -import org.simantics.db.procore.server.environment.windows.Product; - - -/** - * @author Tuukka Lehtonen - */ -public class ExecutionEnvironmentException extends Exception { - - private static final long serialVersionUID = -4189715696439554271L; - - public List requiredProducts; - - public ExecutionEnvironmentException(List requiredProducts) { - super(); - this.requiredProducts = requiredProducts; - } - - public ExecutionEnvironmentException(String message, List requiredProducts) { - super(message); - this.requiredProducts = requiredProducts; - } - -} diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/InstallException.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/InstallException.java deleted file mode 100644 index 8dd0caa39..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/InstallException.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment; - -import java.util.List; - -import org.simantics.db.procore.server.environment.windows.Product; - - -/** - * @author Tuukka Lehtonen - */ -public class InstallException extends Exception { - - private static final long serialVersionUID = -4189715696439554271L; - - public List products; - - public InstallException(List products) { - super(); - this.products = products; - } - - public InstallException(String message, List products) { - super(message); - this.products = products; - } - - public InstallException(Throwable cause, List products) { - super(cause); - this.products = products; - } - - public InstallException(String message, Throwable cause, List products) { - super(message, cause); - this.products = products; - } - -} diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/OSType.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/OSType.java deleted file mode 100644 index 8b9009548..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/OSType.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment; - -/** - * @author Tuukka Lehtonen - */ -public enum OSType { - APPLE, LINUX, SUN, WINDOWS, UNKNOWN -} \ No newline at end of file diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/RebootRequiredException.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/RebootRequiredException.java deleted file mode 100644 index df7b0f4a1..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/RebootRequiredException.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment; - -import java.util.List; - -import org.simantics.db.procore.server.environment.windows.Product; - - -/** - * @author Tuukka Lehtonen - */ -public class RebootRequiredException extends InstallException { - - private static final long serialVersionUID = -4189715696439554271L; - - public RebootRequiredException(List success) { - super(success); - } - -} diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ServerEnvironment.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ServerEnvironment.java deleted file mode 100644 index 5de87a27e..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/ServerEnvironment.java +++ /dev/null @@ -1,129 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.Arrays; - -import org.eclipse.core.runtime.FileLocator; -import org.eclipse.core.runtime.IProgressMonitor; -import org.simantics.db.procore.server.environment.windows.Msi; -import org.simantics.db.procore.server.environment.windows.Product; -import org.simantics.db.procore.server.environment.windows.ProductCodes; - -/** - * @author Tuukka Lehtonen - */ -public final class ServerEnvironment { - - // http://msdn.microsoft.com/en-us/library/aa368542(v=vs.85).aspx - private static final int ERROR_SUCCESS = 0; - private static final int ERROR_SUCCESS_REBOOT_REQUIRED = 3010; - - /** - * Checks whether the current running environment has all the necessary - * components installed to run the ProCore database server. - * - * @throws ExecutionEnvironmentException if dependencies for running the - * database server are not met - */ - public static void ensureServerDependenciesMet() throws ExecutionEnvironmentException { - ExecutionEnvironment env = ExecutionEnvironment.calculate(); - switch (env.os) { - case WINDOWS: { - switch (env.arch) { - case X86: - Msi.checkOneOfProductsInstalled(ProductCodes.VISUAL_CPP_2008_SP1_REDIST_X86_KB2467174); - break; - case X86_64: - Msi.checkProductsInstalled(ProductCodes.VISUAL_CPP_2008_SP1_REDIST_X86_KB2467174, ProductCodes.VISUAL_CPP_2008_SP1_REDIST_X64_KB2467174); - break; - } - break; - } - } - } - - /** - * Checks whether the current running environment has all the necessary - * components installed to run the ProCore database server. - * - * @throws ExecutionEnvironmentException if dependencies for running the - * database server are not met - */ - public static void tryInstallDependencies(IProgressMonitor monitor) throws InstallException { - ExecutionEnvironment env = ExecutionEnvironment.calculate(); - switch (env.os) { - case WINDOWS: { - switch (env.arch) { - case X86: - runInstaller(monitor, ProductCodes.VISUAL_CPP_2008_SP1_REDIST_X86_KB2467174, "VC90.2008.SP1.KB2467174.redist.x86.exe"); - break; - case X86_64: - runInstaller(monitor, ProductCodes.VISUAL_CPP_2008_SP1_REDIST_X86_KB2467174, "VC90.2008.SP1.KB2467174.redist.x86.exe"); - runInstaller(monitor, ProductCodes.VISUAL_CPP_2008_SP1_REDIST_X64_KB2467174, "VC90.2008.SP1.KB2467174.redist.x64.exe"); - break; - } - break; - } - } - } - - private static void runInstaller(IProgressMonitor monitor, Product product, String installerPath) throws InstallException { - try { - URL url = FileLocator.find(new URL("platform:/plugin/org.simantics.db.procore.server.environment/" + installerPath)); - URL fileUrl = FileLocator.toFileURL(url); - final File file = new File(fileUrl.getFile()); - System.out.println(file); - - Process installer = new ProcessBuilder("cmd.exe", "/C", file.toString(), "/qb").start(); - while (true) { - try { - int exitValue = installer.exitValue(); - //System.out.println("installation done, exit code: " + exitValue); - switch (exitValue) { - case ERROR_SUCCESS: - return; - case ERROR_SUCCESS_REBOOT_REQUIRED: - throw new RebootRequiredException(Arrays.asList(product)); - } - throw new InstallException("Installation of " + product.getDescription() + " failed with error code " + exitValue, Arrays.asList(product)); - } catch (IllegalThreadStateException e) { -// if (monitor.isCanceled()) { -// installer.destroy(); -// } - // Not done yet. - try { - //System.out.println("sleeping"); - Thread.sleep(250); - } catch (InterruptedException ie) { - } - } - } - } catch (IOException e) { - throw new InstallException(e, Arrays.asList(product)); - } - } - - // ------------------------------------------------------------------------- - - public static void main(String[] args) { - try { - ensureServerDependenciesMet(); - } catch (ExecutionEnvironmentException e) { - e.printStackTrace(); - } - } - -} diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/Msi.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/Msi.java deleted file mode 100644 index 19a55c494..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/Msi.java +++ /dev/null @@ -1,245 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment.windows; - -import java.io.Closeable; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLDecoder; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; - -import org.simantics.db.procore.server.environment.ExecutionEnvironment; -import org.simantics.db.procore.server.environment.ExecutionEnvironmentException; - -/** - * Provides Java access to Windows Msi API functions: - *
    - *
  • {@link #MsiQueryProductState(String)} (see MSDN)
  • - *
- * - * @author Tuukka Lehtonen - */ -public class Msi { - - public static void checkOneOfProductsInstalled(Product... products) throws ExecutionEnvironmentException { - StringBuilder sb = new StringBuilder(); - sb.append("None of the following products are installed properly:\n"); - for (Product product : products) { - ProductState state = Msi.MsiQueryProductState(product.getCode()); - switch (state) { - case DEFAULT: - // One of the listed products is installed OK. - return; - default: - sb.append("\t" + product); - sb.append(" - MsiQueryProductState returned "); - sb.append(state); - sb.append("\n"); - } - } - throw new ExecutionEnvironmentException("Cannot run ProCore database server in this environment due to the following problems:\n" + sb.toString(), Arrays.asList(products)); - } - - public static void checkProductsInstalled(Product... products) throws ExecutionEnvironmentException { - StringBuilder sb = new StringBuilder(); - for (Product product : products) { - ProductState state = Msi.MsiQueryProductState(product.getCode()); - switch (state) { - case DEFAULT: - // Installed OK - continue; - default: - sb.append("\tProduct " + product + " is not installed properly, MsiQueryProductState returned " + state); - sb.append("\n"); - } - } - if (sb.length() > 0) { - // Something is not installed right, throw exception - throw new ExecutionEnvironmentException("Cannot run ProCore database server in this environment due to the following problems:\n" + sb.toString(), Arrays.asList(products)); - } - } - - // ------------------------------------------------------------------------- - - public static ProductState MsiQueryProductState(String productCode) { - int result = MsiQueryProductState0(productCode); - return ProductState.of(result); - } - - private static native int MsiQueryProductState0(String productCode); - - // ------------------------------------------------------------------------- - - private static final String DLL_NAME = "msijni.dll"; - private static final String DLL_NAME_64 = "msijni64.dll"; - - static { - initialize(); - } - - private static void initialize() { - ExecutionEnvironment env = ExecutionEnvironment.calculate(); - String libName = null; - switch (env.arch) { - case X86: - libName = DLL_NAME; - break; - case X86_64: - libName = DLL_NAME_64; - break; - default: - return; - } - - URL libURL = Msi.class.getResource("/" + libName); - if (libURL != null) { - try { - if ("file".equals(libURL.getProtocol())) { - File path = new File(URLDecoder.decode(libURL.getPath(), "UTF-8")); - initialize(path); - } else { - File libFile = extractLib(libURL, libName); - initialize(libFile); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - private static void initialize(File path) { - //System.out.println("load msijni: " + path); - System.load(path.toString()); - } - - /** - * Extracts the specified source file in the specified bundle into the - * specified local directory. - * - * @param url the source URL to stream the resource from - * @param targetFile the target file to write the resource to - * @param deleteOnExit true to use {@link File#deleteOnExit()} - * on the resulting file. Note that this does not guarantee that the - * file is deleted when the JVM exits - * @return the resulting file - * @throws FileNotFoundException - */ - private static File copyResource(URL url, File targetFile) throws IOException, FileNotFoundException { - FileOutputStream os = null; - InputStream is = null; - try { - if (targetFile.exists()) - targetFile.delete(); - - is = url.openStream(); - int read; - byte [] buffer = new byte [16384]; - os = new FileOutputStream (targetFile); - while ((read = is.read (buffer)) != -1) { - os.write(buffer, 0, read); - } - os.close (); - is.close (); - - return targetFile; - } finally { - uncheckedClose(os); - uncheckedClose(is); - } - } - - - private static void uncheckedClose(Closeable closeable) { - try { - if (closeable != null) - closeable.close(); - } catch (IOException e) { - //ignore - } - } - - private static File extractLib(URL libURL, String libName) throws FileNotFoundException, IOException { - String tmpDirStr = System.getProperty("java.io.tmpdir"); - if (tmpDirStr == null) - throw new NullPointerException("java.io.tmpdir property is null"); - File tmpDir = new File(tmpDirStr); - File libFile = new File(tmpDir, libName); - - if (libFile.exists()) { - if (libFile.isFile()) { - try { - byte[] origSum = computeSum(libURL); - byte[] targetSum = computeSum(libFile); - if (Arrays.equals(origSum, targetSum)) - return libFile; - } catch (NoSuchAlgorithmException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - return copyResource(libURL, libFile); - } - - public static byte[] computeSum(InputStream in) throws IOException { - if (in == null) - throw new IllegalArgumentException("Input cannot be null!"); - - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - byte[] data = new byte[64 * 1024]; - - while (true) { - int read = in.read(data); - if (read == -1) { - return md.digest(); - } - md.update(data, 0, read); - } - } catch (NoSuchAlgorithmException e) { - // Should not be possible for MD5 - throw new IOException(e); - } - } - - public static byte[] computeSum(File f) throws IOException, NoSuchAlgorithmException { - InputStream in = null; - try { - in = new FileInputStream(f); - return computeSum(in); - } finally { - if (in != null) - in.close(); - } - } - - public static byte[] computeSum(URL url) throws IOException, NoSuchAlgorithmException { - InputStream in = null; - try { - in = url.openStream(); - return computeSum(in); - } finally { - if (in != null) - in.close(); - } - } - -} \ No newline at end of file diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/Product.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/Product.java deleted file mode 100644 index 098dd1d1a..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/Product.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment.windows; - -/** - * @author Tuukka Lehtonen - */ -public class Product { - - private final String code; - private final String description; - - public Product(String code, String description) { - this.code = code; - this.description = description; - } - - public String getCode() { - return code; - } - - public String getDescription() { - return description; - } - - @Override - public String toString() { - return description + " - " + code; - } - -} diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/ProductCodes.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/ProductCodes.java deleted file mode 100644 index 493f4d4cf..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/ProductCodes.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment.windows; - -/** - * @author Tuukka Lehtonen - */ -public final class ProductCodes { - -// // Visual C++ 2008 runtime files -// -// // Visual C++ 2008 Redistributable Package (x86) -// // {FF66E9F6-83E7-3A3E-AF14-8DE9A809A6A4} -// public static final Product VISUAL_CPP_2008_REDIST_X86 = new Product("{FF66E9F6-83E7-3A3E-AF14-8DE9A809A6A4}", -// "Visual C++ 2008 Redistributable Package (x86)"); -// -// // Visual C++ 2008 Redistributable Package (x64) -// // {350AA351-21FA-3270-8B7A-835434E766AD} -// public static final Product VISUAL_CPP_2008_REDIST_X64 = new Product("{350AA351-21FA-3270-8B7A-835434E766AD}", -// "Visual C++ 2008 Redistributable Package (x64)"); -// -// // Visual C++ 2008 Redistributable Package (ia64) -// // {2B547B43-DB50-3139-9EBE-37D419E0F5FA} -// public static final Product VISUAL_CPP_2008_REDIST_IA64 = new Product("{2B547B43-DB50-3139-9EBE-37D419E0F5FA}", -// "Visual C++ 2008 Redistributable Package (ia64)"); - - // Visual C++ 2008 SP1 runtime files - - // THIS ONE IS CURRENTLY USED BY ProCore - - // Visual C++ 2008 SP1 Redistributable Package (x86) - // {9A25302D-30C0-39D9-BD6F-21E6EC160475} - // Date Published: 9/16/2008 - // 9.0.30729.17 - // http://www.microsoft.com/downloads/en/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en - public static final Product VISUAL_CPP_2008_SP1_REDIST_X86 = new Product("{9A25302D-30C0-39D9-BD6F-21E6EC160475}", - "Visual C++ 2008 SP1 Redistributable Package (x86) (v9.0.30729.17)"); - - // Visual C++ 2008 SP1 Redistributable Package (x86) KB2467174 - // {86CE85E6-DBAC-3FFD-B977-E4B79F83C909} - // Date Published: 4/12/2011 - // 9.0.30729.5570 - // http://support.microsoft.com/kb/2467174 - // http://www.microsoft.com/downloads/en/details.aspx?familyid=05ce856d-8128-408b-96fa-5e1f57b097d8&displaylang=en - public static final Product VISUAL_CPP_2008_SP1_REDIST_X86_KB2467174 = new Product("{86CE85E6-DBAC-3FFD-B977-E4B79F83C909}", - "Microsoft Visual C++ 2008 Redistributable - KB2467174 - x86 9.0.30729.5570"); - - // Visual C++ 2008 SP1 Redistributable Package (x64) - // {8220EEFE-38CD-377E-8595-13398D740ACE} - // Date Published: 8/9/2008 - // 9.0.30729.17 - // http://www.microsoft.com/downloads/en/details.aspx?familyid=BA9257CA-337F-4B40-8C14-157CFDFFEE4E&displaylang=en - public static final Product VISUAL_CPP_2008_SP1_REDIST_X64 = new Product("{8220EEFE-38CD-377E-8595-13398D740ACE}", - "Visual C++ 2008 SP1 Redistributable Package (x64) (v9.0.30729.17)"); - - // Visual C++ 2008 SP1 Redistributable Package (x64) KB2467174 - // {8338783A-0968-3B85-AFC7-BAAE0A63DC50} - // Date Published: 4/12/2011 - // 9.0.30729.5570 - // http://support.microsoft.com/kb/2467174 - // http://www.microsoft.com/downloads/en/details.aspx?familyid=05ce856d-8128-408b-96fa-5e1f57b097d8&displaylang=en - public static final Product VISUAL_CPP_2008_SP1_REDIST_X64_KB2467174 = new Product("{8338783A-0968-3B85-AFC7-BAAE0A63DC50}", - "Microsoft Visual C++ 2008 Redistributable - KB2467174 - x64 9.0.30729.5570"); - -// // Visual C++ 2008 SP1 Redistributable Package (ia64) -// // {5827ECE1-AEB0-328E-B813-6FC68622C1F9} -// // Date Published: 8/9/2008 -// // 9.0.30729.17 -// // http://www.microsoft.com/downloads/en/details.aspx?FamilyID=DCC211E6-AB82-41D6-8DEC-C79937393FE8&displaylang=en -// public static final Product VISUAL_CPP_2008_SP1_REDIST_IA64 = new Product("{5827ECE1-AEB0-328E-B813-6FC68622C1F9}", -// "Visual C++ 2008 SP1 Redistributable Package (ia64) (v9.0.30729.17)"); - - // Visual C++ 2010 runtime files - - // Visual C++ 2010 Redistributable Package (x86) - // {196BB40D-1578-3D01-B289-BEFC77A11A1E} - public static final Product VISUAL_CPP_2010_REDIST_X86 = new Product("{196BB40D-1578-3D01-B289-BEFC77A11A1E}", - "Visual C++ 2010 Redistributable Package (x86)"); - - // Visual C++ 2010 Redistributable Package (x64) - // {DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E} - public static final Product VISUAL_CPP_2010_REDIST_X64 = new Product("{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}", - "Visual C++ 2010 Redistributable Package (x64)"); - - // Visual C++ 2010 Redistributable Package (ia64) - // {C1A35166-4301-38E9-BA67-02823AD72A1B} - public static final Product VISUAL_CPP_2010_REDIST_IA64 = new Product("{C1A35166-4301-38E9-BA67-02823AD72A1B}", - "Visual C++ 2010 Redistributable Package (ia64)"); - - // Visual C++ 2010 SP1 runtime files - - // Visual C++ 2010 SP1 Redistributable Package (x86) - // {F0C3E5D1-1ADE-321E-8167-68EF0DE699A5} - public static final Product VISUAL_CPP_2010_SP1_REDIST_X86 = new Product("{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}", - "Visual C++ 2010 SP1 Redistributable Package (x86)"); - - // Visual C++ 2010 SP1 Redistributable Package (x64) - // {1D8E6291-B0D5-35EC-8441-6616F567A0F7} - public static final Product VISUAL_CPP_2010_SP1_REDIST_X64 = new Product("{1D8E6291-B0D5-35EC-8441-6616F567A0F7}", - "Visual C++ 2010 SP1 Redistributable Package (x64)"); - - // Visual C++ 2010 SP1 Redistributable Package (ia64) - // {88C73C1C-2DE5-3B01-AFB8-B46EF4AB41CD} - public static final Product VISUAL_CPP_2010_SP1_REDIST_IA64 = new Product("{88C73C1C-2DE5-3B01-AFB8-B46EF4AB41CD}", - "Visual C++ 2010 SP1 Redistributable Package (ia64)"); - -} diff --git a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/ProductState.java b/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/ProductState.java deleted file mode 100644 index d57199936..000000000 --- a/bundles/org.simantics.db.procore.server.environment/src/org/simantics/db/procore/server/environment/windows/ProductState.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * VTT Technical Research Centre of Finland - initial API and implementation - *******************************************************************************/ -package org.simantics.db.procore.server.environment.windows; - -/** - * The possible return values of Win32 API call MsiQueryProductState enumerated. - * - * @author Tuukka Lehtonen - */ -public enum ProductState { - - /** - * An invalid parameter was passed to the function. - */ - INVALIDARG(-2), - - /** - * The product is not advertised or installed. - */ - UNKNOWN(-1), - - /** - * Indicates invocation of {@link Msi#MsiQueryProductState(String)} failed. - */ - FAILED(0), - - /** - * The product is advertised but not installed. - */ - ADVERTISED(1), - - /** - * The product is installed for a different user. - */ - ABSENT(2), - - /** - * The product is installed for a different user. - */ - DEFAULT(5); - - int code; - - ProductState(int code) { - this.code = code; - } - - public static ProductState of(int code) { - switch (code) { - case -2: return INVALIDARG; - case -1: return UNKNOWN; - case 0: return FAILED; - case 1: return ADVERTISED; - case 2: return ABSENT; - case 5: return DEFAULT; - default: throw new IllegalArgumentException("unrecognized product install state return code: " + code); - } - } - - @Override - public String toString() { - return name() + "(" + code + ")"; - } - -} diff --git a/bundles/org.simantics.db.server/build.properties b/bundles/org.simantics.db.server/build.properties index 9b0a72394..f69fe447b 100644 --- a/bundles/org.simantics.db.server/build.properties +++ b/bundles/org.simantics.db.server/build.properties @@ -12,7 +12,4 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ - .,\ - win32.x86/,\ - win32.x86_64/,\ - linux.x86_64/ + . \ No newline at end of file diff --git a/bundles/org.simantics.db.server/linux.x86_64/ProCoreServer b/bundles/org.simantics.db.server/linux.x86_64/ProCoreServer deleted file mode 100644 index fdfbdc0a3..000000000 Binary files a/bundles/org.simantics.db.server/linux.x86_64/ProCoreServer and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/ACE.dll b/bundles/org.simantics.db.server/win32.x86/ACE.dll deleted file mode 100644 index 5717358e9..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/ACE.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/ProCoreServer.exe b/bundles/org.simantics.db.server/win32.x86/ProCoreServer.exe deleted file mode 100644 index a74c8fdc7..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/ProCoreServer.exe and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/boost_chrono-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86/boost_chrono-vc110-mt-1_55.dll deleted file mode 100644 index 7c3816f1e..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/boost_chrono-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/boost_date_time-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86/boost_date_time-vc110-mt-1_55.dll deleted file mode 100644 index cf0e781a7..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/boost_date_time-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/boost_filesystem-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86/boost_filesystem-vc110-mt-1_55.dll deleted file mode 100644 index 38550ee47..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/boost_filesystem-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/boost_regex-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86/boost_regex-vc110-mt-1_55.dll deleted file mode 100644 index b0caf246c..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/boost_regex-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/boost_system-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86/boost_system-vc110-mt-1_55.dll deleted file mode 100644 index 158ecc9c0..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/boost_system-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/boost_thread-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86/boost_thread-vc110-mt-1_55.dll deleted file mode 100644 index c7112dcb0..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/boost_thread-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/msvcp110.dll b/bundles/org.simantics.db.server/win32.x86/msvcp110.dll deleted file mode 100644 index 93fab5683..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/msvcp110.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86/msvcr110.dll b/bundles/org.simantics.db.server/win32.x86/msvcr110.dll deleted file mode 100644 index 1ce960d75..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86/msvcr110.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/ACE.dll b/bundles/org.simantics.db.server/win32.x86_64/ACE.dll deleted file mode 100644 index 58be406c9..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/ACE.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/ProCoreServer.exe b/bundles/org.simantics.db.server/win32.x86_64/ProCoreServer.exe deleted file mode 100644 index 89b1f7191..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/ProCoreServer.exe and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/boost_chrono-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86_64/boost_chrono-vc110-mt-1_55.dll deleted file mode 100644 index 14fb2741f..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/boost_chrono-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/boost_date_time-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86_64/boost_date_time-vc110-mt-1_55.dll deleted file mode 100644 index fc91104a7..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/boost_date_time-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/boost_filesystem-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86_64/boost_filesystem-vc110-mt-1_55.dll deleted file mode 100644 index 44c8bce76..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/boost_filesystem-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/boost_regex-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86_64/boost_regex-vc110-mt-1_55.dll deleted file mode 100644 index 62938b2d7..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/boost_regex-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/boost_system-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86_64/boost_system-vc110-mt-1_55.dll deleted file mode 100644 index 0e0a2305c..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/boost_system-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/boost_thread-vc110-mt-1_55.dll b/bundles/org.simantics.db.server/win32.x86_64/boost_thread-vc110-mt-1_55.dll deleted file mode 100644 index 3606c30c7..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/boost_thread-vc110-mt-1_55.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/lzo2.dll b/bundles/org.simantics.db.server/win32.x86_64/lzo2.dll deleted file mode 100644 index 1c777649e..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/lzo2.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/msvcp110.dll b/bundles/org.simantics.db.server/win32.x86_64/msvcp110.dll deleted file mode 100644 index 7e278956d..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/msvcp110.dll and /dev/null differ diff --git a/bundles/org.simantics.db.server/win32.x86_64/msvcr110.dll b/bundles/org.simantics.db.server/win32.x86_64/msvcr110.dll deleted file mode 100644 index dd484a588..000000000 Binary files a/bundles/org.simantics.db.server/win32.x86_64/msvcr110.dll and /dev/null differ diff --git a/bundles/org.simantics.db.services/META-INF/MANIFEST.MF b/bundles/org.simantics.db.services/META-INF/MANIFEST.MF index 7403f3d70..bb78bf41e 100644 --- a/bundles/org.simantics.db.services/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.db.services/META-INF/MANIFEST.MF @@ -6,9 +6,13 @@ Bundle-Version: 1.1.0.qualifier Bundle-Vendor: VTT Technical Research Centre of Finland Require-Bundle: org.eclipse.core.runtime, gnu.trove3, - org.simantics.layer0.utils;bundle-version="1.1.0", org.simantics.layer0x.ontology;bundle-version="1.0.0", - org.slf4j.api;bundle-version="1.7.25" + org.slf4j.api;bundle-version="1.7.25", + org.simantics.utils;bundle-version="1.1.0", + org.simantics.db;bundle-version="1.1.0", + org.simantics.scl.reflection, + org.simantics.db.common;bundle-version="1.1.0", + org.simantics.layer0.utils Export-Package: org.simantics.db.services, org.simantics.db.services.activation, org.simantics.db.services.adaption diff --git a/bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/AdapterRegistry2.java b/bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/AdapterRegistry2.java index 578b42a61..fe9bab552 100644 --- a/bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/AdapterRegistry2.java +++ b/bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/AdapterRegistry2.java @@ -36,6 +36,7 @@ import org.simantics.db.adaption.AdapterInstaller; import org.simantics.db.adaption.AdaptionService; import org.simantics.db.common.request.ReadRequest; import org.simantics.db.exception.DatabaseException; +import org.simantics.db.request.Read; import org.simantics.db.services.adaption.reflection.AdaptingDynamicAdapter2; import org.simantics.db.services.adaption.reflection.AtMostOneRelatedResource2; import org.simantics.db.services.adaption.reflection.ConstantAdapter; @@ -337,9 +338,9 @@ public class AdapterRegistry2 { } public void updateAdaptionService(Session s, final AdaptionService service) throws DatabaseException { - s.syncRequest(new ReadRequest() { + s.syncRequest(new Read() { @Override - public void run(ReadGraph g) { + public Object perform(ReadGraph g) { for(AdapterInstaller t : installerSources.keySet()) { try { t.install(g, service); @@ -347,6 +348,7 @@ public class AdapterRegistry2 { AdapterRegistry2.this.handleException(e, t); } } + return null; } }); } diff --git a/bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/reflection/ReflectionAdapter2.java b/bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/reflection/ReflectionAdapter2.java index 187fc5219..42eb3d8be 100644 --- a/bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/reflection/ReflectionAdapter2.java +++ b/bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/reflection/ReflectionAdapter2.java @@ -18,12 +18,16 @@ import java.util.Arrays; import org.simantics.db.AsyncReadGraph; import org.simantics.db.Resource; import org.simantics.db.adaption.Adapter; -import org.simantics.db.common.request.AsyncReadRequest; import org.simantics.db.exception.DatabaseException; import org.simantics.db.procedure.AsyncProcedure; +import org.simantics.db.request.AsyncRead; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ReflectionAdapter2 implements Adapter { + private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionAdapter2.class); + Constructor constructor; IDynamicAdapter2[] parameters; @@ -40,22 +44,20 @@ public class ReflectionAdapter2 implements Adapter { if(parameters.length == 0) { -// System.out.println("ReflectionAdapter2 " + ReflectionAdapter2.this); - try { procedure.execute(g, constructor.newInstance()); } catch (IllegalArgumentException e) { procedure.exception(g, e); - e.printStackTrace(); + LOGGER.error("Unexpected exception during adapter creation", e); } catch (InstantiationException e) { procedure.exception(g, e); - e.printStackTrace(); + LOGGER.error("Unexpected exception during adapter creation", e); } catch (IllegalAccessException e) { procedure.exception(g, e); - e.printStackTrace(); + LOGGER.error("Unexpected exception during adapter creation", e); } catch (InvocationTargetException e) { procedure.exception(g, e.getCause()); - e.getCause().printStackTrace(); + LOGGER.error("Unexpected exception during adapter creation", e.getCause()); } } else if( parameters.length == 1 && parameters[0] instanceof ThisResource2) { @@ -64,49 +66,50 @@ public class ReflectionAdapter2 implements Adapter { procedure.execute(g, constructor.newInstance(r)); } catch (IllegalArgumentException e) { procedure.exception(g, e); - e.printStackTrace(); + LOGGER.error("Unexpected exception during adapter creation", e); } catch (InstantiationException e) { procedure.exception(g, e); - e.printStackTrace(); + LOGGER.error("Unexpected exception during adapter creation", e); } catch (IllegalAccessException e) { procedure.exception(g, e); - e.printStackTrace(); + LOGGER.error("Unexpected exception during adapter creation", e); } catch (InvocationTargetException e) { procedure.exception(g, e.getCause()); - e.getCause().printStackTrace(); + LOGGER.error("Unexpected exception during adapter creation", e.getCause()); } } else { - g.asyncRequest(new AsyncReadRequest() { - + g.asyncRequest(new AsyncRead() { + @Override - public void run(AsyncReadGraph graph) { - + public void perform(AsyncReadGraph graph, AsyncProcedure p) { + Object[] args = new Object[parameters.length]; try { - for(int i=0;i implements Adapter { return "ReflectionAdapter$1" + constructor + "$" + Arrays.toString(parameters); } - }); + }, procedure); } diff --git a/bundles/org.simantics.db.testing/src/org/simantics/db/testing/common/TestHandler.java b/bundles/org.simantics.db.testing/src/org/simantics/db/testing/common/TestHandler.java deleted file mode 100644 index ecda4ccb6..000000000 --- a/bundles/org.simantics.db.testing/src/org/simantics/db/testing/common/TestHandler.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.simantics.db.testing.common; - -import java.io.File; -import java.io.IOException; -import java.util.Properties; - -import org.eclipse.core.runtime.Platform; -import org.simantics.db.Driver; -import org.simantics.db.Driver.Management; -import org.simantics.db.Manager; -import org.simantics.db.ServerI; -import org.simantics.db.Session; -import org.simantics.db.SessionManager; -import org.simantics.db.SessionReference; -import org.simantics.db.exception.DatabaseException; - -import fi.vtt.simantics.procore.ProCoreServerReference; -import fi.vtt.simantics.procore.ProCoreSessionReference; -import fi.vtt.simantics.procore.SessionManagerSource; - -/** - * ProCore specific test handler. - * - */ -public class TestHandler { -// private final TestSettings testSettings; - private final Driver driver; - private final File dbFolder; - TestHandler(TestSettings testSettings, String dbFolderName) throws DatabaseException { -// this.testSettings = testSettings; - driver = Manager.getDriver("procore"); - if (null == dbFolderName) - dbFolder = Platform.getLocation().append("db").toFile(); - else - dbFolder = new File(dbFolderName); - } - void initNew() throws DatabaseException { - Management m = getManagement(); - if (m.exist()) - m.delete(); - m.create(); - } - void initIfNeccessary() throws DatabaseException { - Management m = getManagement(); - if (!m.exist()) - m.create(); - } - public Session getSession() throws DatabaseException { - // Note that we normally user authentication agent for user identification. - Properties props = new Properties(); - props.setProperty("user", "Default User"); - props.setProperty("password", ""); - return driver.getSession(dbFolder.getAbsolutePath(), props); - } - public ServerI getServer() throws DatabaseException { - return driver.getServer(dbFolder.getAbsolutePath(), null); - } - public Management getManagement() throws DatabaseException { - return driver.getManagement(dbFolder.getAbsolutePath(), null); - } - public Session regSession(long sessionId) throws DatabaseException, IOException { - SessionManager sm = SessionManagerSource.getSessionManager(); - ProCoreServerReference ser = new ProCoreServerReference(dbFolder.toPath()); - SessionReference ses = new ProCoreSessionReference(ser, sessionId); - return sm.createSession(ses, null); - } - -} \ No newline at end of file diff --git a/bundles/org.simantics.db/src/org/simantics/db/DevelopmentKeys.java b/bundles/org.simantics.db/src/org/simantics/db/DevelopmentKeys.java index 20ba53e51..7f23b07b8 100644 --- a/bundles/org.simantics.db/src/org/simantics/db/DevelopmentKeys.java +++ b/bundles/org.simantics.db/src/org/simantics/db/DevelopmentKeys.java @@ -5,6 +5,10 @@ import org.simantics.utils.Development; public class DevelopmentKeys { + final public static boolean EVERYTHING = true; + + final public static boolean VERBOSE = false; + final public static String PRINT = "Development.print"; final public static String LOGGER_ECHO = trickToInitialize(); @@ -17,41 +21,69 @@ public class DevelopmentKeys { final public static String WRITELOGGER_LOG = "WriteLogger.log"; + final public static String QUERYPROCESSOR_RECOMPUTE = "QueryProcessor.recompute"; + + final public static String QUERYPROCESSOR_LISTENERS = "QueryProcessor.listeners"; + + final public static String QUERYPROCESSOR_CHANGES = "QueryProcessor.changes"; + final public static String QUERYPROCESSOR_UPDATE = "QueryProcessor.update"; + final public static String QUERYPROCESSOR_DEPENDENCIES = "QueryProcessor.dependencies"; + final public static String QUERYPROCESSOR_PUT = "QueryProcessor.put"; + final public static String QUERYCOLLECTOR = "QueryCollector"; + final public static String SESSION_LOG_WRITES = "Session.logWrites"; final public static String READGRAPH_COUNT = "ReadGraph.count"; + final public static String L0_VALIDATION = "L0.validation"; + + final public static String CACHE_ENTRY_STATE = "CacheEntry.state"; + final public static String CLUSTERTABLE_VALIDATE_ON_LOAD = "ClusterTable.validateOnLoad"; public static void initialize() { if(Development.DEVELOPMENT) { - Development.setProperty(DevelopmentKeys.PRINT, true, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.PRINT, EVERYTHING | false, Bindings.BOOLEAN); + + Development.setProperty(DevelopmentKeys.LOGGER_ECHO, EVERYTHING | false, Bindings.BOOLEAN); + + Development.setProperty(DevelopmentKeys.WRITEGRAPH_DEBUG, EVERYTHING | false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.WRITEGRAPH_DEBUG_NAMES, EVERYTHING | false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.WRITEGRAPH_DEBUG_STACK, EVERYTHING | false, Bindings.BOOLEAN); + + Development.setProperty(DevelopmentKeys.WRITEGRAPH_EXCEPTION_STACKTRACES, EVERYTHING | false, Bindings.BOOLEAN); + + Development.setProperty(DevelopmentKeys.READGRAPH_COUNT, EVERYTHING | false, Bindings.BOOLEAN); + + Development.setProperty(DevelopmentKeys.L0_VALIDATION, false, Bindings.BOOLEAN); + + Development.setProperty(DevelopmentKeys.CACHE_ENTRY_STATE, EVERYTHING | false, Bindings.BOOLEAN); + + Development.setProperty(DevelopmentKeys.WRITELOGGER_LOG, EVERYTHING | false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.LOGGER_ECHO, false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.QUERYPROCESSOR_RECOMPUTE, EVERYTHING | false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.WRITEGRAPH_DEBUG, false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.WRITEGRAPH_DEBUG_NAMES, false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.WRITEGRAPH_DEBUG_STACK, false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, EVERYTHING | false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.WRITEGRAPH_EXCEPTION_STACKTRACES, false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.QUERYPROCESSOR_CHANGES, EVERYTHING | false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.READGRAPH_COUNT, false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, EVERYTHING | false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.WRITELOGGER_LOG, false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.QUERYPROCESSOR_DEPENDENCIES, EVERYTHING | false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.QUERYPROCESSOR_PUT, EVERYTHING | false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.QUERYPROCESSOR_PUT, false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.QUERYCOLLECTOR, EVERYTHING | false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.SESSION_LOG_WRITES, false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.SESSION_LOG_WRITES, EVERYTHING | false, Bindings.BOOLEAN); - Development.setProperty(DevelopmentKeys.CLUSTERTABLE_VALIDATE_ON_LOAD, false, Bindings.BOOLEAN); + Development.setProperty(DevelopmentKeys.CLUSTERTABLE_VALIDATE_ON_LOAD, EVERYTHING | false, Bindings.BOOLEAN); diff --git a/bundles/org.simantics.desktop.ui/src/org/simantics/desktop/ui/internal/StandardModelledView.java b/bundles/org.simantics.desktop.ui/src/org/simantics/desktop/ui/internal/StandardModelledView.java index 689134b84..9bc628d00 100644 --- a/bundles/org.simantics.desktop.ui/src/org/simantics/desktop/ui/internal/StandardModelledView.java +++ b/bundles/org.simantics.desktop.ui/src/org/simantics/desktop/ui/internal/StandardModelledView.java @@ -1,14 +1,20 @@ package org.simantics.desktop.ui.internal; +import java.util.Collections; +import java.util.Set; + +import org.simantics.project.ontology.ProjectResource; import org.simantics.selectionview.StandardPropertyPage; import org.simantics.ui.workbench.IPropertyPage; import org.simantics.views.swt.ModelledView; public class StandardModelledView extends ModelledView { + private static final Set defaultBrowseContexts = Collections.singleton(ProjectResource.URIs.ProjectBrowseContext); + @Override protected IPropertyPage getPropertyPage() { - return new StandardPropertyPage(getSite()); + return new StandardPropertyPage(getSite(), defaultBrowseContexts); } } diff --git a/bundles/org.simantics.document.ui/src/org/simantics/document/ui/actions/NewFileDocument.java b/bundles/org.simantics.document.ui/src/org/simantics/document/ui/actions/NewFileDocument.java index 0ab824e91..783725414 100644 --- a/bundles/org.simantics.document.ui/src/org/simantics/document/ui/actions/NewFileDocument.java +++ b/bundles/org.simantics.document.ui/src/org/simantics/document/ui/actions/NewFileDocument.java @@ -17,12 +17,12 @@ import org.simantics.layer0.Layer0; public class NewFileDocument implements ActionFactory { Resource relation; String defaultName; - + public NewFileDocument(ReadGraph graph, String relationUri, String defaultName) throws DatabaseException { relation = graph.getResource(relationUri); this.defaultName = defaultName; } - + @Override public Runnable create(Object target) { @@ -35,29 +35,38 @@ public class NewFileDocument implements ActionFactory { @Override public void run() { Simantics.getSession().asyncRequest(new WriteRequest() { - + @Override public void perform(WriteGraph graph) throws DatabaseException { - graph.markUndoPoint(); - - Layer0 l0 = Layer0.getInstance(graph); - - String name = NameUtils.findFreshName(graph, defaultName, resource, relation); - DocumentResource doc = DocumentResource.getInstance(graph); - - Resource fileResource = graph.newResource(); - graph.claim(fileResource, l0.InstanceOf, doc.FileDocument); - graph.claimLiteral(fileResource, l0.HasName, name); - graph.claim(resource, relation, fileResource); - try { - GraphFileUtil.writeDataToGraph(graph, new byte[0], fileResource); - } catch (IOException e) { - throw new DatabaseException(e); - } + create(graph, resource, relation, defaultName); } - + }); } }; } + + public static Resource create(WriteGraph graph, Resource resource, Resource relation, String defaultName) throws DatabaseException { + + graph.markUndoPoint(); + + Layer0 l0 = Layer0.getInstance(graph); + + String name = NameUtils.findFreshName(graph, defaultName, resource, relation); + DocumentResource doc = DocumentResource.getInstance(graph); + + Resource fileResource = graph.newResource(); + graph.claim(fileResource, l0.InstanceOf, doc.FileDocument); + graph.claimLiteral(fileResource, l0.HasName, name); + graph.claim(resource, relation, fileResource); + try { + GraphFileUtil.writeDataToGraph(graph, new byte[0], fileResource); + } catch (IOException e) { + throw new DatabaseException(e); + } + + return fileResource; + + } + } diff --git a/bundles/org.simantics.layer0.utils/META-INF/MANIFEST.MF b/bundles/org.simantics.layer0.utils/META-INF/MANIFEST.MF index f9f82e4a0..36f82a01d 100644 --- a/bundles/org.simantics.layer0.utils/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.layer0.utils/META-INF/MANIFEST.MF @@ -17,10 +17,10 @@ Export-Package: org.simantics.layer0.utils, org.simantics.layer0.utils.triggers, org.simantics.layer0.utils.writer Require-Bundle: gnu.trove3;bundle-version="3.0.3", - org.simantics.db.common;bundle-version="0.8.0";visibility:=reexport, org.eclipse.equinox.common;bundle-version="3.5.0", org.simantics.layer0;bundle-version="1.0.0", - org.simantics.layer0x.ontology;bundle-version="1.0.0" + org.simantics.layer0x.ontology;bundle-version="1.0.0", + org.simantics.db.common;bundle-version="1.1.0" Bundle-Vendor: VTT Technical Research Centre of Finland Bundle-ClassPath: . Bundle-RequiredExecutionEnvironment: JavaSE-1.8 diff --git a/bundles/org.simantics.layer0/graph/Layer0.pgraph b/bundles/org.simantics.layer0/graph/Layer0.pgraph index e3d00e8aa..d169c9684 100644 --- a/bundles/org.simantics.layer0/graph/Layer0.pgraph +++ b/bundles/org.simantics.layer0/graph/Layer0.pgraph @@ -4,6 +4,9 @@ L0 = : L0.Ontology L0.HasResourceClass "org.simantics.layer0.Layer0" +L0.SCLMain : L0.SCLModule + L0.SCLModule.definition """ include "Simantics/Layer0" """ + // Types L0.Entity : L0.Type L0.HasDescription "All types are inherited from this type." @@ -42,6 +45,7 @@ L0.Entity : L0.Type >-- L0.Entity.methods @L0.assert L0.Entity.methods _ : L0.Property + L0.HasValueType "StructuredProperty" L0.Entity.methods ==> "StructuredProperty" L0.Constraint -- L0.Constraint.Validator Resource -> [Issue]" + L0.RequiresValueType "Resource -> [Issue]" + +L0.SCLValidator [Issue]" + L0.HasConstraint -- L0.SCLScript.definition --> L0.String L0.SCLAction.action ==> "Resource -> ()" -- L0.Ontology.defaultLocalName --> L0.String L0.Entity - L0.HasConstraint L0.Entity.RelationConstraint : L0.Constraint - L0.Constraint.Validator L0.Functions.relationValidator - L0.HasConstraint L0.Entity.PropertyConstraint : L0.Constraint - L0.Constraint.Validator L0.Functions.propertyValidator - L0.HasConstraint L0.Entity.ValueConstraint : L0.Constraint - L0.Constraint.Validator L0.Functions.valueValidator - L0.HasConstraint L0.Entity.URIConstraint : L0.Constraint - L0.Constraint.Validator L0.Functions.uriValidator - L0.HasConstraint L0.Entity.ClusterConstraint : L0.Constraint - L0.Constraint.Validator L0.Functions.clusterValidator - - - \ No newline at end of file + L0.HasConstraint L0.Entity.RelationConstraint + @L0.sclConstraint "relationValidator" + L0.HasConstraint L0.Entity.PropertyConstraint + @L0.sclConstraint "propertyValidator" + L0.HasConstraint L0.Entity.ValueConstraint + @L0.sclConstraint "valueValidator" + L0.HasConstraint L0.Entity.ClusterConstraint + @L0.sclConstraint "clusterValidator" + L0.HasConstraint L0.Entity.URIConstraint + @L0.sclConstraint "uriValidator" + \ No newline at end of file diff --git a/bundles/org.simantics.layer0/graph/Layer0Values.pgraph b/bundles/org.simantics.layer0/graph/Layer0Values.pgraph index 358aaa7e9..14aa774e8 100644 --- a/bundles/org.simantics.layer0/graph/Layer0Values.pgraph +++ b/bundles/org.simantics.layer0/graph/Layer0Values.pgraph @@ -1,6 +1,8 @@ L0 = -L0.Value -- L0.SCLValue.environment --> L0.SCLValue.Environment -- L0.SCLValueType.validator ==> "Variable -> String" T getAdapter(Class adapter) { + // No outline view for scripts + if (IContentOutlinePage.class.equals(adapter)) { + return null; + } + + return super.getAdapter(adapter); + } } diff --git a/bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/SyncTypicalTemplatesToInstances.java b/bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/SyncTypicalTemplatesToInstances.java index 8a0b1ddbc..09545ada8 100644 --- a/bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/SyncTypicalTemplatesToInstances.java +++ b/bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/SyncTypicalTemplatesToInstances.java @@ -554,8 +554,9 @@ public class SyncTypicalTemplatesToInstances extends WriteRequest { if(stm != null) { if(graph.isInstanceOf(connectionPoint, L0.FunctionalRelation)) { if(!isSynchronizedConnector(graph, templateElement, stm.getObject())) { - messageLog.add("\t\tABORTED: tried to connect to an already connected terminal " + NameUtils.getSafeName(graph, counterPartElement) + " " + NameUtils.getSafeName(graph, connectionPoint)); - return; + messageLog.add("\t\tWARNING: skipping addition of template connection " + NameUtils.getSafeName(graph, templateElement, true) + " into instance."); + messageLog.add("\t\t\ttried to connect to an already connected terminal " + NameUtils.getSafeName(graph, counterPartElement, true) + " " + NameUtils.getSafeName(graph, connectionPoint)); + templateElementsAddedToTemplate.remove(templateElement); } } } @@ -825,7 +826,7 @@ public class SyncTypicalTemplatesToInstances extends WriteRequest { Resource instanceElement = typicalInfo.bean.templateToInstance.get(changedTemplateElement); if (instanceElement == null) { // There's an earlier problem in the sync process if this happens. - typicalInfo.messageLog.add("SKIPPING SYNC OF CHANGED TEMPLATE ELEMENT DUE TO MISSING INSTANCE: " + safeNameAndType(graph, getElementNameResource(graph, changedTemplateElement))); + typicalInfo.messageLog.add("\t\tSKIPPING SYNC OF CHANGED TEMPLATE ELEMENT DUE TO MISSING INSTANCE: " + safeNameAndType(graph, getElementNameResource(graph, changedTemplateElement))); continue; } diff --git a/bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/TypicalInfo.java b/bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/TypicalInfo.java index d7620d133..e491a1b11 100644 --- a/bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/TypicalInfo.java +++ b/bundles/org.simantics.modeling/src/org/simantics/modeling/typicals/TypicalInfo.java @@ -1,6 +1,6 @@ package org.simantics.modeling.typicals; -import java.util.Collection; +import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; @@ -8,6 +8,6 @@ public class TypicalInfo { public TypicalInfoBean bean; public IProgressMonitor monitor; - public Collection messageLog; + public List messageLog; } diff --git a/bundles/org.simantics.objmap2/META-INF/MANIFEST.MF b/bundles/org.simantics.objmap2/META-INF/MANIFEST.MF index efd050e10..55a1393f5 100644 --- a/bundles/org.simantics.objmap2/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.objmap2/META-INF/MANIFEST.MF @@ -8,9 +8,10 @@ Require-Bundle: org.simantics.db;bundle-version="1.1.0", gnu.trove3;bundle-version="3.0.0", org.eclipse.core.runtime;bundle-version="3.7.0", org.simantics.layer0;bundle-version="1.0.0", - org.apache.log4j;bundle-version="1.2.15", org.simantics.db.common;bundle-version="1.1.0", - org.simantics.structural.ontology;bundle-version="1.1.0" + org.simantics.structural.ontology;bundle-version="1.1.0", + org.slf4j.api, + org.simantics.db.layer0 Export-Package: org.simantics.objmap.backward, org.simantics.objmap.bidirectional, org.simantics.objmap.exceptions, diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedList.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedList.java new file mode 100644 index 000000000..7018a3915 --- /dev/null +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedList.java @@ -0,0 +1,40 @@ +package org.simantics.objmap.graph.annotations; + +/******************************************************************************* + * Copyright (c) 2019 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum oy - initial API and implementation + *******************************************************************************/ + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.simantics.layer0.Layer0; +import org.simantics.objmap.graph.annotations.meta.IsFieldRule; + +/** + * This field is a java.util.List or an array type that represents the contents + * of a Layer0.List entity that is the single object of the given relation. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +@IsFieldRule +public @interface LinkedList { + /** + * URI of a relation that has a Layer0.List as its object. + */ + String value(); + /** + * URI of the type of the list resource to create. + */ + String type() default Layer0.URIs.List; + boolean composition() default false; +} diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedListAdd.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedListAdd.java new file mode 100644 index 000000000..197579f71 --- /dev/null +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedListAdd.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2019 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum oy - initial API and implementation + *******************************************************************************/ +package org.simantics.objmap.graph.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * An add method add(int index, T value) for a linked list mapped to the single object + * of a given relation. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface LinkedListAdd { + String value(); +} diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedListGet.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedListGet.java new file mode 100644 index 000000000..a4744994b --- /dev/null +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedListGet.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2019 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum oy - initial API and implementation + *******************************************************************************/ +package org.simantics.objmap.graph.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.simantics.layer0.Layer0; +import org.simantics.objmap.graph.annotations.meta.IsCollectionRule; + +/** + * A get method that returns the contents of a linked list mapped to the single object of + * a given relation. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@IsCollectionRule +@HasCollectionAdder(LinkedListAdd.class) +@HasCollectionRemover(LinkedListRem.class) +public @interface LinkedListGet { + String value(); + String type() default Layer0.URIs.List; + boolean composition() default false; +} diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedListRem.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedListRem.java new file mode 100644 index 000000000..afc834ea8 --- /dev/null +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/LinkedListRem.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2019 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum oy - initial API and implementation + *******************************************************************************/ +package org.simantics.objmap.graph.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Remove method for a list of objects represented by a Layer0.List as the + * single object of a given relation. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface LinkedListRem { + String value(); +} diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/UpdateMethod.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/UpdateMethod.java index 1e2ff4f2d..d26b565b9 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/UpdateMethod.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/UpdateMethod.java @@ -16,7 +16,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import org.simantics.objmap.graph.annotations.meta.IsFieldRule; +import org.simantics.objmap.graph.annotations.meta.IsMethodRule; @@ -27,6 +27,6 @@ import org.simantics.objmap.graph.annotations.meta.IsFieldRule; */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) -@IsFieldRule +@IsMethodRule public @interface UpdateMethod { } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/CompoundRelatedGetSetValueRuleFactory.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/CompoundRelatedGetSetValueRuleFactory.java index ab5b1c7a9..b98961154 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/CompoundRelatedGetSetValueRuleFactory.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/CompoundRelatedGetSetValueRuleFactory.java @@ -14,10 +14,12 @@ package org.simantics.objmap.graph.annotations.factories; import java.lang.annotation.Annotation; import java.lang.reflect.Method; +import org.simantics.databoard.binding.Binding; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.exception.DatabaseException; -import org.simantics.layer0.Layer0; +import org.simantics.db.layer0.request.PropertyInfo; +import org.simantics.db.layer0.request.PropertyInfoRequest; import org.simantics.objmap.bidirectional.IBidirectionalMappingRule; import org.simantics.objmap.graph.annotations.CompoundRelatedGetValue; import org.simantics.objmap.graph.annotations.CompoundRelatedSetValue; @@ -43,6 +45,8 @@ public class CompoundRelatedGetSetValueRuleFactory implements IGetSetRule // Class adapterClass = getterAnn.adapter(); IRangeAccessor rangeAccessor = new CompoundGetSetValueAccessor(getter, setter); + PropertyInfo propInfo = g.syncRequest(new PropertyInfoRequest(g.getResource(getterAnn.valRelation()))); + Binding valueBinding = propInfo.defaultBinding; // Resource valueType; // if (adapterClass == IdentityAdapter.class) { // valueType = dataTypeOfClass(g, getter.getReturnType()); @@ -59,7 +63,8 @@ public class CompoundRelatedGetSetValueRuleFactory implements IGetSetRule // } return new ValueRule(new CompoundValueAccessor(g.getResource(getterAnn.objRelation()), g.getResource(getterAnn.objType()), - g.getResource(getterAnn.valRelation())), + g.getResource(getterAnn.valRelation()), + valueBinding), rangeAccessor); } @@ -69,42 +74,5 @@ public class CompoundRelatedGetSetValueRuleFactory implements IGetSetRule CompoundRelatedSetValue setterAnn = (CompoundRelatedSetValue)annotation; return getterAnn.objRelation().equals(setterAnn.value()); } - - public static Resource dataTypeOfClass(ReadGraph g, Class clazz) { - Layer0 b = Layer0.getInstance(g); - if(clazz.equals(Double.class) || clazz.equals(double.class)) - return b.Double; - else if(clazz.equals(String.class)) - return b.String; - else if(clazz.equals(Integer.class) || clazz.equals(int.class)) - return b.Integer; - else if(clazz.equals(Float.class) || clazz.equals(float.class)) - return b.Float; - else if(clazz.equals(Boolean.class) || clazz.equals(boolean.class)) - return b.Boolean; - else if(clazz.equals(Long.class) || clazz.equals(long.class)) - return b.Long; - else if(clazz.equals(Byte.class) || clazz.equals(byte.class)) - return b.Byte; - - else if(clazz.equals(double[].class)) - return b.DoubleArray; - else if(clazz.equals(int[].class)) - return b.IntegerArray; - else if(clazz.equals(byte[].class)) - return b.ByteArray; - else if(clazz.equals(float[].class)) - return b.FloatArray; - else if(clazz.equals(boolean[].class)) - return b.BooleanArray; - else if(clazz.equals(String[].class)) - return b.StringArray; - else if(clazz.equals(long[].class)) - return b.LongArray; - else { - System.out.println("Couldn't find a data type for " + clazz); - return null; - } - } } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/DataTypeUtils.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/DataTypeUtils.java index cd745a523..6d3f33a1b 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/DataTypeUtils.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/DataTypeUtils.java @@ -11,12 +11,28 @@ *******************************************************************************/ package org.simantics.objmap.graph.annotations.factories; +import org.simantics.databoard.Datatypes; +import org.simantics.databoard.binding.error.DatatypeConstructionException; +import org.simantics.databoard.type.ArrayType; +import org.simantics.databoard.type.BooleanType; +import org.simantics.databoard.type.ByteType; +import org.simantics.databoard.type.Datatype; +import org.simantics.databoard.type.DoubleType; +import org.simantics.databoard.type.FloatType; +import org.simantics.databoard.type.IntegerType; +import org.simantics.databoard.type.LongType; +import org.simantics.databoard.type.OptionalType; +import org.simantics.databoard.type.StringType; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.layer0.Layer0; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class DataTypeUtils { + private static final Logger LOGGER = LoggerFactory.getLogger(DataTypeUtils.class); + public static Resource dataTypeOfClass(ReadGraph g, Class clazz) { Layer0 b = Layer0.getInstance(g); if(clazz.equals(Double.class) || clazz.equals(double.class)) @@ -49,9 +65,59 @@ public class DataTypeUtils { else if(clazz.equals(long[].class)) return b.LongArray; else { - System.out.println("Couldn't find a data type for " + clazz); + try { + Datatype type = Datatypes.getDatatype(clazz); + final Resource result = dataTypeOfDatatype(g, type); + if (result != null) + return result; + } catch (DatatypeConstructionException e) { + } + + LOGGER.error("No literal type found for class {}", clazz); return null; } } - + + public static Resource dataTypeOfDatatype(ReadGraph g, Datatype type) { + if (type instanceof OptionalType) + return dataTypeOfDatatype(g, ((OptionalType) type).getComponentType()); + + Layer0 b = Layer0.getInstance(g); + if (type instanceof DoubleType) + return b.Double; + else if(type instanceof StringType) + return b.String; + else if(type instanceof IntegerType) + return b.Integer; + else if(type instanceof FloatType) + return b.Float; + else if(type instanceof BooleanType) + return b.Boolean; + else if(type instanceof LongType) + return b.Long; + else if(type instanceof ByteType) + return b.Byte; + + else if (type instanceof ArrayType) { + type = ((ArrayType) type).componentType(); + + if (type instanceof DoubleType) + return b.DoubleArray; + else if(type instanceof IntegerType) + return b.IntegerArray; + else if(type instanceof ByteType) + return b.ByteArray; + else if(type instanceof FloatType) + return b.FloatArray; + else if(type instanceof BooleanType) + return b.BooleanArray; + else if(type instanceof StringType) + return b.StringArray; + else if(type instanceof LongType) + return b.LongArray; + } + + LOGGER.error("No literal type found for data type {}", type); + return null; + } } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/LinkedListRuleFactory.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/LinkedListRuleFactory.java new file mode 100644 index 000000000..072a6a2df --- /dev/null +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/LinkedListRuleFactory.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2019 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum oy - initial API and implementation + *******************************************************************************/ +package org.simantics.objmap.graph.annotations.factories; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.util.Collection; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.exception.ResourceNotFoundException; +import org.simantics.db.exception.ServiceException; +import org.simantics.db.exception.ValidationException; +import org.simantics.objmap.bidirectional.IBidirectionalMappingRule; +import org.simantics.objmap.graph.annotations.LinkedList; +import org.simantics.objmap.graph.rules.MappedElementsRule; +import org.simantics.objmap.graph.rules.domain.LinkedListAccessor; +import org.simantics.objmap.graph.rules.factory.IFieldRuleFactory; +import org.simantics.objmap.graph.rules.range.FieldAccessor; + +public class LinkedListRuleFactory implements IFieldRuleFactory { + + @Override + public IBidirectionalMappingRule create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException, ValidationException, ServiceException { + LinkedList annotation = (LinkedList)_annotation; + return new MappedElementsRule( + new LinkedListAccessor(g.getResource(annotation.value()), g.getResource(annotation.type()), annotation.composition()), + new FieldAccessor>(field) + ); + } + +} diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/LinkedListRuleFactory2.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/LinkedListRuleFactory2.java new file mode 100644 index 000000000..3ef69d989 --- /dev/null +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/LinkedListRuleFactory2.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2019 Association for Decentralized Information Management in + * Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum oy - initial API and implementation + *******************************************************************************/ +package org.simantics.objmap.graph.annotations.factories; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.exception.DatabaseException; +import org.simantics.objmap.bidirectional.IBidirectionalMappingRule; +import org.simantics.objmap.graph.annotations.LinkedListAdd; +import org.simantics.objmap.graph.annotations.LinkedListGet; +import org.simantics.objmap.graph.annotations.LinkedListRem; +import org.simantics.objmap.graph.rules.MappedElementsRule; +import org.simantics.objmap.graph.rules.domain.LinkedListAccessor; +import org.simantics.objmap.graph.rules.factory.ICollectionRuleFactory; +import org.simantics.objmap.graph.rules.range.CollectionAccessor; + +public class LinkedListRuleFactory2 implements ICollectionRuleFactory { + + @Override + public IBidirectionalMappingRule create(ReadGraph g, Annotation annotation, + Method getter, Method adder, Method remover) + throws DatabaseException { + LinkedListGet getterAnn = (LinkedListGet)annotation; + return new MappedElementsRule(new LinkedListAccessor(g.getResource(getterAnn.value()), g.getResource(getterAnn.type()), getterAnn.composition()), + new CollectionAccessor(getter, adder, remover)); + } + + @Override + public boolean isAdder(Annotation getterAnnotation, Annotation annotation) { + LinkedListGet getterAnn = (LinkedListGet)getterAnnotation; + LinkedListAdd adderAnn = (LinkedListAdd)annotation; + return getterAnn.value().equals(adderAnn.value()); + } + + @Override + public boolean isRemover(Annotation getterAnnotation, Annotation annotation) { + LinkedListGet getterAnn = (LinkedListGet)getterAnnotation; + LinkedListRem adderAnn = (LinkedListRem)annotation; + return getterAnn.value().equals(adderAnn.value()); + } + +} diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/RelatedGetSetValueRuleFactory.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/RelatedGetSetValueRuleFactory.java index 994811fee..5c57a75c3 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/RelatedGetSetValueRuleFactory.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/RelatedGetSetValueRuleFactory.java @@ -14,6 +14,10 @@ package org.simantics.objmap.graph.annotations.factories; import java.lang.annotation.Annotation; import java.lang.reflect.Method; +import org.simantics.databoard.Bindings; +import org.simantics.databoard.binding.Binding; +import org.simantics.databoard.binding.error.BindingConstructionException; +import org.simantics.databoard.binding.reflection.BindingRequest; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.exception.DatabaseException; @@ -47,8 +51,14 @@ public class RelatedGetSetValueRuleFactory implements IGetSetRuleFactory< Class adapterClass = getterAnn.adapter(); IRangeAccessor rangeAccessor = new GetSetValueAccessor(getter, setter); Resource valueType; + Binding valueBinding = null; if (adapterClass == IdentityAdapter.class) { - valueType = dataTypeOfClass(g, getter.getReturnType()); + try { + valueBinding = Bindings.getBinding(BindingRequest.create(getter)); + } catch (BindingConstructionException e) { + return null; + } + valueType = DataTypeUtils.dataTypeOfDatatype(g, valueBinding.type()); } else { try{ ValueAdapter adapter = adapterClass.newInstance(); @@ -60,7 +70,7 @@ public class RelatedGetSetValueRuleFactory implements IGetSetRuleFactory< throw new RuntimeException(e); } } - return new ValueRule(new RelatedValueAccessor(g.getResource(getterAnn.value()), valueType), + return new ValueRule(new RelatedValueAccessor(g.getResource(getterAnn.value()), valueType, valueBinding), rangeAccessor); } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/RelatedValueRuleFactory.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/RelatedValueRuleFactory.java index ca226c605..adb2f6215 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/RelatedValueRuleFactory.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/RelatedValueRuleFactory.java @@ -14,12 +14,15 @@ package org.simantics.objmap.graph.annotations.factories; import java.lang.annotation.Annotation; import java.lang.reflect.Field; +import org.simantics.databoard.Bindings; +import org.simantics.databoard.binding.Binding; +import org.simantics.databoard.binding.error.BindingConstructionException; +import org.simantics.databoard.binding.reflection.BindingRequest; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.exception.ResourceNotFoundException; import org.simantics.db.exception.ServiceException; import org.simantics.db.exception.ValidationException; - import org.simantics.objmap.bidirectional.IBidirectionalMappingRule; import org.simantics.objmap.graph.annotations.RelatedValue; import org.simantics.objmap.graph.rules.ValueRule; @@ -41,8 +44,14 @@ public class RelatedValueRuleFactory implements IFieldRuleFactory adapterClass = annotation.adapter(); IRangeAccessor rangeAccessor = new FieldAccessor(field); Resource valueType; + Binding valueBinding = null; if (adapterClass == IdentityAdapter.class) { - valueType = DataTypeUtils.dataTypeOfClass(g, field.getType()); + try { + valueBinding = Bindings.getBinding(BindingRequest.create(field)); + valueType = DataTypeUtils.dataTypeOfDatatype(g, valueBinding.type()); + } catch (BindingConstructionException e) { + return null; + } } else { try { ValueAdapter adapter = adapterClass.newInstance(); @@ -54,7 +63,7 @@ public class RelatedValueRuleFactory implements IFieldRuleFactory(new RelatedValueAccessor(g.getResource(annotation.value()), valueType), rangeAccessor); + return new ValueRule(new RelatedValueAccessor(g.getResource(annotation.value()), valueType, valueBinding), rangeAccessor); } } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/UpdateMethodFactory.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/UpdateMethodFactory.java index 10f64be78..e1de9f20c 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/UpdateMethodFactory.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/annotations/factories/UpdateMethodFactory.java @@ -14,7 +14,8 @@ package org.simantics.objmap.graph.annotations.factories; import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.WriteGraph; import org.simantics.db.exception.DatabaseException; @@ -26,7 +27,7 @@ import org.simantics.objmap.graph.rules.factory.IMethodRuleFactory; public class UpdateMethodFactory implements IMethodRuleFactory { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(UpdateMethodFactory.class); @Override public IBidirectionalMappingRule create(ReadGraph g, @@ -40,7 +41,7 @@ public class UpdateMethodFactory implements IMethodRuleFactory map, Domain domainElement, Range rangeElement) throws MappingException { - LOGGER.info(" UpdateMethodFactory.updateRange"); + LOGGER.trace(" UpdateMethodFactory.updateRange"); try { return (Boolean)method.invoke(rangeElement, g, domainElement); } catch (Exception e) { diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/impl/Mapping.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/impl/Mapping.java index f105a2894..c2ecdf1b1 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/impl/Mapping.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/impl/Mapping.java @@ -21,7 +21,8 @@ import java.util.Iterator; import java.util.List; import java.util.Set; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.WriteGraph; import org.simantics.db.exception.DatabaseException; @@ -42,7 +43,7 @@ import org.simantics.objmap.graph.schema.IMappingSchema; */ public class Mapping implements IMapping { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static final Logger LOGGER = LoggerFactory.getLogger(Mapping.class); IMappingSchema schema; @@ -72,7 +73,7 @@ public class Mapping implements IMapping { } private void createDomain(WriteGraph g, Link link) throws MappingException { - LOGGER.info(" createDomain for " + link.rangeElement); + LOGGER.trace(" createDomain for " + link.rangeElement); ILinkType type = schema.linkTypeOfRangeElement(link.rangeElement); Domain domainElement = type.createDomainElement(g, link.rangeElement); link.type = type; @@ -263,11 +264,11 @@ public class Mapping implements IMapping { @Override public synchronized Collection updateDomain(WriteGraph g) throws MappingException { - LOGGER.info("Mapping.updateDomain"); + LOGGER.trace("Mapping.updateDomain"); RangeToDomain map = new RangeToDomain(g); ArrayList updated = new ArrayList(); while(!modifiedRangeLinks.isEmpty()) { - LOGGER.info(" modifiedRangeLinks.size() = " + modifiedRangeLinks.size()); + LOGGER.trace(" modifiedRangeLinks.size() = " + modifiedRangeLinks.size()); Link link = modifiedRangeLinks.remove(modifiedRangeLinks.size()-1); link.rangeModified = false; @@ -279,9 +280,10 @@ public class Mapping implements IMapping { if(link.type == null) { createDomain(g, link); } - - if(link.type.updateDomain(g, map, link.domainElement, link.rangeElement)) - updated.add(link.domainElement); + else { + if(link.type.updateDomain(g, map, link.domainElement, link.rangeElement)) + updated.add(link.domainElement); + } } if (listensDomain) updateRange(g); //FIXME: without this listening would stop. @@ -290,11 +292,11 @@ public class Mapping implements IMapping { @Override public synchronized Collection updateRange(ReadGraph g) throws MappingException { - LOGGER.info("Mapping.updateRange"); + LOGGER.trace("Mapping.updateRange"); DomainToRange map = new DomainToRange(g); ArrayList updated = new ArrayList(); while(!modifiedDomainLinks.isEmpty()) { - LOGGER.info(" modifiedDomainLinks.size() = " + modifiedDomainLinks.size()); + LOGGER.trace(" modifiedDomainLinks.size() = " + modifiedDomainLinks.size()); Link link = modifiedDomainLinks.remove(modifiedDomainLinks.size()-1); link.domainModified = false; @@ -357,7 +359,7 @@ public class Mapping implements IMapping { void domainModified(Link link) { if(!link.domainModified) { synchronized(modifiedDomainLinks) { - LOGGER.info(" domainModified for " + link.rangeElement); + LOGGER.trace(" domainModified for " + link.rangeElement); link.domainModified = true; modifiedDomainLinks.add(link); if(modifiedDomainLinks.size() == 1) { diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/MappedElementRule.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/MappedElementRule.java index 3b6fac31d..9761f5555 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/MappedElementRule.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/MappedElementRule.java @@ -11,7 +11,6 @@ *******************************************************************************/ package org.simantics.objmap.graph.rules; -import org.apache.log4j.Logger; import org.simantics.db.ReadGraph; import org.simantics.db.WriteGraph; import org.simantics.objmap.backward.IBackwardMapping; @@ -20,9 +19,8 @@ import org.simantics.objmap.exceptions.MappingException; import org.simantics.objmap.forward.IForwardMapping; import org.simantics.objmap.graph.rules.domain.IDomainAccessor; import org.simantics.objmap.graph.rules.range.IRangeAccessor; - - - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * A rule that synchronizes collection of elements between @@ -32,7 +30,7 @@ import org.simantics.objmap.graph.rules.range.IRangeAccessor; */ public class MappedElementRule implements IBidirectionalMappingRule { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static final Logger LOGGER = LoggerFactory.getLogger(MappedElementRule.class); IDomainAccessor domainAccessor; IRangeAccessor rangeAccessor; @@ -47,7 +45,7 @@ public class MappedElementRule implements IBidirectionalMappingRu public boolean updateDomain(WriteGraph g, IBackwardMapping map, Domain domainElement, Range rangeElement) throws MappingException { - LOGGER.info(" MappedElementRule.updateDomain"); + LOGGER.trace(" MappedElementRule.updateDomain"); Range value = rangeAccessor.get(rangeElement); Domain mappedValue = value == null ? null : map.inverseMap(g, value);//map.inverseGet(value); return domainAccessor.set(g, domainElement, mappedValue); @@ -57,7 +55,7 @@ public class MappedElementRule implements IBidirectionalMappingRu public boolean updateRange(ReadGraph g, IForwardMapping map, Domain domainElement, Range rangeElement) throws MappingException { - LOGGER.info(" MappedElementRule.updateRange"); + LOGGER.trace(" MappedElementRule.updateRange"); Domain value = domainAccessor.get(g, domainElement); Range mappedValue = value == null ? null : map.map(g, value);////map.get(value); return rangeAccessor.set(rangeElement, mappedValue); diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/MappedElementsRule.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/MappedElementsRule.java index cd295e583..7f3c13a10 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/MappedElementsRule.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/MappedElementsRule.java @@ -14,7 +14,6 @@ package org.simantics.objmap.graph.rules; import java.util.ArrayList; import java.util.Collection; -import org.apache.log4j.Logger; import org.simantics.db.ReadGraph; import org.simantics.db.WriteGraph; import org.simantics.objmap.backward.IBackwardMapping; @@ -23,6 +22,8 @@ import org.simantics.objmap.exceptions.MappingException; import org.simantics.objmap.forward.IForwardMapping; import org.simantics.objmap.graph.rules.domain.IDomainAccessor; import org.simantics.objmap.graph.rules.range.IRangeAccessor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -33,7 +34,7 @@ import org.simantics.objmap.graph.rules.range.IRangeAccessor; */ public class MappedElementsRule implements IBidirectionalMappingRule { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static final Logger LOGGER = LoggerFactory.getLogger(MappedElementsRule.class); IDomainAccessor> domainAccessor; IRangeAccessor> rangeAccessor; @@ -48,7 +49,7 @@ public class MappedElementsRule implements IBidirectionalMappingR public boolean updateDomain(WriteGraph g, IBackwardMapping map, Domain domainElement, Range rangeElement) throws MappingException { - LOGGER.info(" MappedElementsRule.updateDomain"); + LOGGER.trace(" MappedElementsRule.updateDomain"); // Snapshot the accessed range value for concurrency safety. // NOTE: still assumes that the accessed collection is concurrent or // synchronized for toArray to be atomic. @@ -64,7 +65,7 @@ public class MappedElementsRule implements IBidirectionalMappingR public boolean updateRange(ReadGraph g, IForwardMapping map, Domain domainElement, Range rangeElement) throws MappingException { - LOGGER.info(" MappedElementsRule.updateRange"); + LOGGER.trace(" MappedElementsRule.updateRange"); Collection value = domainAccessor.get(g, domainElement); ArrayList mappedValue = new ArrayList(value.size()); for(Domain r : value) diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/ValueRule.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/ValueRule.java index 718bc7c2d..9ba9dba11 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/ValueRule.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/ValueRule.java @@ -11,7 +11,8 @@ *******************************************************************************/ package org.simantics.objmap.graph.rules; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.WriteGraph; import org.simantics.objmap.backward.IBackwardMapping; @@ -29,7 +30,7 @@ import org.simantics.objmap.graph.rules.range.IRangeAccessor; */ public class ValueRule implements IBidirectionalMappingRule { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(ValueRule.class); IDomainAccessor domainAccessor; IRangeAccessor rangeAccessor; @@ -44,7 +45,7 @@ public class ValueRule implements IBidirectionalMappingRule map, Domain domainElement, Range rangeElement) throws MappingException { - LOGGER.info(" ValueRule.updateDomain"); + LOGGER.trace(" ValueRule.updateDomain"); Object value = rangeAccessor.get(rangeElement); return domainAccessor.set(g, domainElement, value); } @@ -53,7 +54,7 @@ public class ValueRule implements IBidirectionalMappingRule map, Domain domainElement, Range rangeElement) throws MappingException { - LOGGER.info(" ValueRule.updateRange"); + LOGGER.trace(" ValueRule.updateRange"); Object value = domainAccessor.get(g, domainElement); return rangeAccessor.set(rangeElement, value); } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/CompoundValueAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/CompoundValueAccessor.java index 78b484303..39df524b2 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/CompoundValueAccessor.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/CompoundValueAccessor.java @@ -11,20 +11,22 @@ *******************************************************************************/ package org.simantics.objmap.graph.rules.domain; -import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; -import org.apache.log4j.Logger; +import org.simantics.databoard.binding.Binding; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.Statement; import org.simantics.db.WriteGraph; import org.simantics.db.exception.DatabaseException; +import org.simantics.db.exception.ServiceException; import org.simantics.layer0.Layer0; import org.simantics.objmap.exceptions.MappingException; -import org.simantics.objmap.graph.annotations.factories.CompoundRelatedGetSetValueRuleFactory; +import org.simantics.objmap.graph.annotations.factories.DataTypeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -32,42 +34,46 @@ import org.simantics.objmap.graph.annotations.factories.CompoundRelatedGetSetVal */ public class CompoundValueAccessor implements IDomainAccessor { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static final Logger LOGGER = LoggerFactory.getLogger(CompoundValueAccessor.class); Resource objRelation; Resource objType; Resource valRelation; + Binding valueBinding; - public CompoundValueAccessor(Resource objRelation, Resource objType, Resource valRelation) { + public CompoundValueAccessor(Resource objRelation, Resource objType, Resource valRelation, Binding valueBinding) { this.objRelation = objRelation; this.objType = objType; this.valRelation = valRelation; + this.valueBinding = valueBinding; } @Override public Object get(ReadGraph g, Resource element) throws MappingException { try { Layer0 l0 = Layer0.getInstance(g); - LOGGER.info(" CompoundValueAccessor.get"); + LOGGER.trace(" CompoundValueAccessor.get"); Collection coll = g.getStatements(element, objRelation); Map map = new HashMap(); for (Statement c : coll) { String name = g.getRelatedValue(c.getObject(), l0.HasName); - if (!map.containsKey(name) || !c.isAsserted(element)) - map.put(name, g.getRelatedValue(c.getObject(), valRelation)); + if (!map.containsKey(name) || !c.isAsserted(element)) { + final Object value = getValue(g, c.getObject()); + map.put(name, value); + } } return map; } catch (DatabaseException e) { throw new MappingException(e); } } - + @Override public boolean set(WriteGraph g, Resource element, Object v) throws MappingException { try { Layer0 l0 = Layer0.getInstance(g); - LOGGER.info(" CompoundValueAccessor.set"); + LOGGER.trace(" CompoundValueAccessor.set"); @SuppressWarnings("unchecked") Map values = (Map)v; @@ -81,6 +87,7 @@ public class CompoundValueAccessor implements IDomainAccessor { valueMap.put(name, g.getRelatedValue(c.getObject(), valRelation)); } } + boolean changed = false; for (String key : values.keySet()) { Object value = values.get(key); @@ -97,34 +104,40 @@ public class CompoundValueAccessor implements IDomainAccessor { } Statement valueStatement = g.getPossibleStatement(stm.getObject(), valRelation); - Resource valueType = CompoundRelatedGetSetValueRuleFactory.dataTypeOfClass(g, value.getClass()); + Resource valueType = valueBinding != null ? + DataTypeUtils.dataTypeOfDatatype(g, valueBinding.type()) : + DataTypeUtils.dataTypeOfClass(g, value.getClass()); + if(valueStatement == null) { - Resource valueResource = g.newResource(); - g.claim(valueResource, Layer0.getInstance(g).InstanceOf, null, valueType); + g.claim(valueResource, Layer0.getInstance(g).InstanceOf, null, valueType); g.claim(stm.getObject(), valRelation, valueResource); - g.claimValue(valueResource, value); + claimValue(g, valueResource, value); } else { - - if (!valueStatement.isAsserted(stm.getObject())) g.claimValue(valueStatement.getObject(), value); else { Resource valueResource = g.newResource(); - g.claim(valueResource, Layer0.getInstance(g).InstanceOf, null, - valueType); + g.claim(valueResource, Layer0.getInstance(g).InstanceOf, null, valueType); g.claim(stm.getObject(), valRelation, valueResource); - g.claimValue(valueResource, value); + claimValue(g, valueResource, value); } } } - return changed; + return changed; } catch (DatabaseException e) { throw new MappingException(e); } } + + private void claimValue(WriteGraph g, Resource valueResource, Object value) throws ServiceException { + if (valueBinding != null) + g.claimValue(valueResource, value, valueBinding); + else + g.claimValue(valueResource, value); + } private Statement getStatement(ReadGraph g, Resource s, Resource p, Resource o) throws DatabaseException{ for (Statement stm : g.getStatements(s, p)) { @@ -134,19 +147,8 @@ public class CompoundValueAccessor implements IDomainAccessor { return null; } - private boolean equals(Object o1, Object o2) { - if (o1 instanceof boolean[]) - Arrays.equals((boolean[])o1,(boolean[])o2); - if (o1 instanceof int[]) - Arrays.equals((int[])o1,(int[])o2); - if (o1 instanceof float[]) - Arrays.equals((float[])o1,(float[])o2); - if (o1 instanceof double[]) - Arrays.equals((double[])o1,(double[])o2); - if (o1 instanceof byte[]) - Arrays.equals((byte[])o1,(byte[])o2); - return o1.equals(o2); - + private Object getValue(ReadGraph g, final Resource object) throws DatabaseException { + return valueBinding != null ? g.getRelatedValue(object, valRelation, valueBinding) : g.getRelatedValue(object, valRelation); } } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/LinkedListAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/LinkedListAccessor.java new file mode 100644 index 000000000..e9104c3d9 --- /dev/null +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/LinkedListAccessor.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2019 Association for Decentralized Information Management + * in Industry THTH ry. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Semantum oy - initial API and implementation + *******************************************************************************/ +package org.simantics.objmap.graph.rules.domain; + +import java.util.ArrayList; +import java.util.Collection; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.WriteGraph; +import org.simantics.db.common.utils.ListUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.objmap.exceptions.MappingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Accesses the set of objects attached to the element by the given relation. + * @author Hannu Niemistö + */ +public class LinkedListAccessor implements IDomainAccessor> { + + static Logger LOGGER = LoggerFactory.getLogger(LinkedListAccessor.class); + + Resource relation; + Resource listType; + boolean deleteExtraObjects; + + public LinkedListAccessor(Resource relation, Resource listType, boolean deleteExtraObjects) { + super(); + this.relation = relation; + this.listType = listType; + this.deleteExtraObjects = deleteExtraObjects; + } + + @Override + public Collection get(ReadGraph g, Resource element) throws MappingException { + try { + LOGGER.trace(" LinkdedListAccessor.get"); + return ListUtils.toList(g, g.getPossibleObject(element, relation)); + } catch (DatabaseException e) { + throw new MappingException(e); + } + } + + @Override + public boolean set(WriteGraph g, Resource element, Collection value) + throws MappingException { + try { + LOGGER.trace(" LinkdedListAccessor.set"); + return MappingUtils.synchronizeList(g, element, relation, listType, new ArrayList(value), deleteExtraObjects); + } catch (DatabaseException e) { + throw new MappingException(e); + } + + } + +} diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/MappingUtils.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/MappingUtils.java index a0d0d4dac..0bb50ff57 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/MappingUtils.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/MappingUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 Association for Decentralized Information Management + * Copyright (c) 2007, 2013, 2019 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -8,16 +8,24 @@ * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation + * Semantum oy - linked list utilities *******************************************************************************/ package org.simantics.objmap.graph.rules.domain; import java.util.Arrays; import java.util.Collection; +import java.util.List; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; +import org.simantics.db.common.utils.ListUtils; import org.simantics.db.exception.DatabaseException; +import org.simantics.db.exception.ManyObjectsForFunctionalRelationException; +import org.simantics.db.exception.NoSingleResultException; +import org.simantics.db.exception.ServiceException; +import org.simantics.layer0.Layer0; /** * Static utility methods for rule implementations. @@ -25,7 +33,7 @@ import org.simantics.db.exception.DatabaseException; */ public class MappingUtils { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static final Logger LOGGER = LoggerFactory.getLogger(MappingUtils.class); /** * Adds and removes statements to/from the database so that objects @@ -47,7 +55,7 @@ public class MappingUtils { while(true) { int cmp = currentObjects[i].compareTo(objects[j]); if(cmp < 0) { - LOGGER.info(" remove statement"); + LOGGER.trace(" remove statement"); if(deleteExtraObjects) g.deny(currentObjects[i]); else @@ -58,7 +66,7 @@ public class MappingUtils { break; } else if(cmp > 0) { - LOGGER.info(" add statement"); + LOGGER.trace(" add statement"); g.claim(subject, predicate, objects[j]); modified = true; ++j; @@ -89,4 +97,75 @@ public class MappingUtils { return modified; } + public static boolean synchronizeList(WriteGraph g, Resource element, Resource relation, Resource listType, List value, boolean deleteExtraObjects) throws DatabaseException { + final Layer0 L0 = Layer0.getInstance(g); + + // Return value + boolean modified = false; + + // Get the list - create a new one, if necessary + Resource currentList = g.getPossibleObject(element, relation); + if (currentList == null) { + currentList = ListUtils.create(g, listType); + g.claim(element, relation, currentList); + modified = true; + } + + // Synchronize elements + List currentNodes = ListUtils.getListNodes(g, currentList); + int i = 0, j = 0; + while (i < currentNodes.size()) { + Resource node = currentNodes.get(i); + Resource v = g.getSingleObject(node, L0.List_Element); + if (j < value.size() && v.equals(value.get(j))) { + i++; + j++; + } + else if (value.indexOf(v) > j) { + // Insert new element in the middle + insertElementBefore(g, L0, node, value.get(j)); + modified = true; + j++; + } + else { + // Remove deleted element + if (deleteExtraObjects) g.deny(v); + removeNode(g, L0, node); + modified = true; + i++; + } + } + + // Add new elements at end + while (j < value.size()) { + // Add tailing elements + insertElementBefore(g, L0, currentList, value.get(j)); + modified = true; + j++; + } + + return modified; + } + + private static Resource insertElementBefore(WriteGraph g, final Layer0 L0, Resource node, final Resource val) + throws NoSingleResultException, ManyObjectsForFunctionalRelationException, ServiceException { + Resource prev = g.getSingleObject(node, L0.List_Previous); + g.deny(prev, L0.List_Next, L0.List_Previous, node); + + Resource newNode = g.newResource(); + g.claim(newNode, L0.InstanceOf, L0.List_Entry); + g.claim(prev, L0.List_Next, L0.List_Previous, newNode); + g.claim(newNode, L0.List_Next, L0.List_Previous, node); + g.claim(newNode, L0.List_Element, val); + return newNode; + } + + private static void removeNode(WriteGraph g, final Layer0 L0, Resource node) + throws NoSingleResultException, ManyObjectsForFunctionalRelationException, ServiceException { + Resource prev = g.getSingleObject(node, L0.List_Previous); + Resource next = g.getSingleObject(node, L0.List_Next); + g.claim(prev, L0.List_Next, L0.List_Previous, next); + g.deny(node); + } + } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedObjectAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedObjectAccessor.java index 99253790c..28000a99e 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedObjectAccessor.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedObjectAccessor.java @@ -11,7 +11,8 @@ *******************************************************************************/ package org.simantics.objmap.graph.rules.domain; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; @@ -24,7 +25,7 @@ import org.simantics.objmap.exceptions.MappingException; */ public class RelatedObjectAccessor implements IDomainAccessor { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(RelatedObjectAccessor.class); Resource relation; @@ -35,7 +36,7 @@ public class RelatedObjectAccessor implements IDomainAccessor @Override public Resource get(ReadGraph g, Resource element) throws MappingException { try { - LOGGER.info(" RelatedObjectAccessor.get"); + LOGGER.trace(" RelatedObjectAccessor.get"); return g.getPossibleObject(element, relation); } catch (DatabaseException e) { throw new MappingException(e); @@ -46,7 +47,7 @@ public class RelatedObjectAccessor implements IDomainAccessor public boolean set(WriteGraph g, Resource element, Resource value) throws MappingException { try { - LOGGER.info(" RelatedObjectAccessor.set"); + LOGGER.trace(" RelatedObjectAccessor.set"); Resource resource = g.getPossibleObject(element, relation); if(resource == null) { if(value == null) diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedObjectsAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedObjectsAccessor.java index 9653ab370..d2d1db99a 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedObjectsAccessor.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedObjectsAccessor.java @@ -13,7 +13,8 @@ package org.simantics.objmap.graph.rules.domain; import java.util.Collection; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; @@ -26,7 +27,7 @@ import org.simantics.objmap.exceptions.MappingException; */ public class RelatedObjectsAccessor implements IDomainAccessor> { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(RelatedObjectsAccessor.class); Resource relation; boolean deleteExtraObjects; @@ -40,7 +41,7 @@ public class RelatedObjectsAccessor implements IDomainAccessor get(ReadGraph g, Resource element) throws MappingException { try { - LOGGER.info(" RelatedObjectsAccessor.get"); + LOGGER.trace(" RelatedObjectsAccessor.get"); return g.getObjects(element, relation); } catch (DatabaseException e) { throw new MappingException(e); @@ -51,7 +52,7 @@ public class RelatedObjectsAccessor implements IDomainAccessor value) throws MappingException { try { - LOGGER.info(" RelatedObjectsAccessor.set"); + LOGGER.trace(" RelatedObjectsAccessor.set"); return MappingUtils.synchronizeStatements(g, element, relation, value.toArray(new Resource[value.size()]), deleteExtraObjects); } catch (DatabaseException e) { diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedOrderedSetElementsAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedOrderedSetElementsAccessor.java index c033751e5..4d7895675 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedOrderedSetElementsAccessor.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedOrderedSetElementsAccessor.java @@ -13,7 +13,8 @@ package org.simantics.objmap.graph.rules.domain; import java.util.Collection; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; @@ -27,7 +28,7 @@ import org.simantics.objmap.exceptions.MappingException; */ public class RelatedOrderedSetElementsAccessor implements IDomainAccessor> { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(RelatedOrderedSetElementsAccessor.class); boolean deleteExtraObjects; @@ -39,7 +40,7 @@ public class RelatedOrderedSetElementsAccessor implements IDomainAccessor get(ReadGraph g, Resource element) throws MappingException { try { - LOGGER.info(" RelatedOrderedSetElementsAccessor.get"); + LOGGER.trace(" RelatedOrderedSetElementsAccessor.get"); return OrderedSetUtils.toList(g, element); } catch (DatabaseException e) { throw new MappingException(e); @@ -50,7 +51,7 @@ public class RelatedOrderedSetElementsAccessor implements IDomainAccessor value) throws MappingException { try { - LOGGER.info(" RelatedOrderedSetElementsAccessor.set"); + LOGGER.trace(" RelatedOrderedSetElementsAccessor.set"); return OrderedSetUtils.set(g, element, value); // FIXME Implement deleteExtraObjects } catch (DatabaseException e) { diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedValueAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedValueAccessor.java index d5ad40b77..9aa96d8e8 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedValueAccessor.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/domain/RelatedValueAccessor.java @@ -13,14 +13,20 @@ package org.simantics.objmap.graph.rules.domain; import java.util.Arrays; -import org.apache.log4j.Logger; +import org.simantics.databoard.binding.Binding; +import org.simantics.databoard.binding.OptionalBinding; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.Statement; import org.simantics.db.WriteGraph; +import org.simantics.db.exception.BindingException; import org.simantics.db.exception.DatabaseException; +import org.simantics.db.exception.DoesNotContainValueException; +import org.simantics.db.exception.ServiceException; import org.simantics.layer0.Layer0; import org.simantics.objmap.exceptions.MappingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Accesses a value attached to the element by given functional relation. @@ -28,34 +34,36 @@ import org.simantics.objmap.exceptions.MappingException; */ public class RelatedValueAccessor implements IDomainAccessor { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(RelatedValueAccessor.class); Resource relation; Resource valueType; + Binding valueBinding; - public RelatedValueAccessor(Resource relation, Resource valueType) { + public RelatedValueAccessor(Resource relation, Resource valueType, Binding valueBinding) { this.relation = relation; this.valueType = valueType; + this.valueBinding = valueBinding; } @Override public Object get(ReadGraph g, Resource element) throws MappingException { try { - LOGGER.info(" RelatedValueAccessor.get"); + LOGGER.trace(" RelatedValueAccessor.get"); Resource valueResource = g.getPossibleObject(element, relation); if(valueResource == null) return null; - return g.getValue(valueResource); + return getValue(g, valueResource); } catch (DatabaseException e) { throw new MappingException(e); } } - + @Override public boolean set(WriteGraph g, Resource element, Object value) throws MappingException { try { - LOGGER.info(" RelatedValueAccessor.set"); + LOGGER.trace(" RelatedValueAccessor.set"); Statement valueStatement = g.getPossibleStatement(element, relation); if(valueStatement == null) { if(value == null) @@ -64,7 +72,8 @@ public class RelatedValueAccessor implements IDomainAccessor { g.claim(valueResource, Layer0.getInstance(g).InstanceOf, null, valueType); g.claim(element, relation, valueResource); - g.claimValue(valueResource, value); + claimValue(g, valueResource, value); + return true; } else { @@ -76,7 +85,7 @@ public class RelatedValueAccessor implements IDomainAccessor { return false; } } - Object currentValue = g.getValue(valueStatement.getObject()); + Object currentValue = getValue(g, valueStatement.getObject()); if(equals(currentValue,value)) return false; if (!valueStatement.isAsserted(element)) @@ -86,7 +95,7 @@ public class RelatedValueAccessor implements IDomainAccessor { g.claim(valueResource, Layer0.getInstance(g).InstanceOf, null, valueType); g.claim(element, relation, valueResource); - g.claimValue(valueResource, value); + claimValue(g, valueResource, value); } return true; } @@ -95,8 +104,32 @@ public class RelatedValueAccessor implements IDomainAccessor { } } + + private Object getValue(ReadGraph g, Resource valueResource) + throws DoesNotContainValueException, BindingException, ServiceException { + if (valueBinding != null) { + return g.getValue(valueResource, getBaseBinding(valueBinding)); + } + else { + return g.getValue(valueResource); + } + } + + private void claimValue(WriteGraph g, Resource valueResource, Object value) throws ServiceException { + if (valueBinding != null) + g.claimValue(valueResource, value, getBaseBinding(valueBinding)); + else + g.claimValue(valueResource, value); + } + + private static Binding getBaseBinding(Binding binding) { + return binding instanceof OptionalBinding ? ((OptionalBinding)binding).getComponentBinding() : binding; + } private boolean equals(Object o1, Object o2) { + if (valueBinding != null) + return valueBinding.equals(o1, o2); + if (o1 instanceof boolean[]) Arrays.equals((boolean[])o1,(boolean[])o2); if (o1 instanceof int[]) @@ -108,7 +141,6 @@ public class RelatedValueAccessor implements IDomainAccessor { if (o1 instanceof byte[]) Arrays.equals((byte[])o1,(byte[])o2); return o1.equals(o2); - } } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/range/FieldAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/range/FieldAccessor.java index 6615e94fb..c5a35613c 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/range/FieldAccessor.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/rules/range/FieldAccessor.java @@ -13,8 +13,9 @@ package org.simantics.objmap.graph.rules.range; import java.lang.reflect.Field; -import org.apache.log4j.Logger; import org.simantics.objmap.exceptions.MappingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** @@ -23,7 +24,7 @@ import org.simantics.objmap.exceptions.MappingException; */ public class FieldAccessor implements IRangeAccessor { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static final Logger LOGGER = LoggerFactory.getLogger(FieldAccessor.class); Field field; @@ -37,8 +38,8 @@ public class FieldAccessor implements IRangeAccessor { @SuppressWarnings("unchecked") T result = (T)field.get(element); - if(LOGGER.isInfoEnabled()) - LOGGER.info(" FieldAccessor.get " + + if(LOGGER.isTraceEnabled()) + LOGGER.trace(" FieldAccessor.get " + field.getName() + " -> " + result ); @@ -55,8 +56,8 @@ public class FieldAccessor implements IRangeAccessor { try { Object currentValue = field.get(element); - if(LOGGER.isInfoEnabled()) - LOGGER.info(" FieldAccessor.set " + + if(LOGGER.isTraceEnabled()) + LOGGER.trace(" FieldAccessor.set " + field.getName() + " " + currentValue + " -> " + value ); diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/AdaptedLinkType.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/AdaptedLinkType.java index 046a744cf..9b02d5d50 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/AdaptedLinkType.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/AdaptedLinkType.java @@ -11,7 +11,7 @@ *******************************************************************************/ package org.simantics.objmap.graph.schema; -//import org.apache.log4j.Logger; +//import org.slf4j.Logger; import org.eclipse.core.runtime.IAdaptable; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/DynamicSimpleLinkType.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/DynamicSimpleLinkType.java index 792813bb1..4f44844db 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/DynamicSimpleLinkType.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/DynamicSimpleLinkType.java @@ -70,8 +70,8 @@ public class DynamicSimpleLinkType extends SimpleLinkType{ throws MappingException { try { String typeUri = (String)typeGetter.invoke(rangeElement, (Object[]) null); - if(LOGGER.isInfoEnabled()) - LOGGER.info("SimpleLinkType.createDomainElement " + + if(LOGGER.isTraceEnabled()) + LOGGER.trace("SimpleLinkType.createDomainElement " + rangeElement.toString() ); Resource actualDomainType = g.getResource(typeUri); @@ -95,9 +95,9 @@ public class DynamicSimpleLinkType extends SimpleLinkType{ public Range createRangeElement(ReadGraph g, Resource domainElement) throws MappingException { try { - if(LOGGER.isInfoEnabled()) + if(LOGGER.isTraceEnabled()) try { - LOGGER.info("SimpleLinkType.createRangeElement " + + LOGGER.trace("SimpleLinkType.createRangeElement " + NameUtils.getSafeName(g, domainElement) ); } catch(DatabaseException e) { diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/MappingSchemas.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/MappingSchemas.java index 871d46bda..cf2f3bf45 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/MappingSchemas.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/MappingSchemas.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012, 2013 Association for Decentralized Information Management in + * Copyright (c) 2012, 2013, 2019 Association for Decentralized Information Management in * Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 @@ -8,6 +8,7 @@ * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation + * Semantum oy - linked list mapping API and implementation *******************************************************************************/ package org.simantics.objmap.graph.schema; @@ -27,9 +28,12 @@ import org.simantics.objmap.graph.annotations.GraphType; import org.simantics.objmap.graph.annotations.HasCollectionAdder; import org.simantics.objmap.graph.annotations.HasCollectionRemover; import org.simantics.objmap.graph.annotations.HasSetter; +import org.simantics.objmap.graph.annotations.LinkedListGet; +import org.simantics.objmap.graph.annotations.LinkedList; import org.simantics.objmap.graph.annotations.OptionalRelatedElements; import org.simantics.objmap.graph.annotations.OrderedElementsGet; import org.simantics.objmap.graph.annotations.OrderedSetType; +import org.simantics.objmap.graph.annotations.RelatedElement; import org.simantics.objmap.graph.annotations.RelatedElements; import org.simantics.objmap.graph.annotations.RelatedElementsGet; import org.simantics.objmap.graph.annotations.RelatedGetObj; @@ -38,8 +42,11 @@ import org.simantics.objmap.graph.annotations.RelatedOrderedSetElements; import org.simantics.objmap.graph.annotations.RelatedValue; import org.simantics.objmap.graph.annotations.UpdateMethod; import org.simantics.objmap.graph.annotations.factories.CompoundRelatedGetSetValueRuleFactory; +import org.simantics.objmap.graph.annotations.factories.LinkedListRuleFactory; +import org.simantics.objmap.graph.annotations.factories.LinkedListRuleFactory2; import org.simantics.objmap.graph.annotations.factories.OptionalRelatedElementsRuleFactory; import org.simantics.objmap.graph.annotations.factories.OrderedElementsRuleFactory; +import org.simantics.objmap.graph.annotations.factories.RelatedElementRuleFactory; import org.simantics.objmap.graph.annotations.factories.RelatedElementsRuleFactory; import org.simantics.objmap.graph.annotations.factories.RelatedElementsRuleFactory2; import org.simantics.objmap.graph.annotations.factories.RelatedGetSetObjRuleFactory; @@ -57,52 +64,60 @@ import org.simantics.objmap.graph.rules.factory.ICollectionRuleFactory; import org.simantics.objmap.graph.rules.factory.IFieldRuleFactory; import org.simantics.objmap.graph.rules.factory.IGetSetRuleFactory; import org.simantics.objmap.graph.rules.factory.IMethodRuleFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class MappingSchemas { - /** + private static final Logger LOGGER = LoggerFactory.getLogger(MappingSchemas.class); + + /** * Creates a new SimpleLinkType based on the annotations in the given class. * @throws IllegalAccessException * @throws InstantiationException * @see GraphType * @see RelatedValue */ - public static SimpleLinkType fromAnnotations(ReadGraph g, Class clazz) throws DatabaseException, InstantiationException, IllegalAccessException { - GraphType graphType = clazz.getAnnotation(GraphType.class); - - if (graphType != null) { - ArrayList> rules = new ArrayList>(); - collectRulesFromAnnotations(g, clazz, rules); - - return new SimpleLinkType(g.getResource(graphType.value()), clazz, rules); - } - DynamicGraphType dynamicType = clazz.getAnnotation(DynamicGraphType.class); - if (dynamicType != null) { - ArrayList> rules = new ArrayList>(); - collectRulesFromAnnotations(g, clazz, rules); - - return new DynamicSimpleLinkType(g.getResource(dynamicType.value()), clazz, rules); - } - OrderedSetType orderedSetType = clazz.getAnnotation(OrderedSetType.class); - if (orderedSetType != null) { - ArrayList> rules = new ArrayList>(); - collectRulesFromAnnotations(g, clazz, rules); - - return new OrderedSetSimpleLinkType(g.getResource(orderedSetType.value()), clazz, rules); - } - throw new IllegalArgumentException("Class " + clazz.toString() + " does not contain annotations."); - } - - public static void collectRulesFromAnnotations(ReadGraph g, Class clazz, Collection> rules) throws DatabaseException, InstantiationException, IllegalAccessException { - Class superclass = clazz.getSuperclass(); - if(superclass != null) - collectRulesFromAnnotations(g, superclass, rules); - + public static SimpleLinkType fromAnnotations(ReadGraph g, Class clazz) throws DatabaseException, InstantiationException, IllegalAccessException { + GraphType graphType = clazz.getAnnotation(GraphType.class); + + if (graphType != null) { + ArrayList> rules = new ArrayList>(); + collectRulesFromAnnotations(g, clazz, rules); + + return new SimpleLinkType(g.getResource(graphType.value()), clazz, rules); + } + DynamicGraphType dynamicType = clazz.getAnnotation(DynamicGraphType.class); + if (dynamicType != null) { + ArrayList> rules = new ArrayList>(); + collectRulesFromAnnotations(g, clazz, rules); + + return new DynamicSimpleLinkType(g.getResource(dynamicType.value()), clazz, rules); + } + OrderedSetType orderedSetType = clazz.getAnnotation(OrderedSetType.class); + if (orderedSetType != null) { + ArrayList> rules = new ArrayList>(); + collectRulesFromAnnotations(g, clazz, rules); + + return new OrderedSetSimpleLinkType(g.getResource(orderedSetType.value()), clazz, rules); + } + throw new IllegalArgumentException("Class " + clazz.toString() + " does not contain annotations."); + } + + public static void collectRulesFromAnnotations(ReadGraph g, Class clazz, Collection> rules) throws DatabaseException, InstantiationException, IllegalAccessException { + Class superclass = clazz.getSuperclass(); + if(superclass != null) + collectRulesFromAnnotations(g, superclass, rules); + for(Annotation annotation : clazz.getAnnotations()) { - IsClassRule tag = annotation.annotationType().getAnnotation(IsClassRule.class); + IsClassRule tag = annotation.annotationType().getAnnotation(IsClassRule.class); if(tag!= null) { - rules.add(createClassRule(g, annotation, clazz).create(g, annotation, clazz)); + final IClassRuleFactory ruleFactory = createClassRule(g, annotation, clazz); + if (ruleFactory != null) + rules.add(ruleFactory.create(g, annotation, clazz)); + else + LOGGER.warn("No rule factory found for {}", annotation); } } @@ -111,9 +126,13 @@ public class MappingSchemas { for(Annotation annotation : f.getAnnotations()) { - IsFieldRule tag = annotation.annotationType().getAnnotation(IsFieldRule.class); + IsFieldRule tag = annotation.annotationType().getAnnotation(IsFieldRule.class); if(tag != null) { - rules.add(createFieldRule(g, annotation, f).create(g, annotation, f)); + final IFieldRuleFactory ruleFactory = createFieldRule(g, annotation, f); + if (ruleFactory != null) + rules.add(ruleFactory.create(g, annotation, f)); + else + LOGGER.warn("No rule factory found for {}", annotation); } } } @@ -122,140 +141,154 @@ public class MappingSchemas { m.setAccessible(true); for(Annotation annotation : m.getAnnotations()) { - IsMethodRule tag = + IsMethodRule tag = annotation.annotationType().getAnnotation(IsMethodRule.class); if(tag != null) { - rules.add(createMethodRule(g, annotation, m).create(g, annotation, m)); + final IMethodRuleFactory ruleFactory = createMethodRule(g, annotation, m); + if (ruleFactory != null) + rules.add(ruleFactory.create(g, annotation, m)); + else + LOGGER.warn("No rule factory found for {}", annotation); } } } - + for (Method m : clazz.getDeclaredMethods()) { - m.setAccessible(true); - for (Annotation annotation : m.getAnnotations()) { - Class annotationType = annotation.annotationType(); - - IsGetSetRule tag = - annotationType.getAnnotation(IsGetSetRule.class); - if (tag != null) { - - HasSetter setterAnnType = annotationType.getAnnotation(HasSetter.class); - - Class setterAnn = setterAnnType.value(); - - Method getter = m; - - IGetSetRuleFactory ruleFactory = createGetSetRuleFactory(g, annotation, getter); - - - Method setter = null; - - for (Method m2 : clazz.getDeclaredMethods()) { - Annotation set = m2.getAnnotation(setterAnn); - if (set != null && ruleFactory.isSetter(annotation, set)) - setter = m2; - } - - rules.add(ruleFactory.create(g, annotation, getter, setter)); - } - - } + m.setAccessible(true); + for (Annotation annotation : m.getAnnotations()) { + Class annotationType = annotation.annotationType(); + + IsGetSetRule tag = + annotationType.getAnnotation(IsGetSetRule.class); + if (tag != null) { + + HasSetter setterAnnType = annotationType.getAnnotation(HasSetter.class); + + Class setterAnn = setterAnnType.value(); + + Method getter = m; + + IGetSetRuleFactory ruleFactory = createGetSetRuleFactory(g, annotation, getter); + if (ruleFactory != null) { + Method setter = null; + + for (Method m2 : clazz.getDeclaredMethods()) { + Annotation set = m2.getAnnotation(setterAnn); + if (set != null && ruleFactory.isSetter(annotation, set)) + setter = m2; + } + + rules.add(ruleFactory.create(g, annotation, getter, setter)); + } + else { + LOGGER.warn("No rule factory found for {}", annotation); + } + } + + } } - + for (Method m : clazz.getDeclaredMethods()) { - m.setAccessible(true); - for (Annotation annotation : m.getAnnotations()) { - Class annotationType = annotation.annotationType(); - - IsCollectionRule tag = - annotationType.getAnnotation(IsCollectionRule.class); - if (tag != null) { - - HasCollectionAdder adderAnnType = annotationType.getAnnotation(HasCollectionAdder.class); - HasCollectionRemover removerAnnType = annotationType.getAnnotation(HasCollectionRemover.class); - - Class adderAnn = adderAnnType.value(); - Class removerAnn = removerAnnType.value(); - - Method getter = m; - - ICollectionRuleFactory ruleFactory = createCollectionRuleFactory(g, annotation, getter); - - - Method adder = null; - Method remover = null; - - for (Method m2 : clazz.getDeclaredMethods()) { - Annotation add = m2.getAnnotation(adderAnn); - Annotation rem = m2.getAnnotation(removerAnn); - if (add != null && ruleFactory.isAdder(annotation, add)) - adder = m2; - if (rem != null && ruleFactory.isRemover(annotation, rem)) - remover = m2; - } - - - - rules.add(ruleFactory.create(g, annotation, getter,adder,remover)); - } - - } + m.setAccessible(true); + for (Annotation annotation : m.getAnnotations()) { + Class annotationType = annotation.annotationType(); + + IsCollectionRule tag = + annotationType.getAnnotation(IsCollectionRule.class); + if (tag != null) { + + HasCollectionAdder adderAnnType = annotationType.getAnnotation(HasCollectionAdder.class); + HasCollectionRemover removerAnnType = annotationType.getAnnotation(HasCollectionRemover.class); + + Class adderAnn = adderAnnType.value(); + Class removerAnn = removerAnnType.value(); + + Method getter = m; + + ICollectionRuleFactory ruleFactory = createCollectionRuleFactory(g, annotation, getter); + if (ruleFactory != null) { + Method adder = null; + Method remover = null; + + for (Method m2 : clazz.getDeclaredMethods()) { + Annotation add = m2.getAnnotation(adderAnn); + Annotation rem = m2.getAnnotation(removerAnn); + if (add != null && ruleFactory.isAdder(annotation, add)) + adder = m2; + if (rem != null && ruleFactory.isRemover(annotation, rem)) + remover = m2; + } + + rules.add(ruleFactory.create(g, annotation, getter,adder,remover)); + } + else { + LOGGER.warn("No rule factory found for {}", annotation); + } + } + + } } } - - public static IClassRuleFactory createClassRule(ReadGraph g, Annotation annotation, Class clazz) { - return null; - } - - public static IFieldRuleFactory createFieldRule(ReadGraph g, Annotation annotation, Field field) { - if (annotation.annotationType().equals(RelatedElements.class)) - return new RelatedElementsRuleFactory(); - if (annotation.annotationType().equals(RelatedValue.class)) - return new RelatedValueRuleFactory(); - if (annotation.annotationType().equals(OptionalRelatedElements.class)) - return new OptionalRelatedElementsRuleFactory(); - if (annotation.annotationType().equals(RelatedOrderedSetElements.class)) - return new RelatedOrderedSetElementsRuleFactory(); - return null; - } - - public static IMethodRuleFactory createMethodRule(ReadGraph g, Annotation annotation, Method m) { - if (annotation.annotationType().equals(UpdateMethod.class)) - return new UpdateMethodFactory(); - return null; - } - - public static IGetSetRuleFactory createGetSetRuleFactory(ReadGraph g, Annotation annotation, Method getter) { - if (annotation.annotationType().equals(RelatedGetValue.class)) - return new RelatedGetSetValueRuleFactory(); - if (annotation.annotationType().equals(RelatedGetObj.class)) - return new RelatedGetSetObjRuleFactory(); - if (annotation.annotationType().equals(CompoundRelatedGetValue.class)) - return new CompoundRelatedGetSetValueRuleFactory(); - return null; - } - - public static ICollectionRuleFactory createCollectionRuleFactory(ReadGraph g, Annotation annotation, Method getter) { - if (annotation.annotationType().equals(RelatedElementsGet.class)) - return new RelatedElementsRuleFactory2(); - if (annotation.annotationType().equals(OrderedElementsGet.class)) - return new OrderedElementsRuleFactory(); - return null; - } - - /** + + public static IClassRuleFactory createClassRule(ReadGraph g, Annotation annotation, Class clazz) { + return null; + } + + public static IFieldRuleFactory createFieldRule(ReadGraph g, Annotation annotation, Field field) { + if (annotation.annotationType().equals(RelatedElement.class)) + return new RelatedElementRuleFactory(); + if (annotation.annotationType().equals(RelatedElements.class)) + return new RelatedElementsRuleFactory(); + if (annotation.annotationType().equals(RelatedValue.class)) + return new RelatedValueRuleFactory(); + if (annotation.annotationType().equals(OptionalRelatedElements.class)) + return new OptionalRelatedElementsRuleFactory(); + if (annotation.annotationType().equals(RelatedOrderedSetElements.class)) + return new RelatedOrderedSetElementsRuleFactory(); + if (annotation.annotationType().equals(LinkedList.class)) + return new LinkedListRuleFactory(); + return null; + } + + public static IMethodRuleFactory createMethodRule(ReadGraph g, Annotation annotation, Method m) { + if (annotation.annotationType().equals(UpdateMethod.class)) + return new UpdateMethodFactory(); + return null; + } + + public static IGetSetRuleFactory createGetSetRuleFactory(ReadGraph g, Annotation annotation, Method getter) { + if (annotation.annotationType().equals(RelatedGetValue.class)) + return new RelatedGetSetValueRuleFactory(); + if (annotation.annotationType().equals(RelatedGetObj.class)) + return new RelatedGetSetObjRuleFactory(); + if (annotation.annotationType().equals(CompoundRelatedGetValue.class)) + return new CompoundRelatedGetSetValueRuleFactory(); + return null; + } + + public static ICollectionRuleFactory createCollectionRuleFactory(ReadGraph g, Annotation annotation, Method getter) { + if (annotation.annotationType().equals(RelatedElementsGet.class)) + return new RelatedElementsRuleFactory2(); + if (annotation.annotationType().equals(OrderedElementsGet.class)) + return new OrderedElementsRuleFactory(); + if (annotation.annotationType().equals(LinkedListGet.class)) + return new LinkedListRuleFactory2<>(); + return null; + } + + /** * Creates a new SimpleLinkType based on the annotations in the given class. * @throws IllegalAccessException * @throws InstantiationException * @see GraphType * @see RelatedValue */ - - public static AdaptedLinkType fromAdaptable(ReadGraph g, String type, Class clazz) throws DatabaseException, InstantiationException, IllegalAccessException { - - - return new AdaptedLinkType(g.getResource(type), clazz); - } - - + + public static AdaptedLinkType fromAdaptable(ReadGraph g, String type, Class clazz) throws DatabaseException, InstantiationException, IllegalAccessException { + + + return new AdaptedLinkType(g.getResource(type), clazz); + } + + } diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/OrderedSetSimpleLinkType.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/OrderedSetSimpleLinkType.java index bd87c074f..748422df2 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/OrderedSetSimpleLinkType.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/OrderedSetSimpleLinkType.java @@ -20,8 +20,8 @@ public class OrderedSetSimpleLinkType extends SimpleLinkType { public Resource createDomainElement(org.simantics.db.WriteGraph g, Range rangeElement) throws org.simantics.objmap.exceptions.MappingException { try { - if(LOGGER.isInfoEnabled()) - LOGGER.info("SimpleLinkType.createDomainElement " + + if(LOGGER.isTraceEnabled()) + LOGGER.trace("SimpleLinkType.createDomainElement " + rangeElement.toString() ); Resource result = OrderedSetUtils.create(g, domainType); diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/SimpleLinkType.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/SimpleLinkType.java index fcfb3b012..9ddc43716 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/SimpleLinkType.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/graph/schema/SimpleLinkType.java @@ -13,7 +13,8 @@ package org.simantics.objmap.graph.schema; import java.util.ArrayList; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; @@ -34,7 +35,7 @@ import org.simantics.objmap.forward.IForwardMapping; */ public class SimpleLinkType implements ILinkType { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(SimpleLinkType.class); public Resource domainType; public Class rangeType; @@ -63,8 +64,8 @@ public class SimpleLinkType implements ILinkType { public Resource createDomainElement(WriteGraph g, Range rangeElement) throws MappingException { try { - if(LOGGER.isInfoEnabled()) - LOGGER.info("SimpleLinkType.createDomainElement " + + if(LOGGER.isTraceEnabled()) + LOGGER.trace("SimpleLinkType.createDomainElement " + rangeElement.toString() ); Resource result = g.newResource(); @@ -79,9 +80,9 @@ public class SimpleLinkType implements ILinkType { public Range createRangeElement(ReadGraph g, Resource domainElement) throws MappingException { try { - if(LOGGER.isInfoEnabled()) + if(LOGGER.isTraceEnabled()) try { - LOGGER.info("SimpleLinkType.createRangeElement " + + LOGGER.trace("SimpleLinkType.createRangeElement " + NameUtils.getSafeName(g, domainElement) ); } catch(DatabaseException e) { @@ -104,9 +105,9 @@ public class SimpleLinkType implements ILinkType { }; public boolean updateDomain(WriteGraph g, IBackwardMapping map, Resource domainElement, Range rangeElement) throws MappingException { - if(LOGGER.isInfoEnabled()) + if(LOGGER.isTraceEnabled()) try { - LOGGER.info("SimpleLinkType.updateDomain " + + LOGGER.trace("SimpleLinkType.updateDomain " + NameUtils.getSafeName(g, domainElement) + " " + rangeElement.toString() ); @@ -122,11 +123,11 @@ public class SimpleLinkType implements ILinkType { public boolean updateRange(ReadGraph g, IForwardMapping map, Resource domainElement, Range rangeElement) throws MappingException { - if(LOGGER.isInfoEnabled()) + if(LOGGER.isTraceEnabled()) try { - LOGGER.info("SimpleLinkType.updateRange " + + LOGGER.trace("SimpleLinkType.updateRange " + NameUtils.getSafeName(g, domainElement) + " " + - rangeElement.toString() + (rangeElement.getClass().getName() + "@" + Integer.toHexString(rangeElement.hashCode())) ); } catch(DatabaseException e) { throw new MappingException(e); diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/annotations/factories/UpdateMethodFactory.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/annotations/factories/UpdateMethodFactory.java index a5dc78f91..a2be5fa42 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/annotations/factories/UpdateMethodFactory.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/annotations/factories/UpdateMethodFactory.java @@ -14,7 +14,8 @@ package org.simantics.objmap.structural.annotations.factories; import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.WriteGraph; import org.simantics.db.exception.DatabaseException; @@ -26,7 +27,7 @@ import org.simantics.objmap.graph.rules.factory.IMethodRuleFactory; public class UpdateMethodFactory implements IMethodRuleFactory { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(UpdateMethodFactory.class); @Override public IBidirectionalMappingRule create(ReadGraph g, @@ -40,7 +41,7 @@ public class UpdateMethodFactory implements IMethodRuleFactory map, Domain domainElement, Range rangeElement) throws MappingException { - LOGGER.info(" UpdateMethodFactory.updateRange"); + LOGGER.trace(" UpdateMethodFactory.updateRange"); try { return (Boolean)method.invoke(rangeElement, g, domainElement); } catch (Exception e) { diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedObjectAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedObjectAccessor.java index 295e60e2f..de80a9a95 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedObjectAccessor.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedObjectAccessor.java @@ -11,7 +11,8 @@ *******************************************************************************/ package org.simantics.objmap.structural.rules.domain; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; @@ -23,7 +24,7 @@ import org.simantics.objmap.structural.StructuralResource; public class RelatedObjectAccessor implements IDomainAccessor { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(RelatedObjectAccessor.class); Resource relation; boolean useTypeResource; @@ -50,7 +51,7 @@ public class RelatedObjectAccessor implements IDomainAccessor> { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(RelatedObjectsAccessor.class); Resource relation; boolean deleteExtraObjects; @@ -57,7 +58,7 @@ public class RelatedObjectsAccessor implements IDomainAccessor get(ReadGraph g, StructuralResource element) throws MappingException { try { - LOGGER.info(" RelatedObjectsAccessor.get"); + LOGGER.trace(" RelatedObjectsAccessor.get"); Resource res = getServiceResource(g, element); @@ -86,7 +87,7 @@ public class RelatedObjectsAccessor implements IDomainAccessor value) throws MappingException { try { - LOGGER.info(" RelatedObjectsAccessor.set"); + LOGGER.trace(" RelatedObjectsAccessor.set"); Resource res = getServiceResource(g, element); if (res == null) return false; diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedOrderedSetElementsAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedOrderedSetElementsAccessor.java index 6c1ed3aa2..35f98994d 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedOrderedSetElementsAccessor.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedOrderedSetElementsAccessor.java @@ -16,7 +16,8 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; @@ -28,7 +29,7 @@ import org.simantics.objmap.structural.StructuralResource; public class RelatedOrderedSetElementsAccessor implements IDomainAccessor> { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(RelatedOrderedSetElementsAccessor.class); boolean deleteExtraObjects; boolean useTypeResource; @@ -42,7 +43,7 @@ public class RelatedOrderedSetElementsAccessor implements IDomainAccessor get(ReadGraph g, StructuralResource element) throws MappingException { try { - LOGGER.info(" RelatedOrderedSetElementsAccessor.get"); + LOGGER.trace(" RelatedOrderedSetElementsAccessor.get"); Resource res = getServiceResource(g, element); if (res == null) return Collections.emptyList(); @@ -61,7 +62,7 @@ public class RelatedOrderedSetElementsAccessor implements IDomainAccessor value) throws MappingException { try { - LOGGER.info(" RelatedOrderedSetElementsAccessor.set"); + LOGGER.trace(" RelatedOrderedSetElementsAccessor.set"); Resource res = getServiceResource(g, element); if (res == null) return false; diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedValueAccessor.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedValueAccessor.java index 2d3a24230..21a6733a4 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedValueAccessor.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/rules/domain/RelatedValueAccessor.java @@ -13,7 +13,8 @@ package org.simantics.objmap.structural.rules.domain; import java.util.Arrays; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.Statement; @@ -27,7 +28,7 @@ import org.simantics.objmap.structural.StructuralResource; public class RelatedValueAccessor implements IDomainAccessor { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(RelatedValueAccessor.class); Resource relation; Resource valueType; @@ -57,7 +58,7 @@ public class RelatedValueAccessor implements IDomainAccessor { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(StructuralRelatedObjectAccessor.class); Resource relation; boolean useTypeResource; @@ -54,7 +55,7 @@ public class StructuralRelatedObjectAccessor implements IDomainAccessor> { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(StructuralRelatedObjectsAccessor.class); Resource relation; boolean deleteExtraObjects; @@ -43,7 +44,7 @@ public class StructuralRelatedObjectsAccessor implements IDomainAccessor get(ReadGraph g, StructuralResource element) throws MappingException { try { - LOGGER.info(" RelatedObjectsAccessor.get"); + LOGGER.trace(" RelatedObjectsAccessor.get"); if (!element.isStructural()) return Collections.emptyList(); @@ -78,7 +79,7 @@ public class StructuralRelatedObjectsAccessor implements IDomainAccessor value) throws MappingException { try { - LOGGER.info(" RelatedObjectsAccessor.set"); + LOGGER.trace(" RelatedObjectsAccessor.set"); if (!element.isStructural()) return false; diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/schema/AdaptedLinkType.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/schema/AdaptedLinkType.java index 4f5508486..203863a6c 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/schema/AdaptedLinkType.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/schema/AdaptedLinkType.java @@ -11,7 +11,7 @@ *******************************************************************************/ package org.simantics.objmap.structural.schema; -//import org.apache.log4j.Logger; +//import org.slf4j.Logger; import org.eclipse.core.runtime.IAdaptable; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; diff --git a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/schema/SimpleLinkType.java b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/schema/SimpleLinkType.java index 8a7091fd4..77b2ab094 100644 --- a/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/schema/SimpleLinkType.java +++ b/bundles/org.simantics.objmap2/src/org/simantics/objmap/structural/schema/SimpleLinkType.java @@ -15,7 +15,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.WriteGraph; @@ -34,7 +35,7 @@ import org.simantics.objmap.structural.StructuralResource; public class SimpleLinkType implements ILinkType { - static Logger LOGGER = Logger.getLogger("org.simantics.objmap"); + static Logger LOGGER = LoggerFactory.getLogger(SimpleLinkType.class); public Resource domainType; public Class rangeType; @@ -63,8 +64,8 @@ public class SimpleLinkType implements ILinkType map, StructuralResource domainElement, IStructuralObject rangeElement) throws MappingException { - if(LOGGER.isInfoEnabled()) + if(LOGGER.isTraceEnabled()) try { - LOGGER.info("SimpleLinkType.updateDomain " + + LOGGER.trace("SimpleLinkType.updateDomain " + NameUtils.getSafeName(g, domainElement.getResource()) + " " + rangeElement.toString() ); @@ -172,9 +173,9 @@ public class SimpleLinkType implements ILinkType map, StructuralResource domainElement, IStructuralObject rangeElement) throws MappingException { - if(LOGGER.isInfoEnabled()) + if(LOGGER.isTraceEnabled()) try { - LOGGER.info("SimpleLinkType.updateRange " + + LOGGER.trace("SimpleLinkType.updateRange " + NameUtils.getSafeName(g, domainElement.getResource()) + " " + rangeElement.toString() ); diff --git a/bundles/org.simantics.project/src/org/simantics/project/management/ServerManagerFactory.java b/bundles/org.simantics.project/src/org/simantics/project/management/ServerManagerFactory.java index 444585bbd..feec73dc9 100644 --- a/bundles/org.simantics.project/src/org/simantics/project/management/ServerManagerFactory.java +++ b/bundles/org.simantics.project/src/org/simantics/project/management/ServerManagerFactory.java @@ -11,16 +11,7 @@ *******************************************************************************/ package org.simantics.project.management; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLDecoder; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; import org.simantics.db.DatabaseUserAgent; import org.simantics.db.Driver; @@ -42,168 +33,5 @@ public class ServerManagerFactory { driver.setDatabaseUserAgent(address, agent); return new ServerManager(driver); } - /** - * Create a server manager in OSGi platform. - * - * @return - * @throws IOException - * @throws ClassNotFoundException - * @throws RuntimeException unexpected problem with OSGi environment - */ - public static ServerManager createOSGI() throws IOException, RuntimeException { - try { - ClassLoader cl = ServerManager.class.getClassLoader(); - - // Object bundle = Platform.getBundle("org.simantics.db.build"); - Class Platform_class = cl.loadClass("org.eclipse.core.runtime.Platform"); - Method Platform_getBundle = Platform_class.getMethod("getBundle", String.class); - Object bundle = Platform_getBundle.invoke(null, "org.simantics.db.build"); - if (bundle==null) throw new RuntimeException("Bundle org.simantics.db.build not found."); - - // URL db_build_url = bundle.getEntry("/"); - Class Bundle_class = cl.loadClass("org.osgi.framework.Bundle"); - Method Bundle_getEntry = Bundle_class.getMethod("getEntry", String.class); - URL db_build_url = (URL) Bundle_getEntry.invoke(bundle, "/"); - - // URL db_build_file_url = FileLocator.toFileURL( db_build_url ); - Class FileLocator_class = cl.loadClass("org.eclipse.core.runtime.FileLocator"); - Method FileLocator_toFileURL = FileLocator_class.getMethod("toFileURL", URL.class); - URL db_build_file_url = (URL) FileLocator_toFileURL.invoke(null, db_build_url); - - @SuppressWarnings("unused") - String buildFile = URLDecoder.decode(db_build_file_url.getPath(), "UTF-8"); - -// File db_build_file = new File( buildFile ); - //return new ServerManager( db_build_file ); - throw new RuntimeException("ServerManager.createOSGI not implemented."); - } catch( ClassNotFoundException e ) { - throw new RuntimeException(e); - } catch (SecurityException e) { - throw new RuntimeException(e); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } catch (IllegalArgumentException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (InvocationTargetException e) { - throw new RuntimeException(e.getCause()); - } - } - - /** - * Create a server manager in an POJO environment. - * - * @return - * @throws IOException - */ - public static ServerManager createPOJO() throws IOException { - String tempPath = System.getenv("tmp"); - if (tempPath==null) tempPath = "c:/temp/"; - File driverDir = new File(tempPath+"/core_drivers"); - if (!driverDir.exists()) { - System.out.println("Extracting Core drivers to "+driverDir); - driverDir.mkdirs(); - ServerManagerFactory.extractDrivers(driverDir); - } else { - System.out.println("Loading Core drivers from "+driverDir); - } - //return new ServerManager(driverDir); - throw new RuntimeException("ServerManager.createPOJO not implemented."); - } - - public static ServerManager createPOJO(File driverDir) throws IOException { - //return new ServerManager(driverDir); - throw new RuntimeException("ServerManager.createPOJO not implemented."); - } - - static ServerManager cached; - - public static boolean isOSGi() { - try { - ServerManager.class.getClassLoader().loadClass("org.osgi.framework.Bundle"); - return true; - } catch (ClassNotFoundException e) { - return false; - } - } - - public synchronized static ServerManager getServerManager() { - if (cached!=null) return cached; - try { - try { - return createOSGI(); - } catch(RuntimeException e) { - return createPOJO(); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - - /** - * Extracts drivers files to a location. - * - * @param path location where to extract application files - * @throws IOException - */ - public static void extractDrivers(File path) - throws IOException - { - // Extract org.simantics.db.build.zip to workspace - InputStream is = ServerManager.class.getResource("org.simantics.db.build.zip").openStream(); - try { - extractZip(is, path); - } finally { - is.close(); - } - } - - /** - * Extract a zip file into a directory - * - * @param zipInput - * @param dst directory - * @throws IOException - */ - private static void extractZip(InputStream zipInput, File dst) throws IOException { - byte[] buf = new byte[8192]; - ZipInputStream zis = new ZipInputStream(zipInput); - ZipEntry entry; - - entry = zis.getNextEntry(); - while (entry != null) { - // for each entry to be extracted - String name = entry.getName(); - LOGGER.debug("Extracting "+name); - File file = new File(dst, name); - - if (entry.isDirectory()) - { - if ( !file.exists() ) file.mkdirs(); - } else { - File parent = file.getParentFile(); - if (!parent.exists()) parent.mkdirs(); - if (!file.exists()) file.createNewFile(); - - FileOutputStream fileoutputstream = new FileOutputStream(file); - try { - int n = 0; - while ((n = zis.read(buf, 0, buf.length)) > -1) - fileoutputstream.write(buf, 0, n); - } finally { - fileoutputstream.close(); - } - } - - zis.closeEntry(); - entry = zis.getNextEntry(); - }// while - - zis.close(); - } - - -} +} \ No newline at end of file diff --git a/bundles/org.simantics.project/src/org/simantics/project/management/org.simantics.db.build.zip b/bundles/org.simantics.project/src/org/simantics/project/management/org.simantics.db.build.zip deleted file mode 100644 index e31cdabd4..000000000 Binary files a/bundles/org.simantics.project/src/org/simantics/project/management/org.simantics.db.build.zip and /dev/null differ diff --git a/bundles/org.simantics.project/src/org/simantics/project/management/server_template.cnfg b/bundles/org.simantics.project/src/org/simantics/project/management/server_template.cnfg deleted file mode 100644 index 840437855..000000000 --- a/bundles/org.simantics.project/src/org/simantics/project/management/server_template.cnfg +++ /dev/null @@ -1,27 +0,0 @@ -# Journal options. -# If 0 then write journal. (default) -# If 1 then write journal with additional debug information. -# If 2 then do not write journal. -journal_reportFileMode=1 - -# Log file. -common_logFile=../server.log - -# Log levels. -#common_logLevels=trace -#common_logLevels=debug -#common_logLevels=info -#common_logLevels=warning - -# Log packages. -#common_logPackages=main -#common_logPackages=session -#common_logPackages=memory -#common_logPackages=transaction -#common_logPackages=extension -#common_logPackages=utility -#common_logPackages=test -#common_logPackages=value -#common_logPackages=revision -#common_logPackages=graph -#common_logPackages=page diff --git a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/markdown/html/SCLDocumentationExtensionNodeHandler.java b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/markdown/html/SCLDocumentationExtensionNodeHandler.java index d9e65e28c..e719aaf8c 100644 --- a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/markdown/html/SCLDocumentationExtensionNodeHandler.java +++ b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/markdown/html/SCLDocumentationExtensionNodeHandler.java @@ -178,7 +178,7 @@ public class SCLDocumentationExtensionNodeHandler implements ExtensionNodeHandle StringBuilder signature = new StringBuilder(); signature.append("
"); + .append("\" class=\"code-doc-box\">
"); char firstChar = name.charAt(0); if(!Character.isAlphabetic(firstChar) && firstChar != '_') name = "(" + name + ")"; @@ -231,7 +231,9 @@ public class SCLDocumentationExtensionNodeHandler implements ExtensionNodeHandle TypeUnparsingContext tuc = new TypeUnparsingContext(); StringBuilder signature = new StringBuilder(); - signature.append("
"); + signature.append("
"); signature.append("class "); if(typeClass.context.length > 0) { signature.append('('); @@ -293,7 +295,9 @@ public class SCLDocumentationExtensionNodeHandler implements ExtensionNodeHandle TypeUnparsingContext tuc = new TypeUnparsingContext(); StringBuilder signature = new StringBuilder(); - signature.append("
"); + signature.append("
"); signature.append("data "); signature.append(typeDescriptor.name.name); if(typeDescriptor instanceof TypeConstructor) { diff --git a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/markdown/html/SclDoc.css b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/markdown/html/SclDoc.css index 27ecb48eb..7dd204348 100644 --- a/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/markdown/html/SclDoc.css +++ b/bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/markdown/html/SclDoc.css @@ -491,7 +491,6 @@ vertical-align:1px; .code-doc-box>.code { font-size: 12px; font-family: Consolas, "Liberation Mono", Courier, monospace; - background-color: #f0f0ff; white-space: pre; padding: 10px 15px; border-bottom: 1px solid; @@ -500,7 +499,19 @@ vertical-align:1px; display: block; } -.code-doc-box>.doc {display: block; +.code-doc-box>.value { + background-color: #f0f0ff; +} + +.code-doc-box>.data { + background-color: #f0fff0; +} + +.code-doc-box>.class { + background-color: #fff0f0; +} + +.code-doc-box>.doc { padding: 0px 15px ; display: block; } diff --git a/bundles/org.simantics.scl.db/scl/Simantics/DB.scl b/bundles/org.simantics.scl.db/scl/Simantics/DB.scl index af8c19476..b69119eae 100644 --- a/bundles/org.simantics.scl.db/scl/Simantics/DB.scl +++ b/bundles/org.simantics.scl.db/scl/Simantics/DB.scl @@ -250,13 +250,6 @@ importJava "org.simantics.db.WriteGraph" where @JavaName denyValue denyValue :: Resource -> () -claimAssertion :: Resource -> Resource -> Resource -> () -claimAssertion type_ predicate object = do - ass = newResource () - claim ass L0.HasPredicate predicate - claim ass L0.HasObject object - claim type_ L0.Asserts ass - "Sets the value of the literal that is an object with the given subject and predicate." @inline claimRelatedValue :: Serializable a => Resource -> Resource -> a -> () @@ -415,6 +408,9 @@ importJava "org.simantics.db.layer0.util.Layer0Utils" where addMetadataListener :: ChangeListener -> () removeMetadataListener :: ChangeListener -> () + @JavaName assert_ + claimAssertion :: Resource -> Resource -> Resource -> () + copyTo :: Resource -> Resource -> Resource copyTo targetContainer source = do (collectionToList $ copyTo_ targetContainer source)!0 diff --git a/bundles/org.simantics.scl.db/src/org/simantics/scl/db/SCLFunctions.java b/bundles/org.simantics.scl.db/src/org/simantics/scl/db/SCLFunctions.java index f3d4c3430..e20dfc471 100644 --- a/bundles/org.simantics.scl.db/src/org/simantics/scl/db/SCLFunctions.java +++ b/bundles/org.simantics.scl.db/src/org/simantics/scl/db/SCLFunctions.java @@ -1,6 +1,8 @@ package org.simantics.scl.db; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import org.cojen.classfile.TypeDesc; import org.simantics.Simantics; @@ -25,14 +27,24 @@ import org.simantics.db.service.QueryControl; import org.simantics.db.service.SerialisationSupport; import org.simantics.db.service.VirtualGraphSupport; import org.simantics.layer0.utils.triggers.IActivationManager; +import org.simantics.scl.compiler.elaboration.modules.SCLValue; import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification; +import org.simantics.scl.compiler.errors.DoesNotExist; import org.simantics.scl.compiler.errors.Failable; +import org.simantics.scl.compiler.errors.Failure; import org.simantics.scl.compiler.internal.codegen.types.JavaTypeTranslator; import org.simantics.scl.compiler.module.Module; import org.simantics.scl.compiler.module.repository.ImportFailureException; import org.simantics.scl.compiler.runtime.RuntimeEnvironment; +import org.simantics.scl.compiler.runtime.RuntimeModule; +import org.simantics.scl.compiler.top.ValueNotFound; +import org.simantics.scl.compiler.types.TCon; import org.simantics.scl.compiler.types.Type; +import org.simantics.scl.compiler.types.Types; +import org.simantics.scl.compiler.types.exceptions.MatchException; +import org.simantics.scl.compiler.types.util.MultiFunction; import org.simantics.scl.osgi.SCLOsgi; +import org.simantics.scl.reflection.ValueNotFoundException; import org.simantics.scl.runtime.SCLContext; import org.simantics.scl.runtime.function.Function; import org.simantics.scl.runtime.function.Function1; @@ -58,8 +70,95 @@ public class SCLFunctions { return null; } } + + public static Function resolveFunction(RuntimeModule rm, String function) throws ValueNotFound { + return (Function)rm.getValue(function); + } + + private static SCLValue resolveSCLValue(RuntimeModule rm, String function) throws ValueNotFound { + return rm.getModule().getValue(function); + } + + private static RuntimeModule resolveRuntimeModule(String module) throws ValueNotFound { + Failable f = SCLOsgi.MODULE_REPOSITORY.getRuntimeModule(module); + if(f.didSucceed()) + return f.getResult(); + else if(f == DoesNotExist.INSTANCE) + throw new ValueNotFound("Didn't find module " + module); + else + throw new ValueNotFound(((Failure)f).toString()); + } + + private static List getEffects(SCLValue value) throws ValueNotFoundException, ValueNotFound, MatchException { + + Type type = value.getType(); + MultiFunction mfun = Types.matchFunction(type, 1); + ArrayList concreteEffects = new ArrayList<>(); + mfun.effect.collectConcreteEffects(concreteEffects); + return concreteEffects; + + } + + public static List getEffects(RuntimeModule rm, String function) throws ValueNotFoundException, ValueNotFound, MatchException { + return getEffects(resolveSCLValue(rm, function)); + } + + public static List getEffects(String module, String function) throws ValueNotFoundException, ValueNotFound, MatchException { + return getEffects(resolveSCLValue(resolveRuntimeModule(module), function)); + } + + private static T evaluate(Function function, Object ... args) { + return (T)function.applyArray(args); + } + + private static T evaluate(RuntimeModule rm, String function, Object ... args) throws ValueNotFound { + return evaluate(resolveFunction(rm, function)); + } + + public static T evaluate(String module, String function, Object ... args) throws ValueNotFound { + return evaluate(resolveRuntimeModule(module), function, args); + } + + public static T evaluateDB(String module, String function, Object ... args) throws DatabaseException { + try { + RuntimeModule rm = resolveRuntimeModule(module); + List effects = getEffects(resolveSCLValue(rm, function)); + Function f = resolveFunction(rm, function); + if(effects.contains(Types.WRITE_GRAPH)) { + return syncWrite(f, args); + } else if(effects.contains(Types.READ_GRAPH)) { + return syncRead(f, args); + } else { + return evaluate(f, args); + } + } catch (ValueNotFound e) { + throw new DatabaseException("SCL Value not found: " + e.name); + } catch (Throwable t) { + if (t instanceof DatabaseException) + throw (DatabaseException) t; + throw new DatabaseException(t); + } + } - public static void asyncRead(final Function f) throws DatabaseException { + public static T evaluateGraph(String module, String function, Object graph, Object ... args) throws DatabaseException { + final SCLContext context = SCLContext.getCurrent(); + SCLContext.push(context); + Object oldGraph = context.put(GRAPH, graph); + try { + return evaluateDB(module, function, args); + } finally { + context.put(GRAPH, oldGraph); + SCLContext.pop(); + } + } + + private static Object[] NO_ARGS = new Object[] { Tuple0.INSTANCE }; + + public static void asyncRead(final Function f) throws DatabaseException { + asyncRead(f, NO_ARGS); + } + + public static void asyncRead(final Function f, final Object ... args) throws DatabaseException { final SCLContext context = SCLContext.createDerivedContext(); Simantics.getSession().asyncRequest(new ReadRequest() { @Override @@ -76,10 +175,14 @@ public class SCLFunctions { } public static T syncRead(final Function f) throws DatabaseException { + return syncRead(f, NO_ARGS); + } + + public static T syncRead(final Function f, final Object ... args) throws DatabaseException { final SCLContext context = SCLContext.getCurrent(); Object graph = context.get(GRAPH); if (graph != null) { - return (T)f.apply(Tuple0.INSTANCE); + return (T)f.applyArray(args); } else { return Simantics.getSession().syncRequest(new Read() { @Override @@ -96,8 +199,12 @@ public class SCLFunctions { }); } } - + public static void asyncWrite(final Function f) throws DatabaseException { + asyncWrite(f, NO_ARGS); + } + + public static void asyncWrite(final Function f, final Object ... args) throws DatabaseException { SCLContext context = SCLContext.createDerivedContext(); if (Simantics.peekSession() != null) { Simantics.getSession().asyncRequest(new WriteRequest() { @@ -106,7 +213,7 @@ public class SCLFunctions { SCLContext.push(context); context.put(GRAPH, graph); try { - f.apply(Tuple0.INSTANCE); + f.apply(args); } finally { SCLContext.pop(); } @@ -118,6 +225,10 @@ public class SCLFunctions { } public static T syncWrite(final Function f) throws DatabaseException { + return syncWrite(f, NO_ARGS); + } + + public static T syncWrite(final Function f, final Object ... args) throws DatabaseException { final SCLContext context = SCLContext.getCurrent(); Object graph = context.get(GRAPH); if (graph != null) { @@ -131,7 +242,7 @@ public class SCLFunctions { SCLReportingHandler oldPrinter = (SCLReportingHandler)context.put(SCLReportingHandler.REPORTING_HANDLER, printer); ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph); try { - return (T)f.apply(Tuple0.INSTANCE); + return (T)f.apply(args); } finally { context.put(GRAPH, oldGraph); context.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter); @@ -144,13 +255,13 @@ public class SCLFunctions { public static T delayedSyncWrite(final Function f) throws DatabaseException { final SCLContext context = SCLContext.getCurrent(); - final DataContainer dc = new DataContainer(null); + final DataContainer dc = new DataContainer(null); DelayedWriteRequest request = new DelayedWriteRequest() { @Override public void perform(WriteGraph graph) throws DatabaseException { - final SCLContext context = SCLContext.getCurrent(); - SCLContext.push(context); + final SCLContext context = SCLContext.getCurrent(); + SCLContext.push(context); ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph); try { dc.set((T)f.apply(Tuple0.INSTANCE)); @@ -160,18 +271,18 @@ public class SCLFunctions { } } }; - + Object graph = context.get(GRAPH); if (graph != null) { if (graph instanceof WriteGraph) { - ((WriteGraph)graph).syncRequest(request); + ((WriteGraph)graph).syncRequest(request); } else { - throw new DatabaseException("Caller is inside a read transaction."); + throw new DatabaseException("Caller is inside a read transaction."); } } else { Simantics.getSession().syncRequest(request); } - return dc.get(); + return dc.get(); } public static T virtualSyncWriteMem(WriteGraph graph, String virtualGraphId, final Function f) throws DatabaseException { @@ -217,7 +328,7 @@ public class SCLFunctions { @Override public T perform(ReadGraph graph) throws DatabaseException { return Variables.getVariable(graph, uri).getValue(graph); - } + } }); } @@ -226,7 +337,7 @@ public class SCLFunctions { @Override public void perform(WriteGraph graph) throws DatabaseException { Variables.getVariable(graph, uri).setValue(graph, value); - } + } }); } @@ -257,23 +368,23 @@ public class SCLFunctions { public static class SCLUnaryRead extends BinaryRead, Object, Object> { - public SCLUnaryRead(Function1 parameter1, Object parameter2) { - super(parameter1, parameter2); - } + public SCLUnaryRead(Function1 parameter1, Object parameter2) { + super(parameter1, parameter2); + } + + @Override + public Object perform(ReadGraph graph) throws DatabaseException { + return Simantics.applySCLRead(graph, parameter, parameter2); + } - @Override - public Object perform(ReadGraph graph) throws DatabaseException { - return Simantics.applySCLRead(graph, parameter, parameter2); - } - } public static Object unaryQuery(ReadGraph graph, Function1 fn, Object value) throws DatabaseException { - return graph.syncRequest(new SCLUnaryRead(fn, value)); + return graph.syncRequest(new SCLUnaryRead(fn, value)); } public static Object unaryQueryCached(ReadGraph graph, Function1 fn, Object value) throws DatabaseException { - return graph.syncRequest(new SCLUnaryRead(fn, value), TransientCacheAsyncListener.instance()); + return graph.syncRequest(new SCLUnaryRead(fn, value), TransientCacheAsyncListener.instance()); } @@ -318,15 +429,15 @@ public class SCLFunctions { } public static Object possibleFromDynamic(Type expectedType, String moduleName, Object value) { - + try { - + Failable failable = SCLOsgi.MODULE_REPOSITORY.getModule(moduleName); Module module = failable.getResult(); - RuntimeEnvironment env = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment( - EnvironmentSpecification.of(moduleName, ""), module.getParentClassLoader()); + RuntimeEnvironment env = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment( + EnvironmentSpecification.of(moduleName, ""), module.getParentClassLoader()); JavaTypeTranslator tr = new JavaTypeTranslator(env.getEnvironment()); TypeDesc desc = tr.toTypeDesc(expectedType); @@ -342,22 +453,22 @@ public class SCLFunctions { public static void restrictQueries(ReadGraph graph, int amount, int step, int maxTimeInMs) { - QueryControl qc = graph.getService(QueryControl.class); - long start = System.currentTimeMillis(); - while(true) { - int current = qc.count(); - if(current < amount) return; - qc.gc(graph, step); - long duration = System.currentTimeMillis() - start; - if(duration > maxTimeInMs) return; - } + QueryControl qc = graph.getService(QueryControl.class); + long start = System.currentTimeMillis(); + while(true) { + int current = qc.count(); + if(current < amount) return; + qc.gc(graph, step); + long duration = System.currentTimeMillis() - start; + if(duration > maxTimeInMs) return; + } } public static int countQueries(ReadGraph graph) { - QueryControl qc = graph.getService(QueryControl.class); - return qc.count(); + QueryControl qc = graph.getService(QueryControl.class); + return qc.count(); } diff --git a/bundles/org.simantics.scl.ui/src/org/simantics/scl/ui/outline/SCLModuleOutlinePage.java b/bundles/org.simantics.scl.ui/src/org/simantics/scl/ui/outline/SCLModuleOutlinePage.java index 80e34c374..f19081754 100644 --- a/bundles/org.simantics.scl.ui/src/org/simantics/scl/ui/outline/SCLModuleOutlinePage.java +++ b/bundles/org.simantics.scl.ui/src/org/simantics/scl/ui/outline/SCLModuleOutlinePage.java @@ -30,6 +30,7 @@ import org.simantics.scl.osgi.SCLOsgi; import org.simantics.scl.ui.Activator; import org.simantics.scl.ui.editor2.SCLModuleEditor2; import org.simantics.scl.ui.editor2.SCLModuleEditorInput; +import org.simantics.utils.ui.SWTUtils; public class SCLModuleOutlinePage extends ContentOutlinePage { @@ -69,16 +70,20 @@ public class SCLModuleOutlinePage extends ContentOutlinePage { @Override public void notifyAboutUpdate() { - parent.getDisplay().asyncExec(() -> { + if (parent.isDisposed()) + return; + + Failable module = SCLOsgi.MODULE_REPOSITORY.getModule(moduleSource.getModuleName(), updateListener); + SWTUtils.asyncExec(parent, () -> { if (!outlineViewer.getControl().isDisposed()) { + outlineViewer.setInput(module.didSucceed() ? module.getResult() : null); outlineViewer.refresh(); } }); } }; - Failable module = SCLOsgi.MODULE_REPOSITORY.getModule(moduleSource.getModuleName(), updateListener); - Module result = module.getResult(); - outlineViewer.setInput(result); + + updateListener.notifyAboutUpdate(); } @Override diff --git a/bundles/org.simantics.selectionview.ontology/graph/Selectionview.pgraph b/bundles/org.simantics.selectionview.ontology/graph/Selectionview.pgraph index 861f705d7..c38966f65 100644 --- a/bundles/org.simantics.selectionview.ontology/graph/Selectionview.pgraph +++ b/bundles/org.simantics.selectionview.ontology/graph/Selectionview.pgraph @@ -112,8 +112,7 @@ SEL.GenericParameterType (climbed.size()); needDrill.add(desc); } else { + if(relationType != null) { + if(!filterByRelationType(graph, desc, relationType)) + continue; + } if(result == null) result = new THashSet(climbed.size()); result.add(desc); } } - if(needDrill == null) { - /* - * All descriptors were already flat - just take case of filtering - */ - if(relationType != null) { - ArrayList filtered = new ArrayList(climbed.size()); - for(VariableConnectionPointDescriptor desc : climbed) - if(filterByRelationType(graph, desc, relationType)) - filtered.add(desc); - return filtered; - } else { - return climbed; + if(needDrill != null) { + /* + * There were some descriptors that require drill + */ + for(VariableConnectionPointDescriptor top : needDrill) { + Collection drilled = drill(graph, top); + if(drilled != null) { + for(VariableConnectionPointDescriptor drill : drilled) { + if(relationType != null) { + if(!filterByRelationType(graph, drill, relationType)) + continue; + } + if(result == null) + result = new THashSet(climbed.size()); + result.add(drill); + } + } } } - - /* - * There were some descriptors that require drill - */ - for(VariableConnectionPointDescriptor top : needDrill) { - Collection drilled = drill(graph, top); - if(drilled != null) { - for(VariableConnectionPointDescriptor drill : drilled) { - if(relationType != null) { - if(!filterByRelationType(graph, drill, relationType)) - continue; - } - if(result == null) - result = new THashSet(climbed.size()); - result.add(drill); - } - } + if (result != null) { + return result; + } else { + return Collections.emptySet(); } - return result; - } private static boolean filterByRelationType(ReadGraph graph, VariableConnectionPointDescriptor desc, Resource relationType) throws DatabaseException { diff --git a/bundles/org.simantics.utils.ui/src/org/simantics/utils/ui/widgets/FileOrDirectorySelectionWidget.java b/bundles/org.simantics.utils.ui/src/org/simantics/utils/ui/widgets/FileOrDirectorySelectionWidget.java index d685b7af0..19390e566 100644 --- a/bundles/org.simantics.utils.ui/src/org/simantics/utils/ui/widgets/FileOrDirectorySelectionWidget.java +++ b/bundles/org.simantics.utils.ui/src/org/simantics/utils/ui/widgets/FileOrDirectorySelectionWidget.java @@ -53,7 +53,7 @@ public abstract class FileOrDirectorySelectionWidget extends Composite{ public void widgetSelected(SelectionEvent e) { String[] name = openDialog(); if (name != null) { - setFilename(name); + setFilename(name,true); } } }); @@ -63,7 +63,11 @@ public abstract class FileOrDirectorySelectionWidget extends Composite{ @Override public void modifyText(ModifyEvent e) { String file = fileText.getText(); - setFilename(file.split(",")); + String files[] = file.split(","); + for (int i = 0; i < files.length; i++) { + files[i] = files[i].trim(); + } + setFilename(files, false); } }); @@ -74,14 +78,22 @@ public abstract class FileOrDirectorySelectionWidget extends Composite{ protected abstract boolean isValid(File file); protected void setFilename(String[] filename) { + setFilename(filename, true); + } + + protected void setFilename(String[] filename, boolean update) { String text = ""; - for (String s : filename) { - text += s + ","; + if (filename.length < 6) { + for (String s : filename) { + text += s + ","; + } + if (text.length() > 2) + text = text.substring(0, text.length() - 1); + } else { + text = filename[0] + " and " + (filename.length -1) + " other files."; } - if (text.length() > 2) - text = text.substring(0, text.length() - 1); - if (!text.equals(fileText.getText())) + if (update && !text.equals(fileText.getText())) fileText.setText(text); boolean accept = true; diff --git a/bundles/org.simantics.utils.ui/src/org/simantics/utils/ui/widgets/FileSelectionWidget.java b/bundles/org.simantics.utils.ui/src/org/simantics/utils/ui/widgets/FileSelectionWidget.java index 4acbf1cff..ef385ba0a 100644 --- a/bundles/org.simantics.utils.ui/src/org/simantics/utils/ui/widgets/FileSelectionWidget.java +++ b/bundles/org.simantics.utils.ui/src/org/simantics/utils/ui/widgets/FileSelectionWidget.java @@ -23,6 +23,8 @@ public class FileSelectionWidget extends FileOrDirectorySelectionWidget { FileDialog dialog = new FileDialog(getShell(),style); dialog.setFilterExtensions(getFilterExtensions()); dialog.setFilterNames(getFilterNames()); + if (filename != null && filename.length == 1) + dialog.setFileName(filename[0]); String filename = dialog.open(); if (filename == null) return null; diff --git a/bundles/org.simantics.workbench/META-INF/MANIFEST.MF b/bundles/org.simantics.workbench/META-INF/MANIFEST.MF index 5b183ad68..47e0c5c7e 100644 --- a/bundles/org.simantics.workbench/META-INF/MANIFEST.MF +++ b/bundles/org.simantics.workbench/META-INF/MANIFEST.MF @@ -27,7 +27,6 @@ Require-Bundle: com.ibm.icu, org.simantics.layer0;bundle-version="1.0.0", org.simantics.graph.db;bundle-version="1.0.0", org.simantics.editors;bundle-version="1.0.0", - org.simantics.db.procore.server.environment;bundle-version="1.1.0", org.simantics;bundle-version="1.0.0";visibility:=reexport, org.simantics.workbench.ontology;bundle-version="1.0.0", org.simantics.workbench.search;bundle-version="1.5.0", @@ -37,7 +36,6 @@ Require-Bundle: com.ibm.icu, org.simantics.simulation.ui;bundle-version="1.1.0";visibility:=reexport, org.simantics.scenegraph.profile;bundle-version="1.0.0";visibility:=reexport, org.simantics.browsing.ui.model;bundle-version="1.0.0";visibility:=reexport, - org.simantics.db.procore.ui, org.eclipse.ui.workbench, org.eclipse.e4.ui.workbench;bundle-version="1.3.0", org.eclipse.e4.ui.model.workbench;bundle-version="1.1.100.v20150407-1430", diff --git a/bundles/org.simantics.workbench/src/org/simantics/workbench/internal/SimanticsWorkbenchAdvisor.java b/bundles/org.simantics.workbench/src/org/simantics/workbench/internal/SimanticsWorkbenchAdvisor.java index 6f70bc56e..cb1ee16d3 100644 --- a/bundles/org.simantics.workbench/src/org/simantics/workbench/internal/SimanticsWorkbenchAdvisor.java +++ b/bundles/org.simantics.workbench/src/org/simantics/workbench/internal/SimanticsWorkbenchAdvisor.java @@ -96,8 +96,6 @@ import org.simantics.application.arguments.IArguments; import org.simantics.application.arguments.SimanticsArguments; import org.simantics.db.common.Indexing; import org.simantics.db.indexing.DatabaseIndexing; -import org.simantics.db.procore.server.environment.RebootRequiredException; -import org.simantics.db.procore.server.environment.windows.Product; import org.simantics.project.IProject; import org.simantics.project.ProjectKeys; import org.simantics.ui.SimanticsUI; @@ -465,19 +463,7 @@ public class SimanticsWorkbenchAdvisor extends WorkbenchAdvisor { return false; } catch (Exception e) { log.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e)); - - Throwable cause = e.getCause(); - if (cause instanceof RebootRequiredException) { - RebootRequiredException rre = (RebootRequiredException) cause; - StringBuilder msg = new StringBuilder(); - msg.append("The application must be restarted after installing the following products:\n"); - for (Product product : rre.products) - msg.append("\t" + product + "\n"); - msg.append("\nThe application will now close."); - MessageDialog.openInformation(null, "Restart Required", msg.toString()); - } else { - new ShowError("Platform Startup Failed", "Simantics Platform startup failed:\n\n" + e.getMessage(), e, true); - } + new ShowError("Platform Startup Failed", "Simantics Platform startup failed:\n\n" + e.getMessage(), e, true); return false; } diff --git a/bundles/org.simantics/META-INF/MANIFEST.MF b/bundles/org.simantics/META-INF/MANIFEST.MF index dcc2bf9ef..1a1102e20 100644 --- a/bundles/org.simantics/META-INF/MANIFEST.MF +++ b/bundles/org.simantics/META-INF/MANIFEST.MF @@ -9,7 +9,6 @@ Require-Bundle: org.eclipse.core.runtime;visibility:=reexport, org.simantics.db.layer0;bundle-version="1.1.0";visibility:=reexport, org.simantics.db.management;bundle-version="1.1.0";visibility:=reexport, org.simantics.project;bundle-version="1.0.1";visibility:=reexport, - org.simantics.db.procore.server.environment;bundle-version="1.1.0", org.simantics.graph.db;bundle-version="1.1.5", org.eclipse.equinox.p2.metadata;bundle-version="2.0.0", org.apache.log4j;bundle-version="1.2.15", diff --git a/bundles/org.simantics/src/org/simantics/SimanticsPlatform.java b/bundles/org.simantics/src/org/simantics/SimanticsPlatform.java index 2504ba62d..7839ce70d 100644 --- a/bundles/org.simantics/src/org/simantics/SimanticsPlatform.java +++ b/bundles/org.simantics/src/org/simantics/SimanticsPlatform.java @@ -45,6 +45,8 @@ import org.eclipse.osgi.service.datalocation.Location; import org.eclipse.osgi.service.resolver.BundleDescription; import org.ini4j.Ini; import org.ini4j.InvalidFileFormatException; +import org.simantics.SimanticsPlatform.OntologyRecoveryPolicy; +import org.simantics.SimanticsPlatform.RecoveryPolicy; import org.simantics.databoard.Bindings; import org.simantics.databoard.Databoard; import org.simantics.datatypes.literal.Font; @@ -59,6 +61,8 @@ import org.simantics.db.SessionModel; import org.simantics.db.UndoContext; import org.simantics.db.VirtualGraph; import org.simantics.db.WriteGraph; +import org.simantics.db.common.processor.MergingDelayedWriteProcessor; +import org.simantics.db.common.processor.MergingGraphRequestProcessor; import org.simantics.db.common.request.ObjectsWithType; import org.simantics.db.common.request.WriteResultRequest; import org.simantics.db.common.utils.Transaction; @@ -82,6 +86,7 @@ import org.simantics.db.service.QueryControl; import org.simantics.db.service.UndoRedoSupport; import org.simantics.db.service.VirtualGraphSupport; import org.simantics.db.service.XSupport; +import org.simantics.db.services.GlobalServiceInitializer; import org.simantics.graph.db.GraphDependencyAnalyzer; import org.simantics.graph.db.GraphDependencyAnalyzer.IU; import org.simantics.graph.db.GraphDependencyAnalyzer.IdentityNode; @@ -950,6 +955,13 @@ public class SimanticsPlatform implements LifecycleListener { } + public void registerServices(SessionContext context) { + new GlobalServiceInitializer().initialize(session); + session.registerService(MergingGraphRequestProcessor.class, new MergingGraphRequestProcessor("SessionService", session, 20)); + session.registerService(MergingDelayedWriteProcessor.class, new MergingDelayedWriteProcessor(session, 20)); + } + + public SessionContext createSessionContext(boolean init) throws PlatformException { try { // Construct and initialize SessionContext from Session. @@ -957,7 +969,7 @@ public class SimanticsPlatform implements LifecycleListener { String message = "Session context created"; LOGGER.info(message); if (init) { - sessionContext.registerServices(); + registerServices(sessionContext); message = "Session services registered"; LOGGER.info(message); } diff --git a/bundles/org.simantics/src/org/simantics/internal/SessionUtil.java b/bundles/org.simantics/src/org/simantics/internal/SessionUtil.java deleted file mode 100644 index 86bc76467..000000000 --- a/bundles/org.simantics/src/org/simantics/internal/SessionUtil.java +++ /dev/null @@ -1,102 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 Association for Decentralized Information Management - * in Industry THTH ry. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Semantum Oy - initial API and implementation - *******************************************************************************/ -package org.simantics.internal; - -import java.io.File; -import java.util.Properties; -import java.util.UUID; - -import org.eclipse.core.runtime.IProduct; -import org.eclipse.core.runtime.Platform; -import org.simantics.db.ServerEx; -import org.simantics.db.Session; -import org.simantics.db.exception.DatabaseException; -import org.simantics.db.service.LifecycleSupport; -import org.simantics.db.service.XSupport; -import org.simantics.project.management.ServerManager; -import org.simantics.project.management.ServerManagerFactory; - -/** - * An as-simple-as-possible utility class for starting a Simantics database - * instance and opening a connection ({@link Session}) to it. - * - *

- * To get up and running, simply invoke: - *

- *     SessionUtil util = new SessionUtil("my-client-id");
- *     try {
- *         File workspaceLocation = ...;
- *         Session session = util.openSession(workspaceLocation);
- *         // do something with the database session
- *     } finally {
- *         util.close();
- *     }
- * 
- * - *

- * This class is a provisional utility, pending for public inclusion. - * - * @author Tuukka Lehtonen - * @see Session - */ -public class SessionUtil { - - private String clientId; - @SuppressWarnings("unused") - private File workspace; - - private ServerManager serverManager; - private ServerEx server; - private Session session; - - public static String getApplicationClientId() { - IProduct product = Platform.getProduct(); - if(product == null) return "noProduct"; - String application = product.getApplication(); - return application != null ? application : UUID.randomUUID().toString(); - } - - public SessionUtil() { - this(UUID.randomUUID().toString()); - } - - public SessionUtil(String clientId) { - serverManager = ServerManagerFactory.getServerManager(); - this.clientId = clientId; - } - - public void close() throws DatabaseException { - if (session != null) { - session.getService(LifecycleSupport.class).close(); - } - serverManager.close(); - } - -// public Session open(File workspace) throws IOException, DatabaseException { -// File dbDir = new File(workspace, "db"); -// if (!dbDir.exists() || !dbDir.isDirectory()) -// throw new FileNotFoundException("database directory " + dbDir + " not found"); -// server = serverManager.getServer(dbDir); -// server.start(null); -// session = openSession(server, dbDir); -// this.workspace = workspace; -// return session; -// } - - private Session openSession(ServerEx server, File dbDir) throws DatabaseException { - Properties info = new Properties(ServerManager.DEFAULT); - session = server.createSession(info); - session.getService(XSupport.class).setServiceMode(true, true); - return session; - } - -} diff --git a/bundles/pom.xml b/bundles/pom.xml index 6469aaff9..e90980faf 100644 --- a/bundles/pom.xml +++ b/bundles/pom.xml @@ -88,7 +88,6 @@ org.simantics.db.layer0 org.simantics.db.management org.simantics.db.procore - org.simantics.db.procore.server.environment org.simantics.db.procore.ui org.simantics.db.server org.simantics.db.services diff --git a/features/org.simantics.workbench.feature/feature.xml b/features/org.simantics.workbench.feature/feature.xml index 7b5873219..20c72be5f 100644 --- a/features/org.simantics.workbench.feature/feature.xml +++ b/features/org.simantics.workbench.feature/feature.xml @@ -65,13 +65,6 @@ version="0.0.0" unpack="false"/> - -