@L0.new
L0.HasResourceClass "org.simantics.action.ontology.ActionResource"
-ACT.Action <T L0.Entity
+ACT.Action <T L0.Action
ACT.DropAction <T L0.Entity
editor.setEditor(combo, item, columnIndex);
combo.setFocus();
- combo.setListVisible(true);
GraphExplorerImpl.this.reconfigureTreeEditorForText(item, columnIndex, combo, combo.getText(), SWT.DEFAULT, 0, 0);
// Removed in comboListener
currentlyModifiedNodes.add(context);
+ combo.setListVisible(true);
//System.out.println("START ENUMERATION EDITING: " + item);
}
*
* Contributors:
* VTT Technical Research Centre of Finland - initial API and implementation
+ * Semantum Oy - gitlab #313
*******************************************************************************/
package org.simantics.databoard;
databoard.initialize();
- DATATYPE = getBindingUnchecked(Datatype.class);
+ DATATYPE = getBindingUnchecked(Datatype.class);
+ /**
+ * {@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 BindingRepository#classMap} is allowed
+ * to contain a cached Datatype.class -> Binding mapping.
+ */
+ bindingRepository.registerClassMapping(Datatype.class, DATATYPE);
}
}
/*******************************************************************************
- * 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
*
* 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;
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
*/
this.requestMap = requests;
for (Entry<BindingRequest, Binding> e : requests.entrySet()) {
if ( isClassRequest( e.getKey() ) ) {
- classMap.put(e.getKey().getClazz(), e.getValue());
+ registerClassMapping(e.getKey().getClazz(), e.getValue());
}
}
}
*/
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<BindingRequest, Binding> e : requestMap.entrySet()) {
if (e.getValue() == binding) {
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);
+ }
}
}
*
* 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;
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;
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.
*
this.signature = classSignature;
this.annotations = annotations;
this.descriptor = classDescriptor;
- hash = className.hashCode();
- for (Annotation a : annotations) {
- hash = 7*hash + a.hashCode();
- }
+ hash = calcHash(className);
}
/**
className = clazz.getCanonicalName();
signature = getSignature(clazz);
- List<Class<?>> 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<Class<?>> classes, MutableInteger pos)
+
+ private StringBuilder _buildDescriptor(StringBuilder sb, Class<?> c, List<Class<?>> classes, MutableInteger pos)
{
int genericCount = c.getTypeParameters().length;
int genericsLeft = classes.size()-pos.value;
} else {
sb.append( getSignature(c) );
}
+ return sb;
}
public BindingRequest(Class<?> clazz, List<Annotation> 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:
+ * 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;
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;
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);
type.componentType = binding.componentBinding.type();
inprogress.remove(request);
+ repository.put(request, binding);
return binding;
}
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 );
binding = defaultBinding;
}
- repository.put(request, binding);
-
return binding;
} catch (RangeException e) {
inprogress.remove( request );
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<Class<?>> list = new ArrayList<Class<?>>();
+ 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);
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,
--- /dev/null
+/*******************************************************************************
+ * 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 <code>null</code> 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.
+ *
+ * <p>
+ * The method always returns a non-null Session or produces an
+ * IllegalStateException if a Session was not attainable.
+ * </p>
+ *
+ * @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
+ * <code>null</code> if there is no current Session available.
+ *
+ * @see #getSession()
+ * @return the Session bound to the currently active context or
+ * <code>null</code>
+ */
+ 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> T sync(ReadInterface<T> r) throws DatabaseException {
+ return getSession().sync(r);
+ }
+
+ public static <T> T sync(WriteInterface<T> r) throws DatabaseException {
+ return getSession().sync(r);
+ }
+
+}
--- /dev/null
+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<Resource, RuntimeEnvironment> {
+
+ public RuntimeEnvironmentRequest(Resource parameter) {
+ super(parameter);
+ }
+
+ protected void fillEnvironmentSpecification(EnvironmentSpecification environmentSpecification) {
+ }
+
+ static class UpdateListenerImpl extends UpdateListener {
+
+ final EnvironmentSpecification environmentSpecification;
+ final Listener<RuntimeEnvironment> callback;
+
+ UpdateListenerImpl(EnvironmentSpecification environmentSpecification, Listener<RuntimeEnvironment> 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<RuntimeEnvironment> 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<RuntimeEnvironment>() {
+ @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<String, RuntimeEnvironment>(mainModuleUri) {
+
+ UpdateListenerImpl sclListener;
+
+ @Override
+ public void register(ReadGraph graph, Listener<RuntimeEnvironment> 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();
+ }
+
+}
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Set;
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;
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;
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;
+ }
}
*/
public static Resource create(WriteGraph g, Iterable<Resource> 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<Resource> 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}.
*/
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;
}
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;
+
}
}
+++ /dev/null
-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;
-
-}
*******************************************************************************/
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;
StringBuilder sb = new StringBuilder(32);
try {
long rid = getResourceId();
- if(DebugPolicy.VERBOSE) {
+ if(DevelopmentKeys.VERBOSE) {
sb.append("[id=");
sb.append(id);
sb.append(" - rid=");
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=");
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;
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;
@Override
public String toString() {
StringBuilder sb = new StringBuilder(32);
- if(DebugPolicy.VERBOSE) {
+ if(DevelopmentKeys.VERBOSE) {
sb.append("[delayed id=");
sb.append(id);
sb.append("]");
@Override
public <T> 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.<Boolean>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);
@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.<Boolean>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);
}
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncMultiReadEntry.class);
- protected AsyncMultiRead<T> request;
+ protected AsyncMultiRead<T> id;
AsyncMultiReadEntry(AsyncMultiRead<T> 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);
}
except(t);
}
- }, request);
+ }, id);
- request.perform(graph , proc);
+ id.perform(graph , proc);
proc.get();
@Override
public String toString() {
- if(request == null) return "DISCARDED";
- else return request.toString() + statusOrException;
+ if(id == null) return "DISCARDED";
+ else return id.toString() + statusOrException;
}
};
@Override
public String toString() {
- if(request == null) return "DISCARDED";
- else return request.toString() + statusOrException;
+ if(id == null) return "DISCARDED";
+ else return id.toString() + statusOrException;
}
public Object compute(ReadGraphImpl graph, AsyncMultiProcedure<T> procedure) throws DatabaseException {
- return graph.processor.cache.performQuery(graph, request, this, procedure);
+ return graph.processor.cache.performQuery(graph, id, this, procedure);
}
}
*******************************************************************************/
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;
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncReadEntry.class);
- protected AsyncRead<T> request;
+ protected AsyncRead<T> id;
AsyncReadEntry(AsyncRead<T> request) {
- this.request = request;
- if (DebugPolicy.QUERY_STATE)
- System.out.println("[QUERY STATE]: created " + this);
+ this.id = request;
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>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
except(t);
}
- }, request);
+ }, id);
- request.perform(graph, proc);
+ id.perform(graph, proc);
proc.get();
@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;
}
};
@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
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);
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;
@Override
public void discard() {
- if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: discarded " + this);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) {
+ System.err.println("[QUERY STATE]: discarded " + this);
+ }
+ }
statusOrException = DISCARDED;
}
@Override
final public void refute() {
- if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: refuted " + this);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) {
+ System.err.println("[QUERY STATE]: refuted " + this);
+ }
+ }
statusOrException = REQUIRES_COMPUTATION;
}
@Override
public void except(Throwable throwable) {
- if(DebugPolicy.QUERY_STATE) System.out.println("[QUERY STATE]: excepted " + this);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) {
+ System.err.println("[QUERY STATE]: excepted " + this);
+ }
+ }
if(statusOrException != DISCARDED) {
statusOrException = EXCEPTED;
result = throwable;
}
@Override
- public void setPending() {
- statusOrException = PENDING;
+ public void setPending(QuerySupport querySupport) {
+ statusOrException = PENDING;
+ clearResult(querySupport);
}
@Override
@Override
void prepareRecompute(QuerySupport querySupport) {
- setPending();
- clearResult(querySupport);
+ setPending(querySupport);
}
@Override
public class CodeGen {
- int indent = 4;
-
- String[] signatureR1RelationInfo = { "int r", "r", "keyR", "long", "InternalProcedure<RelationInfo>", "entry.id" };
- String[] signatureR1Bytes = { "int r", "r", "keyR", "long", "InternalProcedure<byte[]>", "entry.id" };
- String[] signatureR1IntSet = { "int r", "r", "keyR", "long", "InternalProcedure<IntSet>", "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<Integer>", "entry.id" };
- String[] signatureID2 = { "String id", "id", "keyID", "String", "InternalProcedure<TObjectIntHashMap<String>>", "entry.id" };
- String[] signatureChildMap = { "int r", "r", "keyR", "long", "InternalProcedure<ObjectResourceIdMap<String>>", "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<indent;i++)
- content.append(" ");
- content.append(line);
- content.append("\n");
- }
-
- public void generateQuery(StringBuilder content, String clazz, String[] signature, boolean runnerShortcut, boolean genReturn) {
- generateGetOrCreate(content, clazz, signature);
- generateRemove(content, clazz, signature);
- generateRunner(content, clazz, signature, runnerShortcut, genReturn);
- }
-
- public void generateRunner(StringBuilder content, String clazz, String[] signature, boolean shortcut, boolean genReturn) {
-
- line(content, "public static " + (genReturn ? "Object" : "void") + " runner" + clazz + "(ReadGraphImpl graph, " + signature[0] + ", CacheEntry parent, ListenerBase listener, final " + signature[4] + " procedure) throws DatabaseException {");
- line(content, " QueryCache cache = graph.processor.cache;");
- if(shortcut) {
- line(content, " if(parent == null && listener == null && !cache.shouldCache(graph.processor, " + signature[1] + ")) {");
- line(content, " if (SINGLE) {");
- line(content, " " + clazz + " e = cache.peek" + clazz + "(" + signature[1] + ");");
- line(content, " if (e != null && e.isReady()) {");
- line(content, " " + (genReturn ? "return " : "") + "e.performFromCache(graph, procedure);");
- if(!genReturn) line(content, " return;");
- line(content, " }");
- line(content, " }");
- line(content, " " + (genReturn ? "return " : "") + clazz + ".computeForEach(graph, " + signature[1] + ", null, procedure);");
- if(!genReturn) line(content, " return;");
- line(content, " }");
- }
- line(content, " " + clazz + " entry = (" + clazz + ")cache.getOrCreate" + clazz + "(graph, " + signature[1] + ");");
- line(content, " " + signature[4] + " procedure_ = procedure != null ? procedure : emptyProcedure" + clazz + ";");
- line(content, " ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);");
- line(content, " if(entry.isReady()) " + (genReturn ? "return " : "") + "entry.performFromCache(graph, procedure_);");
- line(content, " else {");
- line(content, " assert(entry.isPending());");
- if(shortcut) line(content, " " + (genReturn ? "Object result = " : "") + clazz + ".computeForEach(graph, " + signature[1] + ", entry, procedure_);");
- else line(content, " entry.compute(graph, procedure_);");
- line(content, " if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());");
- if(genReturn) line(content, " return result;");
- line(content, " }");
- line(content, "}");
- line(content, "");
+ int indent = 4;
+
+ class GenerationInfo {
+ String p1;
+ String keyName;
+ String keyToId;
+ String procedure;
+ boolean useNeedsToBlock;
+ String entryCreationArguments;
+ GenerationInfo(String p1, String keyName, String keyToId, String p4, String procedure, String entryCreationArguments, boolean useNeedsToBlock) {
+ this.p1 = p1;
+ this.keyName = keyName;
+ this.keyToId = keyToId;
+ this.procedure = procedure;
+ this.useNeedsToBlock = useNeedsToBlock;
+ this.entryCreationArguments = entryCreationArguments;
+ }
+ }
+
+ GenerationInfo signatureR1RelationInfo = new GenerationInfo ( "int r", "r", "keyR", "long", "InternalProcedure<RelationInfo>", "", false );
+ GenerationInfo signatureR1Bytes = new GenerationInfo ( "int r", "r", "keyR", "long", "InternalProcedure<byte[]>", "", false );
+ GenerationInfo signatureR1IntSet = new GenerationInfo ( "int r", "r", "keyR", "long", "InternalProcedure<IntSet>", "", 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<Integer>", "", false );
+ GenerationInfo signatureID2 = new GenerationInfo ( "String id", "id", "keyID", "String", "InternalProcedure<TObjectIntHashMap<String>>", "", false );
+ GenerationInfo signatureChildMap = new GenerationInfo ( "int r", "r", "keyR", "long", "InternalProcedure<ObjectResourceIdMap<String>>", "", 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<indent;i++)
+ content.append(" ");
+ content.append(line);
+ content.append("\n");
+ }
+
+ public void generateQuery(StringBuilder content, String clazz, GenerationInfo signature, boolean runnerShortcut, boolean genReturn) {
+ generateGetOrCreate(content, clazz, signature);
+ generateRemove(content, clazz, signature);
+ generateRunner(content, clazz, signature, runnerShortcut, genReturn);
+ }
+
+ public void generateRunner(StringBuilder content, String clazz, GenerationInfo signature, boolean shortcut, boolean genReturn) {
+
+ line(content, "public static " + (genReturn ? "Object" : "void") + " runner" + clazz + "(ReadGraphImpl graph, " + signature.p1 + ", CacheEntry parent, ListenerBase listener, final " + signature.procedure + " procedure" + (signature.useNeedsToBlock ? ", boolean needsToBlock" : "") + ") throws DatabaseException {");
+ line(content, " QueryCache cache = graph.processor.cache;");
+ if(shortcut) {
+ line(content, " if(parent == null && listener == null && !cache.shouldCache(graph.processor, " + signature.keyName + ")) {");
+ line(content, " if (SINGLE) {");
+ line(content, " " + clazz + " e = cache.peek" + clazz + "(" + signature.keyName + ");");
+ line(content, " if (e != null && e.isReady()) {");
+ line(content, " " + (genReturn ? "return " : "") + "e.performFromCache(graph, procedure);");
+ if(!genReturn) line(content, " return;");
+ line(content, " }");
+ line(content, " }");
+ line(content, " " + (genReturn ? "return " : "") + clazz + ".computeForEach(graph, " + signature.keyName + ", null, procedure" + (signature.useNeedsToBlock ? ", needsToBlock" : "") + ");");
+ if(!genReturn) line(content, " return;");
+ line(content, " }");
+ }
+ if(signature.useNeedsToBlock) {
+ line(content, " " + clazz + " entry = (" + clazz + ")cache.getOrCreate" + clazz + "(graph, " + signature.keyName + ", needsToBlock);");
+ line(content, " if(entry == null) {");
+ line(content, " graph.processor.schedule(new SessionTask(graph) {");
+ line(content, " @Override");
+ line(content, " public void run0(int thread) {");
+ line(content, " try {");
+ line(content, " runner" + clazz + "(graph, r, parent, listener, procedure, needsToBlock);");
+ line(content, " } catch (DatabaseException e) {");
+ line(content, " Logger.defaultLogError(e);");
+ line(content, " }");
+ line(content, " }");
+ line(content, " });");
+ line(content, " return null;");
+ line(content, " }");
+ } else {
+ line(content, " " + clazz + " entry = (" + clazz + ")cache.getOrCreate" + clazz + "(graph, " + signature.keyName + ");");
+ }
+ line(content, " " + signature.procedure + " procedure_ = procedure != null ? procedure : emptyProcedure" + clazz + ";");
+ line(content, " ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);");
+ line(content, " if(entry.isReady()) " + (genReturn ? "return " : "") + "entry.performFromCache(graph, procedure_);");
+ line(content, " else {");
+ line(content, " assert(entry.isPending());");
+ if(shortcut) line(content, " " + (genReturn ? "Object result = " : "") + clazz + ".computeForEach(graph, " + signature.keyName + ", entry, procedure_" + (signature.useNeedsToBlock ? ", needsToBlock" : "") + ");");
+ else line(content, " entry.compute(graph, procedure_);");
+ line(content, " if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());");
+ if(genReturn) line(content, " return result;");
+ line(content, " }");
+ line(content, "}");
+ line(content, "");
+
+ String lower = Character.toLowerCase(clazz.charAt(0)) + clazz.substring(1);
+
+ line(content, "private " + clazz + " peek" + clazz + "(" + signature.p1 + ") {");
+ line(content, " synchronized(" + lower +"Map) {");
+ line(content, " return (" + clazz + ") " + lower + "Map.get(" + signature.keyName + ");");
+ line(content, " }");
+ line(content, "}");
+ line(content, "");
+ }
+
+ public void generateRemove(StringBuilder content, String clazz, GenerationInfo signature) {
+
+ String lower = Character.toLowerCase(clazz.charAt(0)) + clazz.substring(1);
+
+ line(content, "void remove(" + clazz + " entry) {");
+ line(content, " synchronized(" + lower + "Map) {");
+ line(content, " " + lower + "Map.remove(entry.id);");
+ line(content, " }");
+ line(content, "}");
+ line(content, "");
+
+ }
+
+ public void generateGetOrCreate(StringBuilder content, String clazz, GenerationInfo signature) {
String lower = Character.toLowerCase(clazz.charAt(0)) + clazz.substring(1);
- line(content, "private " + clazz + " peek" + clazz + "(" + signature[0] + ") {");
- line(content, " synchronized(" + lower +"Map) {");
- line(content, " return (" + clazz + ") " + lower + "Map.get(" + signature[1] + ");");
- line(content, " }");
- line(content, "}");
- line(content, "");
- }
-
- public void generateRemove(StringBuilder content, String clazz, String[] signature) {
-
- String lower = Character.toLowerCase(clazz.charAt(0)) + clazz.substring(1);
-
- line(content, "void remove(" + clazz + " entry) {");
- line(content, " synchronized(" + lower + "Map) {");
- line(content, " " + lower + "Map.remove(" + signature[5] + ");");
- line(content, " }");
- line(content, "}");
- line(content, "");
-
- }
-
- public void generateGetOrCreate(StringBuilder content, String clazz, String[] signature) {
-
- String lower = Character.toLowerCase(clazz.charAt(0)) + clazz.substring(1);
-
- line(content, "" + clazz + " getOrCreate" + clazz + "(ReadGraphImpl graph, " + signature[0] + ") throws DatabaseException {");
- line(content, " " + clazz + " existing = null;");
- line(content, " synchronized(" + lower + "Map) {");
- line(content, " existing = (" + clazz + ")" + lower + "Map.get(" + signature[1] + ");");
- line(content, " if(existing == null) {");
- line(content, " existing = new " + clazz + "(" + signature[1] + ");");
- line(content, " existing.clearResult(querySupport);");
- line(content, " existing.setPending();");
- line(content, " " + lower + "Map.put(" + signature[2] + "(" + signature[1] + "), existing);");
- line(content, " size++;");
- line(content, " return existing;");
- line(content, " }");
- line(content, " if(existing.requiresComputation()) {");
- line(content, " existing.setPending();");
- line(content, " return existing;");
- line(content, " }");
- line(content, " }");
- line(content, " if(existing.isPending()) waitPending(graph, existing);");
- line(content, " return existing;");
- line(content, "}");
- line(content, "");
-
- }
-
- public void generate() {
-
- URL classLocation = CodeGen.class.getResource(".");
- if (classLocation != null) {
- if (classLocation.getProtocol().equals("file")) {
- try {
- URL resource = new URL(classLocation, ".");
- File path = new File(URLDecoder.decode(resource.getPath(), "UTF-8"));
- String target = path.getAbsolutePath().replace("\\", "/");
- target = target.replace("/bin/", "/src/") + "/QueryCache.java";
- System.err.println("target=" + target);
- File source = new File(target);
- StringBuilder content = new StringBuilder();
- content.append("package org.simantics.db.impl.query;\n");
- content.append("\n");
-
- content.append("import org.simantics.db.ObjectResourceIdMap;\n");
- content.append("import org.simantics.db.RelationInfo;\n");
- content.append("import org.simantics.db.common.utils.Logger;\n");
- content.append("import org.simantics.db.exception.DatabaseException;\n");
- content.append("import org.simantics.db.impl.graph.ReadGraphImpl;\n");
- content.append("import org.simantics.db.impl.procedure.InternalProcedure;\n");
- content.append("import org.simantics.db.impl.query.QueryProcessor.SessionTask;\n");
- content.append("import org.simantics.db.procedure.AsyncMultiProcedure;\n");
- content.append("import org.simantics.db.procedure.AsyncProcedure;\n");
- content.append("import org.simantics.db.procedure.ListenerBase;\n");
- content.append("import org.simantics.db.procedure.SyncMultiProcedure;\n");
- content.append("import org.simantics.db.request.AsyncMultiRead;\n");
- content.append("import org.simantics.db.request.AsyncRead;\n");
- content.append("import org.simantics.db.request.ExternalRead;\n");
- content.append("import org.simantics.db.request.MultiRead;\n");
- content.append("import org.simantics.db.request.Read;\n");
- content.append("\n");
-
- content.append("public class QueryCache extends QueryCacheBase {\n");
- content.append("\n");
-
- line(content, "private static final boolean SINGLE = true;");
- content.append("\n");
-
- line(content,"public QueryCache(QuerySupport querySupport, int threads) {");
- line(content," super(querySupport, threads);");
- line(content,"}");
- content.append("\n");
-
- generateQuery(content, "Objects", signatureR2IP, true, false);
- generateQuery(content, "Statements", signatureR2TIP, true, false);
- generateQuery(content, "DirectObjects", signatureR2IP, true, false);
- generateQuery(content, "RelationInfoQuery", signatureR1RelationInfo, true, false);
- generateQuery(content, "URIToResource", signatureID1, true, false);
- generateQuery(content, "ValueQuery", signatureR1Bytes, true, false);
- generateQuery(content, "OrderedSet", signatureR1IP, true, false);
- generateQuery(content, "PrincipalTypes", signatureR1IP, true, false);
- generateQuery(content, "DirectPredicates", signatureR1IntSet, true, false);
- generateQuery(content, "Predicates", signatureR1IntSet, true, false);
- generateQuery(content, "ReadEntry", signatureRead, true, true);
- generateQuery(content, "AsyncReadEntry", signatureAsyncRead, true, true);
- generateQuery(content, "Types", signatureR1IntSet, true, false);
- generateQuery(content, "ChildMap", signatureChildMap, true, false);
- generateQuery(content, "TypeHierarchy", signatureR1IntSet, true, false);
- generateQuery(content, "SuperTypes", signatureR1IntSet, true, false);
- generateQuery(content, "SuperRelations", signatureR1IntSet, true, false);
-
- generateQuery(content, "AssertedPredicates", signatureR1IP, false, false);
- generateQuery(content, "AssertedStatements", signatureR2TIP, false, false);
- generateQuery(content, "DirectSuperRelations", signatureR1IP, false, false);
- generateQuery(content, "MultiReadEntry", signatureMultiRead, false, false);
- generateQuery(content, "AsyncMultiReadEntry", signatureAsyncMultiRead, false, false);
- generateQuery(content, "ExternalReadEntry", signatureExternalRead, false, false);
- content.append("}\n");
- FileUtils.writeFile(source, content.toString().getBytes());
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- }
-
- public static void main(String[] args) {
- new CodeGen().generate();
- }
+ line(content, "" + clazz + " getOrCreate" + clazz + "(ReadGraphImpl graph, " + signature.p1 + (signature.useNeedsToBlock ? ", boolean needsToBlock" : "") + ") throws DatabaseException {");
+ line(content, " " + clazz + " existing = null;");
+ line(content, " synchronized(" + lower + "Map) {");
+ line(content, " existing = (" + clazz + ")" + lower + "Map.get(" + signature.keyName + ");");
+ line(content, " if(existing == null) {");
+ line(content, " existing = new " + clazz + "(" + signature.keyName + signature.entryCreationArguments + ");");
+ line(content, " existing.setPending(querySupport);");
+ line(content, " " + lower + "Map.put(" + signature.keyToId + "(" + signature.keyName + "), existing);");
+ line(content, " size++;");
+ line(content, " return existing;");
+ line(content, " }");
+ line(content, " if(existing.requiresComputation()) {");
+ line(content, " existing.setPending(querySupport);");
+ line(content, " return existing;");
+ line(content, " }");
+ line(content, " }");
+ line(content, " if(existing.isPending()) {");
+ if(signature.useNeedsToBlock) {
+ line(content, " if(needsToBlock)");
+ line(content, " waitPending(graph, existing);");
+ line(content, " else {");
+ line(content, " return null;");
+ line(content, " }");
+ } else {
+ line(content, " waitPending(graph, existing);");
+ }
+ line(content, " }");
+ line(content, " return existing;");
+ line(content, "}");
+ line(content, "");
+
+ }
+
+ public void generate() {
+
+ URL classLocation = CodeGen.class.getResource(".");
+ if (classLocation != null) {
+ if (classLocation.getProtocol().equals("file")) {
+ try {
+ URL resource = new URL(classLocation, ".");
+ File path = new File(URLDecoder.decode(resource.getPath(), "UTF-8"));
+ String target = path.getAbsolutePath().replace("\\", "/");
+ target = target.replace("/bin/", "/src/") + "/QueryCache.java";
+ System.err.println("target=" + target);
+ File source = new File(target);
+ StringBuilder content = new StringBuilder();
+ content.append("package org.simantics.db.impl.query;\n");
+ content.append("\n");
+
+ content.append("import org.simantics.db.ObjectResourceIdMap;\n");
+ content.append("import org.simantics.db.RelationInfo;\n");
+ content.append("import org.simantics.db.common.utils.Logger;\n");
+ content.append("import org.simantics.db.exception.DatabaseException;\n");
+ content.append("import org.simantics.db.impl.graph.ReadGraphImpl;\n");
+ content.append("import org.simantics.db.impl.procedure.InternalProcedure;\n");
+ content.append("import org.simantics.db.impl.query.QueryProcessor.SessionTask;\n");
+ content.append("import org.simantics.db.procedure.AsyncMultiProcedure;\n");
+ content.append("import org.simantics.db.procedure.AsyncProcedure;\n");
+ content.append("import org.simantics.db.procedure.ListenerBase;\n");
+ content.append("import org.simantics.db.procedure.SyncMultiProcedure;\n");
+ content.append("import org.simantics.db.request.AsyncMultiRead;\n");
+ content.append("import org.simantics.db.request.AsyncRead;\n");
+ content.append("import org.simantics.db.request.ExternalRead;\n");
+ content.append("import org.simantics.db.request.MultiRead;\n");
+ content.append("import org.simantics.db.request.Read;\n");
+ content.append("\n");
+
+ content.append("public class QueryCache extends QueryCacheBase {\n");
+ content.append("\n");
+
+ line(content, "private static final boolean SINGLE = false;");
+ content.append("\n");
+
+ line(content,"public QueryCache(QuerySupport querySupport, int threads) {");
+ line(content," super(querySupport, threads);");
+ line(content,"}");
+ content.append("\n");
+
+ generateQuery(content, "Objects", signatureR2IP, true, false);
+ generateQuery(content, "Statements", signatureR2TIP, true, false);
+ generateQuery(content, "DirectObjects", signatureR2IP, true, false);
+ generateQuery(content, "RelationInfoQuery", signatureR1RelationInfo, true, false);
+ generateQuery(content, "URIToResource", signatureID1, true, false);
+ generateQuery(content, "ValueQuery", signatureR1Bytes, true, false);
+ generateQuery(content, "OrderedSet", signatureR1IP, true, false);
+ generateQuery(content, "PrincipalTypes", signatureR1IP, true, false);
+ generateQuery(content, "DirectPredicates", signatureR1IntSet, true, false);
+ generateQuery(content, "Predicates", signatureR1IntSet, true, false);
+ generateQuery(content, "ReadEntry", signatureRead, true, true);
+ generateQuery(content, "AsyncReadEntry", signatureAsyncRead, true, true);
+ generateQuery(content, "Types", signatureR1IntSet, true, false);
+ generateQuery(content, "ChildMap", signatureChildMap, true, false);
+ generateQuery(content, "TypeHierarchy", signatureR1IntSet, true, false);
+ generateQuery(content, "SuperTypes", signatureR1IntSet, true, false);
+ generateQuery(content, "SuperRelations", signatureR1IntSet, true, false);
+
+ generateQuery(content, "AssertedPredicates", signatureR1IP, false, false);
+ generateQuery(content, "AssertedStatements", signatureR2TIP, false, false);
+ generateQuery(content, "DirectSuperRelations", signatureR1IP, false, false);
+ generateQuery(content, "MultiReadEntry", signatureMultiRead, false, false);
+ generateQuery(content, "AsyncMultiReadEntry", signatureAsyncMultiRead, false, false);
+ generateQuery(content, "ExternalReadEntry", signatureExternalRead, false, false);
+ content.append("}\n");
+ FileUtils.writeFile(source, content.toString().getBytes());
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ }
+
+ public static void main(String[] args) {
+ new CodeGen().generate();
+ }
}
import java.util.LinkedList;
+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.procedure.AsyncProcedure;
import org.simantics.db.procedure.Listener;
import org.simantics.db.request.ExternalRead;
import org.simantics.db.request.RequestFlags;
+import org.simantics.utils.Development;
final public class ExternalReadEntry<T> extends CacheEntryBase<AsyncProcedure<T>> implements Listener<T> {
final LinkedList<T> items = new LinkedList<T>();
- protected ExternalRead<T> request;
+ protected ExternalRead<T> 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
@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();
//}
public ExternalReadEntry(ExternalRead<T> 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.<Boolean>getProperty(DevelopmentKeys.CACHE_ENTRY_STATE, Bindings.BOOLEAN)) {
+ System.err.println("[QUERY STATE]: excepted " + this);
+ }
+ }
+
if(statusOrException != DISCARDED) {
statusOrException = EXCEPTED;
result = t;
}
// Reschedule
if(!items.isEmpty()) {
- graph.processor.updatePrimitive(request);
+ graph.processor.updatePrimitive(id);
}
}
@Override
public String toString() {
- if(request == null) return "DISCARDED ExternalRead";
- else return request.toString();
+ if(id == null) return "DISCARDED ExternalRead";
+ else return id.toString();
}
};
@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
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) {
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.
}
private static final Logger LOGGER = LoggerFactory.getLogger(MultiReadEntry.class);
- protected MultiRead<T> request;
+ protected MultiRead<T> id;
MultiReadEntry(MultiRead<T> 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);
}
try {
- request.perform(graph , new SyncMultiProcedure<T>() {
+ id.perform(graph , new SyncMultiProcedure<T>() {
@Override
public void execute(ReadGraph graph, T result) {
@Override
public String toString() {
- if(request == null) return "DISCARDED";
- else return request.toString() + statusOrException;
+ if(id == null) return "DISCARDED";
+ else return id.toString() + statusOrException;
}
};
@Override
public String toString() {
- if(request == null) return "DISCARDED";
- else return request.toString() + statusOrException;
+ if(id == null) return "DISCARDED";
+ else return id.toString() + statusOrException;
}
public Object compute(ReadGraphImpl graph, SyncMultiProcedure<T> procedure) throws DatabaseException {
- return graph.processor.cache.performQuery(graph, request, this, procedure);
+ return graph.processor.cache.performQuery(graph, id, this, procedure);
}
}
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);
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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) {
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) {
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) {
}
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);
return result;
}
}
-
private AsyncReadEntry peekAsyncReadEntry(AsyncRead<?> r) {
synchronized(asyncReadEntryMap) {
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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);
}
}
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);
}
}
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);
}
}
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;
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;
} catch (DatabaseException e) {
Logger.defaultLogError(e);
}
- if(DebugPolicy.DEPENDENCIES) System.out.println(child + " -> " + parent);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_DEPENDENCIES, Bindings.BOOLEAN)) {
+ System.err.println(child + " -> " + parent);
+ }
+ }
}
if (listener != null) {
list.add(result);
}
- if(DebugPolicy.LISTENER) {
- new Exception().printStackTrace();
- System.out.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
+ new Exception().printStackTrace();
+ System.err.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure);
+ }
}
return result;
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;
private boolean findCollectables(CacheEntry<?> entry, Map<CacheEntry, Boolean> collectables, ArrayList<CacheEntry> result) {
if (entry.isDiscarded()) {
- if(DebugPolicy.COLLECT && DebugPolicy.VERBOSE)
- System.out.println("GC: discarded entry " + entry);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>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.<Boolean>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.<Boolean>getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) {
+ System.err.println("GC: listened entry " + entry + " was not collected. Entry=" + entry);
+ }
}
collectables.remove(entry);
return false;
}
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.<Boolean>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;
}
// 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.<Boolean>getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) {
+ System.err.println("collector found " + freeCount + " free queries.");
+ }
+ }
lastKnownFixedSize = currentSize - freeCount;
int target = freeCount - maxNumberOfCollectableQueries/2;
- if(DebugPolicy.COLLECT)
- System.out.println("collector removes " + target + " free queries.");
+
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>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))
removals.clear();
}
- if(DebugPolicy.COLLECT) {
- System.out.println("collect found " + freeCount + " collectable entries.");
+
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) {
+ System.err.println("collect found " + freeCount + " collectable entries.");
+ }
}
return;
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.<Boolean>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.<Boolean>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.<Boolean>getProperty(DevelopmentKeys.QUERYCOLLECTOR, Bindings.BOOLEAN)) {
+ System.err.println("Collect took " + 1e-9*duration + "s.");
+ }
+ }
} catch (Throwable t) {
t.printStackTrace();
}
@Override
- public void setPending() {
+ public void setPending(QuerySupport querySupport) {
// TODO Auto-generated method stub
}
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;
} catch (DatabaseException e) {
Logger.defaultLogError(e);
}
- if(DebugPolicy.DEPENDENCIES) System.out.println(child + " -> " + parent);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_DEPENDENCIES, Bindings.BOOLEAN)) {
+ System.out.println(child + " -> " + parent);
+ }
+ }
}
if (listener != null) {
list.add(result);
}
- if(DebugPolicy.LISTENER) {
- new Exception().printStackTrace();
- System.out.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
+ new Exception().printStackTrace();
+ System.err.println("addListener -> " + list.size() + " " + entry + " " + base + " " + procedure);
+ }
}
return result;
private void scheduleListener(ListenerEntry entry) {
assert (entry != null);
- if(DebugPolicy.LISTENER) System.out.println("Scheduled " + entry.procedure);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
+ System.err.println("Scheduled " + entry.procedure);
+ }
+ }
scheduledListeners.add(entry);
}
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);
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.
if (entry.isDiscarded()) {
if (Development.DEVELOPMENT) {
if(Development.<Boolean>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.<Boolean>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.<Boolean>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.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) {
- System.out.print("E");
+ System.err.print("E");
}
}
}
if (entry.isPending()) {
if (Development.DEVELOPMENT) {
if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) {
- System.out.print("P");
+ System.err.print("P");
}
}
}
if (Development.DEVELOPMENT) {
if(Development.<Boolean>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());
}
}
if (Development.DEVELOPMENT) {
if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) {
if(hasListener(entry)) {
- System.out.println(" (L)");
+ System.err.println(" (L)");
} else {
- System.out.println("");
+ System.err.println("");
}
}
}
Query query = entry.getQuery();
- if(DebugPolicy.RECOMPUTE) System.out.println("R " + query);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_RECOMPUTE, Bindings.BOOLEAN)) {
+ System.err.println("R " + query);
+ }
+ }
entry.prepareRecompute(querySupport);
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.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_CHANGES, Bindings.BOOLEAN)) {
+ System.out.println("C " + query);
+ System.out.println("- " + oldValue);
+ System.out.println("- " + newValue);
+ }
}
return newValue;
}
} 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.<Boolean>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;
for (ListenerEntry listenerEntry : entries) {
if (pruneListener(listenerEntry)) {
- if(DebugPolicy.LISTENER) System.out.println("Pruned " + listenerEntry.procedure);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_LISTENERS, Bindings.BOOLEAN)) {
+ new Exception().printStackTrace();
+ System.err.println("Pruned " + listenerEntry.procedure);
+ }
+ }
continue;
}
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.<Boolean>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());
}
for(ListenerEntry listenerEntry : schedule) {
final CacheEntry entry = listenerEntry.entry;
- if(DebugPolicy.LISTENER)
- System.out.println("Firing " + listenerEntry.procedure);
+ if (Development.DEVELOPMENT) {
+ if(Development.<Boolean>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.<Boolean>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();
private Object primitiveUpdateLock = new Object();
private THashSet scheduledPrimitiveUpdates = new THashSet();
+ private ArrayList<CacheEntry> 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;
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.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) {
+ System.err.println("== Query update ends ==");
+ }
+ }
+
return;
}
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.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) {
+ System.err.println("== Query update ends ==");
+ }
+ }
+
return;
}
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;
}
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);
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);
@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;
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;
});
- // 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.<Boolean>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.<Boolean>getProperty(DevelopmentKeys.QUERYPROCESSOR_UPDATE, Bindings.BOOLEAN)) {
+ System.err.println("== Query update ends ==");
+ }
+ }
}
private static final Logger LOGGER = LoggerFactory.getLogger(ReadEntry.class);
- protected Read<T> request;
+ protected Read<T> id;
public ReadEntry(Read<T> 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
try {
- T result = request.perform(graph);
+ T result = id.perform(graph);
setResult(result);
setReady();
@Override
public int type() {
- if (request instanceof ReadExt) {
- return ((ReadExt) request).getType();
+ if (id instanceof ReadExt) {
+ return ((ReadExt) id).getType();
} else {
return RequestFlags.INVALIDATE;
}
@Override
public String toString() {
- if (request == null)
+ if (id == null)
return "DISCARDED";
else
- return request.toString() + statusOrException;
+ return id.toString() + statusOrException;
}
};
}
public static <T> T computeForEach(ReadGraphImpl graph, Read<T> request, ReadEntry<T> entry,
- AsyncProcedure<T> procedure_) throws DatabaseException {
+ AsyncProcedure<T> procedure_, boolean needsToBlock) throws DatabaseException {
AsyncProcedure<T> procedure = entry != null ? entry : procedure_;
@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<T> procedure) throws DatabaseException {
@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;
}
</target>
<target interface="org.simantics.db.layer0.adapter.ActionFactory">
- <baseType uri="http://www.simantics.org/Action-0.0/Action" />
+ <baseType uri="http://www.simantics.org/Layer0-0.0/Action" />
+ <type uri="http://www.simantics.org/Layer0-0.0/SCLAction"
+ class="org.simantics.db.layer0.scl.SCLAction">
+ <graph/>
+ <this/>
+ </type>
</target>
<target interface="org.simantics.db.layer0.migration.MigrationStep">
bin.includes = META-INF/,\
.,\
plugin.xml,\
- adapters.xml
+ adapters.xml,\
+ scl/
--- /dev/null
+include "Simantics/DB"
+include "Simantics/Issue"
+
+importJava "org.simantics.db.layer0.function.All" where
+ uriValidator :: Resource -> <ReadGraph> [Issue]
+ valueValidator :: Resource -> <ReadGraph> [Issue]
+ relationValidator :: Resource -> <ReadGraph> [Issue]
+ propertyValidator :: Resource -> <ReadGraph> [Issue]
+ clusterValidator :: Resource -> <ReadGraph> [Issue]
\ No newline at end of file
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.
*
* 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 <code>null</code> 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.
- *
- * <p>
- * The method always returns a non-null Session or produces an
- * IllegalStateException if a Session was not attainable.
- * </p>
- *
- * @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
- * <code>null</code> if there is no current Session available.
- *
- * @see #getSession()
- * @return the Session bound to the currently active context or
- * <code>null</code>
- */
- 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
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> T sync(ReadInterface<T> r) throws DatabaseException {
- return getSession().sync(r);
- }
-
- public static <T> T sync(WriteInterface<T> r) throws DatabaseException {
- return getSession().sync(r);
- }
-
public static File getTemporaryDirectory() {
File workspace = Platform.getLocation().toFile();
File temp = new File(workspace, "tempFiles");
--- /dev/null
+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<Function1<Resource, Object>> {
+
+ protected RuleFunctionRequest(Resource rule) {
+ super(rule);
+ }
+
+ @Override
+ public Function1<Resource, Object> 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<Resource, Object> 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);
+ }
+
+}
--- /dev/null
+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<String>() {
+
+ @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();
+ }
+ }
+
+}
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;
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 {
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 {
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.
* @author Hannu Niemistö
* @author Antti Villberg
*/
-public class RuntimeEnvironmentRequest extends UnaryRead<Resource, RuntimeEnvironment> {
+@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<RuntimeEnvironment> callback;
-
- UpdateListenerImpl(EnvironmentSpecification environmentSpecification, Listener<RuntimeEnvironment> 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<RuntimeEnvironment> 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<RuntimeEnvironment>() {
- @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<String, RuntimeEnvironment>(mainModuleUri) {
-
- UpdateListenerImpl sclListener;
-
- @Override
- public void register(ReadGraph graph, Listener<RuntimeEnvironment> 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();
- }
-
}
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;
import org.simantics.db.layer0.util.ModelTransferableGraphSourceRequest;
import org.simantics.layer0.Layer0;
+import gnu.trove.set.hash.THashSet;
+
public class ValidationUtils {
/**
return validateConstraints(graph, r, null);
}
- public static Set<Issue> validateConstraintsForDomain(ReadGraph graph, Resource r) throws DatabaseException {
+ public static List<Issue> validateConstraintsForDomain(ReadGraph graph, Resource r) throws DatabaseException {
Set<Issue> result = null;
DomainProcessor3 dp = ModelTransferableGraphSourceRequest.getDomainOnly(graph, null, r);
}
}
- return result != null ? result : Collections.<Issue>emptySet();
+ return result != null ? new ArrayList(result) : Collections.<Issue>emptyList();
}
}
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;
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;
public <T> 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.<Boolean>getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) {
+ String error = L0Validations.checkValueType(graph, parentResource, property.predicate);
+ if(error != null) {
+ LOGGER.error(error);
+ throw new ValidationException(error);
+ }
}
}
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.<Boolean>getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) {
+ String error = L0Validations.checkValueType(graph, parentResource, property.predicate);
+ if(error != null) {
+ LOGGER.error(error);
+ throw new ValidationException(error);
+ }
}
}
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.<Boolean>getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) {
+ String error = L0Validations.checkValueType(graph, parentResource, property.predicate);
+ if(error != null) {
+ LOGGER.error(error);
+ throw new ValidationException(error);
+ }
}
}
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.<Boolean>getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) {
+ String error = L0Validations.checkValueType(graph, parentResource, property.predicate);
+ if(error != null) {
+ LOGGER.error(error);
+ throw new ValidationException(error);
+ }
}
}
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
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;
* @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);
}
}
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<Object>() {
@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)
+++ /dev/null
-/*******************************************************************************
- * 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;
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>org.simantics.db.procore.server.environment</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+++ /dev/null
-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
+++ /dev/null
-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
+++ /dev/null
-###############################################################################
-# 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/
+++ /dev/null
-@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
+++ /dev/null
-#!/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
+++ /dev/null
-@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
+++ /dev/null
-@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
+++ /dev/null
-/*******************************************************************************
- * 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 <windows.h>
-#include <Msi.h>
-#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;
-}
+++ /dev/null
-
-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
+++ /dev/null
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
- ProjectType="Visual C++"
- Version="9,00"
- Name="msijni"
- ProjectGUID="{2C249AD2-A0AE-4A88-8DCD-71F96133690E}"
- RootNamespace="msijni"
- Keyword="Win32Proj"
- TargetFrameworkVersion="196613"
- >
- <Platforms>
- <Platform
- Name="Win32"
- />
- <Platform
- Name="x64"
- />
- </Platforms>
- <ToolFiles>
- </ToolFiles>
- <Configurations>
- <Configuration
- Name="Debug|Win32"
- OutputDirectory="$(SolutionDir)$(ConfigurationName)"
- IntermediateDirectory="$(ConfigurationName)"
- ConfigurationType="2"
- CharacterSet="1"
- >
- <Tool
- Name="VCPreBuildEventTool"
- />
- <Tool
- Name="VCCustomBuildTool"
- />
- <Tool
- Name="VCXMLDataGeneratorTool"
- />
- <Tool
- Name="VCWebServiceProxyGeneratorTool"
- />
- <Tool
- Name="VCMIDLTool"
- />
- <Tool
- Name="VCCLCompilerTool"
- Optimization="0"
- AdditionalIncludeDirectories="C:\Program Files\Java\jdk1.6.0_20\include;C:\Program Files\Java\jdk1.6.0_20\include\win32"
- PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;MSIJNI_EXPORTS"
- MinimalRebuild="true"
- BasicRuntimeChecks="3"
- RuntimeLibrary="3"
- UsePrecompiledHeader="0"
- WarningLevel="3"
- DebugInformationFormat="4"
- />
- <Tool
- Name="VCManagedResourceCompilerTool"
- />
- <Tool
- Name="VCResourceCompilerTool"
- />
- <Tool
- Name="VCPreLinkEventTool"
- />
- <Tool
- Name="VCLinkerTool"
- AdditionalDependencies="Msi.lib"
- LinkIncremental="2"
- GenerateDebugInformation="true"
- SubSystem="2"
- TargetMachine="1"
- />
- <Tool
- Name="VCALinkTool"
- />
- <Tool
- Name="VCManifestTool"
- />
- <Tool
- Name="VCXDCMakeTool"
- />
- <Tool
- Name="VCBscMakeTool"
- />
- <Tool
- Name="VCFxCopTool"
- />
- <Tool
- Name="VCAppVerifierTool"
- />
- <Tool
- Name="VCPostBuildEventTool"
- CommandLine="copy "$(TargetPath)" "..\..\src\msijni.dll""
- />
- </Configuration>
- <Configuration
- Name="Debug|x64"
- OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
- IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
- ConfigurationType="2"
- CharacterSet="1"
- >
- <Tool
- Name="VCPreBuildEventTool"
- />
- <Tool
- Name="VCCustomBuildTool"
- />
- <Tool
- Name="VCXMLDataGeneratorTool"
- />
- <Tool
- Name="VCWebServiceProxyGeneratorTool"
- />
- <Tool
- Name="VCMIDLTool"
- TargetEnvironment="3"
- />
- <Tool
- Name="VCCLCompilerTool"
- Optimization="0"
- AdditionalIncludeDirectories="C:\Program Files\Java\jdk1.6.0_20\include;C:\Program Files\Java\jdk1.6.0_20\include\win32"
- PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;MSIJNI_EXPORTS"
- MinimalRebuild="true"
- BasicRuntimeChecks="3"
- RuntimeLibrary="3"
- UsePrecompiledHeader="0"
- WarningLevel="3"
- DebugInformationFormat="3"
- />
- <Tool
- Name="VCManagedResourceCompilerTool"
- />
- <Tool
- Name="VCResourceCompilerTool"
- />
- <Tool
- Name="VCPreLinkEventTool"
- />
- <Tool
- Name="VCLinkerTool"
- LinkIncremental="2"
- GenerateDebugInformation="true"
- SubSystem="2"
- TargetMachine="17"
- />
- <Tool
- Name="VCALinkTool"
- />
- <Tool
- Name="VCManifestTool"
- />
- <Tool
- Name="VCXDCMakeTool"
- />
- <Tool
- Name="VCBscMakeTool"
- />
- <Tool
- Name="VCFxCopTool"
- />
- <Tool
- Name="VCAppVerifierTool"
- />
- <Tool
- Name="VCPostBuildEventTool"
- CommandLine="copy "$(TargetPath)" "..\..\src\msijni64.dll""
- />
- </Configuration>
- <Configuration
- Name="Release|Win32"
- OutputDirectory="$(SolutionDir)$(ConfigurationName)"
- IntermediateDirectory="$(ConfigurationName)"
- ConfigurationType="2"
- CharacterSet="1"
- WholeProgramOptimization="1"
- >
- <Tool
- Name="VCPreBuildEventTool"
- />
- <Tool
- Name="VCCustomBuildTool"
- />
- <Tool
- Name="VCXMLDataGeneratorTool"
- />
- <Tool
- Name="VCWebServiceProxyGeneratorTool"
- />
- <Tool
- Name="VCMIDLTool"
- />
- <Tool
- Name="VCCLCompilerTool"
- Optimization="2"
- EnableIntrinsicFunctions="true"
- AdditionalIncludeDirectories="C:\Program Files\Java\jdk1.6.0_20\include;C:\Program Files\Java\jdk1.6.0_20\include\win32"
- PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;MSIJNI_EXPORTS"
- RuntimeLibrary="2"
- EnableFunctionLevelLinking="true"
- UsePrecompiledHeader="0"
- WarningLevel="3"
- DebugInformationFormat="3"
- />
- <Tool
- Name="VCManagedResourceCompilerTool"
- />
- <Tool
- Name="VCResourceCompilerTool"
- />
- <Tool
- Name="VCPreLinkEventTool"
- />
- <Tool
- Name="VCLinkerTool"
- AdditionalDependencies="Msi.lib"
- LinkIncremental="1"
- AdditionalLibraryDirectories=""
- GenerateDebugInformation="true"
- SubSystem="2"
- OptimizeReferences="2"
- EnableCOMDATFolding="2"
- TargetMachine="1"
- />
- <Tool
- Name="VCALinkTool"
- />
- <Tool
- Name="VCManifestTool"
- />
- <Tool
- Name="VCXDCMakeTool"
- />
- <Tool
- Name="VCBscMakeTool"
- />
- <Tool
- Name="VCFxCopTool"
- />
- <Tool
- Name="VCAppVerifierTool"
- />
- <Tool
- Name="VCPostBuildEventTool"
- CommandLine="copy "$(TargetPath)" "..\..\src\msijni.dll""
- />
- </Configuration>
- <Configuration
- Name="Release|x64"
- OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
- IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
- ConfigurationType="2"
- CharacterSet="1"
- WholeProgramOptimization="1"
- >
- <Tool
- Name="VCPreBuildEventTool"
- />
- <Tool
- Name="VCCustomBuildTool"
- />
- <Tool
- Name="VCXMLDataGeneratorTool"
- />
- <Tool
- Name="VCWebServiceProxyGeneratorTool"
- />
- <Tool
- Name="VCMIDLTool"
- TargetEnvironment="3"
- />
- <Tool
- Name="VCCLCompilerTool"
- Optimization="2"
- EnableIntrinsicFunctions="true"
- AdditionalIncludeDirectories="C:\Program Files\Java\jdk1.6.0_20\include;C:\Program Files\Java\jdk1.6.0_20\include\win32"
- PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;MSIJNI_EXPORTS"
- RuntimeLibrary="2"
- EnableFunctionLevelLinking="true"
- UsePrecompiledHeader="0"
- WarningLevel="3"
- DebugInformationFormat="3"
- />
- <Tool
- Name="VCManagedResourceCompilerTool"
- />
- <Tool
- Name="VCResourceCompilerTool"
- />
- <Tool
- Name="VCPreLinkEventTool"
- />
- <Tool
- Name="VCLinkerTool"
- LinkIncremental="1"
- GenerateDebugInformation="true"
- SubSystem="2"
- OptimizeReferences="2"
- EnableCOMDATFolding="2"
- TargetMachine="17"
- />
- <Tool
- Name="VCALinkTool"
- />
- <Tool
- Name="VCManifestTool"
- />
- <Tool
- Name="VCXDCMakeTool"
- />
- <Tool
- Name="VCBscMakeTool"
- />
- <Tool
- Name="VCFxCopTool"
- />
- <Tool
- Name="VCAppVerifierTool"
- />
- <Tool
- Name="VCPostBuildEventTool"
- CommandLine="copy "$(TargetPath)" "..\..\src\msijni64.dll""
- />
- </Configuration>
- </Configurations>
- <References>
- </References>
- <Files>
- <Filter
- Name="Source Files"
- Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
- UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
- >
- <File
- RelativePath="..\msijni.c"
- >
- </File>
- </Filter>
- <Filter
- Name="Header Files"
- Filter="h;hpp;hxx;hm;inl;inc;xsd"
- UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
- >
- </Filter>
- <Filter
- Name="Resource Files"
- Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
- UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
- >
- </Filter>
- </Files>
- <Globals>
- </Globals>
-</VisualStudioProject>
+++ /dev/null
-/*******************************************************************************
- * 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
+++ /dev/null
-/*******************************************************************************
- * 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;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * 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<Product> requiredProducts;
-
- public ExecutionEnvironmentException(List<Product> requiredProducts) {
- super();
- this.requiredProducts = requiredProducts;
- }
-
- public ExecutionEnvironmentException(String message, List<Product> requiredProducts) {
- super(message);
- this.requiredProducts = requiredProducts;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * 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<Product> products;
-
- public InstallException(List<Product> products) {
- super();
- this.products = products;
- }
-
- public InstallException(String message, List<Product> products) {
- super(message);
- this.products = products;
- }
-
- public InstallException(Throwable cause, List<Product> products) {
- super(cause);
- this.products = products;
- }
-
- public InstallException(String message, Throwable cause, List<Product> products) {
- super(message, cause);
- this.products = products;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * 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
+++ /dev/null
-/*******************************************************************************
- * 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<Product> success) {
- super(success);
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * 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();
- }
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * 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:
- * <ul>
- * <li>{@link #MsiQueryProductState(String)} (see <a
- * href="http://msdn.microsoft.com/en-us/library/aa370363(VS.85).aspx">MSDN</a>)</li>
- * </ul>
- *
- * @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 <code>true</code> 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
+++ /dev/null
-/*******************************************************************************
- * 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;
- }
-
-}
+++ /dev/null
-/*******************************************************************************
- * 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)");
-
-}
+++ /dev/null
-/*******************************************************************************
- * 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 + ")";
- }
-
-}
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
- .,\
- win32.x86/,\
- win32.x86_64/,\
- linux.x86_64/
+ .
\ No newline at end of file
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
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;
}
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);
AdapterRegistry2.this.handleException(e, t);
}
}
+ return null;
}
});
}
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<T> implements Adapter<T, Resource> {
+ private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionAdapter2.class);
+
Constructor<? extends T> constructor;
IDynamicAdapter2[] parameters;
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) {
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<T>() {
+
@Override
- public void run(AsyncReadGraph graph) {
-
+ public void perform(AsyncReadGraph graph, AsyncProcedure<T> p) {
+
Object[] args = new Object[parameters.length];
try {
- for(int i=0;i<parameters.length;++i)
- args[i] = parameters[i].adapt(graph, r);
- procedure.execute(graph, constructor.newInstance(args));
- } catch (IllegalArgumentException e) {
- procedure.exception(g, e);
- e.printStackTrace();
- } catch (InstantiationException e) {
- procedure.exception(g, e);
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- procedure.exception(g, e);
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- procedure.exception(g, e.getCause());
- e.getCause().printStackTrace();
- } catch (DatabaseException e) {
- procedure.exception(g, e);
- e.printStackTrace();
- } catch (Throwable t) {
- procedure.exception(g, t);
- t.printStackTrace();
- }
+ for(int i=0;i<parameters.length;++i)
+ args[i] = parameters[i].adapt(graph, r);
+ p.execute(graph, constructor.newInstance(args));
+ } catch (IllegalArgumentException e) {
+ p.exception(g, e);
+ LOGGER.error("Unexpected exception during adapter creation", e);
+ } catch (InstantiationException e) {
+ p.exception(g, e);
+ LOGGER.error("Unexpected exception during adapter creation", e);
+ } catch (IllegalAccessException e) {
+ p.exception(g, e);
+ LOGGER.error("Unexpected exception during adapter creation", e);
+ } catch (InvocationTargetException e) {
+ p.exception(g, e.getCause());
+ LOGGER.error("Unexpected exception during adapter creation", e);
+ } catch (DatabaseException e) {
+ p.exception(g, e);
+ LOGGER.error("Unexpected exception during adapter creation", e);
+ } catch (Throwable t) {
+ p.exception(g, t);
+ LOGGER.error("Unexpected exception during adapter creation", t);
+ }
+
}
@Override
return "ReflectionAdapter$1" + constructor + "$" + Arrays.toString(parameters);
}
- });
+ }, procedure);
}
+++ /dev/null
-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
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();
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);
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<String> defaultBrowseContexts = Collections.singleton(ProjectResource.URIs.ProjectBrowseContext);
+
@Override
protected IPropertyPage getPropertyPage() {
- return new StandardPropertyPage(getSite());
+ return new StandardPropertyPage(getSite(), defaultBrowseContexts);
}
}
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) {
@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;
+
+ }
+
}
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
L0 = <http://www.simantics.org/Layer0-1.1> : 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."
>-- L0.Entity.methods
@L0.assert L0.Entity.methods
_ : L0.Property
+ L0.HasValueType "StructuredProperty"
L0.Entity.methods ==> "StructuredProperty" <R L0.HasProperty : L0.FunctionalRelation
L0.domainProperties L0.Functions.methodsPropertyDomainProperties
L0.Constraint <T L0.Entity
>-- L0.Constraint.Validator <R L0.HasProperty : L0.FunctionalRelation
- L0.RequiresValueType "ReadGraph => Resource -> [Issue]"
+ L0.RequiresValueType "Resource -> <ReadGraph> [Issue]"
+
+L0.SCLValidator <T L0.SCLValue
+ L0.HasValueType "Resource -> <ReadGraph> [Issue]"
+
L0.HasConstraint <R L0.IsRelatedTo
L0.InverseOf L0.HasConstraint.Inverse <R L0.IsRelatedTo
<-- L0.Type
>-- L0.SCLScript.definition --> L0.String <R L0.HasProperty : L0.TotalFunction
@L0.assert L0.SCLScript.definition ""
+L0.Action <T L0.Entity
+
+L0.SCLAction <T L0.Action
+ --> L0.SCLAction.action ==> "Resource -> <Proc> ()" <R L0.HasProperty : L0.TotalFunction
+
L0.Ontology
>-- L0.Ontology.defaultLocalName --> L0.String <R L0.HasProperty : L0.TotalFunction
@L0.assert L0.Ontology.defaultLocalName ""
%resource %tag %resource
L0.defTag : L0.Template
@template %resource
- %resource <R L0.IsWeaklyRelatedTo : L0.Tag
\ No newline at end of file
+ %resource <R L0.IsWeaklyRelatedTo : L0.Tag
+
+L0.SCLAction.valueType = "Resource -> <Proc> ()" : L0.String
+
+L0.sclAction : L0.Template
+ @template %action %expression
+ %action : L0.SCLAction
+ L0.SCLAction.action _ : L0.SCLValue
+ L0.SCLValue.expression %expression
+ L0.HasValueType L0.SCLAction.valueType
+
+L0.sclConstraint : L0.Template
+ @template %constraint %expression
+ %constraint : L0.Constraint
+ L0.Constraint.Validator _ : L0.SCLValidator
+ L0.SCLValue.expression %expression
+
L0 = <http://www.simantics.org/Layer0-1.1>
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
L0 = <http://www.simantics.org/Layer0-1.1>
-L0.Value <T L0.Entity
+L0.Value <T L0.Entity : L0.ValueType
+
+L0.ValueType <T L0.Type
L0.ExternalValue <T L0.Value
>-- L0.SCLValue.environment --> L0.SCLValue.Environment <R L0.IsRelatedTo : L0.TotalFunction
@L0.assert L0.ConvertsToValueWith L0.Functions.sclValue
-L0.SCLValueType <T L0.Entity
+L0.SCLValueType <T L0.ValueType
>-- L0.SCLValueType.validator ==> "Variable -> <ReadGraph> String" <R L0.HasProperty
L0.scl : L0.Template
import org.simantics.g2d.diagram.DiagramHints;
import org.simantics.layer0.Layer0;
import org.simantics.modeling.ComponentUtils;
+import org.simantics.modeling.ModelingResources;
import org.simantics.modeling.actions.NavigateToTarget;
import org.simantics.modeling.ui.Activator;
import org.simantics.structural.stubs.StructuralResource2;
super(Messages.OpenDiagramFromConfigurationAdapter_DiagramEditor, Activator.COMPOSITE_ICON);
}
- protected String getEditorId() {
- return EDITOR_ID;
+ protected String getEditorId(ReadGraph g, Resource composite) throws DatabaseException {
+ ModelingResources MOD = ModelingResources.getInstance(g);
+ String preferredEditorId = g.getPossibleRelatedValue(composite, MOD.PreferredDiagramEditorID);
+ if(preferredEditorId != null)
+ return preferredEditorId;
+ else
+ return EDITOR_ID;
}
@Override
Simantics.getSession().asyncRequest(new ReadRequest() {
@Override
public void run(ReadGraph g) throws DatabaseException {
- openEditor(g, r, getEditorId());
+ openEditor(g, r, getEditorId(g, r));
}
});
}
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.contexts.IContextService;
+import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.simantics.scl.ui.editor.SCLSourceViewerConfigurationNew;
import org.simantics.scl.ui.editor2.SCLModuleEditor2;
super.createPartControl(parent);
getSite().getService(IContextService.class).activateContext("org.simantics.modeling.ui.scl.scriptEditor.context");
}
+
+ @Override
+ public <T> T getAdapter(Class<T> adapter) {
+ // No outline view for scripts
+ if (IContentOutlinePage.class.equals(adapter)) {
+ return null;
+ }
+
+ return super.getAdapter(adapter);
+ }
}
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);
}
}
}
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;
}
package org.simantics.modeling.typicals;
-import java.util.Collection;
+import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
public TypicalInfoBean bean;
public IProgressMonitor monitor;
- public Collection<String> messageLog;
+ public List<String> messageLog;
}
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,
--- /dev/null
+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;
+}
--- /dev/null
+/*******************************************************************************
+ * 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();
+}
--- /dev/null
+/*******************************************************************************
+ * 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;
+}
--- /dev/null
+/*******************************************************************************
+ * 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();
+}
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;
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
-@IsFieldRule
+@IsMethodRule
public @interface UpdateMethod {
}
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;
// Class<? extends ValueAdapter> adapterClass = getterAnn.adapter();
IRangeAccessor<Range,Object> rangeAccessor = new CompoundGetSetValueAccessor<Range,Object>(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());
// }
return new ValueRule<Resource,Range>(new CompoundValueAccessor(g.getResource(getterAnn.objRelation()),
g.getResource(getterAnn.objType()),
- g.getResource(getterAnn.valRelation())),
+ g.getResource(getterAnn.valRelation()),
+ valueBinding),
rangeAccessor);
}
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;
- }
- }
}
*******************************************************************************/
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))
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;
+ }
}
--- /dev/null
+/*******************************************************************************
+ * 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<Range> implements IFieldRuleFactory<Resource, Range> {
+
+ @Override
+ public IBidirectionalMappingRule<Resource, Range> create(ReadGraph g, Annotation _annotation, Field field) throws ResourceNotFoundException, ValidationException, ServiceException {
+ LinkedList annotation = (LinkedList)_annotation;
+ return new MappedElementsRule<Resource,Range>(
+ new LinkedListAccessor(g.getResource(annotation.value()), g.getResource(annotation.type()), annotation.composition()),
+ new FieldAccessor<Range,Collection<Range>>(field)
+ );
+ }
+
+}
--- /dev/null
+/*******************************************************************************
+ * 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<Range> implements ICollectionRuleFactory<Resource,Range> {
+
+ @Override
+ public IBidirectionalMappingRule<Resource, Range> create(ReadGraph g, Annotation annotation,
+ Method getter, Method adder, Method remover)
+ throws DatabaseException {
+ LinkedListGet getterAnn = (LinkedListGet)annotation;
+ return new MappedElementsRule<Resource,Range>(new LinkedListAccessor(g.getResource(getterAnn.value()), g.getResource(getterAnn.type()), getterAnn.composition()),
+ new CollectionAccessor<Range,Range>(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());
+ }
+
+}
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;
Class<? extends ValueAdapter> adapterClass = getterAnn.adapter();
IRangeAccessor<Range,Object> rangeAccessor = new GetSetValueAccessor<Range,Object>(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();
throw new RuntimeException(e);
}
}
- return new ValueRule<Resource,Range>(new RelatedValueAccessor(g.getResource(getterAnn.value()), valueType),
+ return new ValueRule<Resource,Range>(new RelatedValueAccessor(g.getResource(getterAnn.value()), valueType, valueBinding),
rangeAccessor);
}
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;
Class<? extends ValueAdapter> adapterClass = annotation.adapter();
IRangeAccessor<Range,Object> rangeAccessor = new FieldAccessor<Range,Object>(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();
throw new RuntimeException(e);
}
}
- return new ValueRule<Resource,Range>(new RelatedValueAccessor(g.getResource(annotation.value()), valueType), rangeAccessor);
+ return new ValueRule<Resource,Range>(new RelatedValueAccessor(g.getResource(annotation.value()), valueType, valueBinding), rangeAccessor);
}
}
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;
public class UpdateMethodFactory<Domain, Range> implements IMethodRuleFactory<Domain, Range> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(UpdateMethodFactory.class);
@Override
public IBidirectionalMappingRule<Domain, Range> create(ReadGraph g,
public boolean updateRange(ReadGraph g, IForwardMapping<Domain, Range> 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) {
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;
*/
public class Mapping<Domain, Range> implements IMapping<Domain, Range> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static final Logger LOGGER = LoggerFactory.getLogger(Mapping.class);
IMappingSchema<Domain, Range> schema;
}
private void createDomain(WriteGraph g, Link<Domain,Range> link) throws MappingException {
- LOGGER.info(" createDomain for " + link.rangeElement);
+ LOGGER.trace(" createDomain for " + link.rangeElement);
ILinkType<Domain,Range> type = schema.linkTypeOfRangeElement(link.rangeElement);
Domain domainElement = type.createDomainElement(g, link.rangeElement);
link.type = type;
@Override
public synchronized Collection<Domain> updateDomain(WriteGraph g) throws MappingException {
- LOGGER.info("Mapping.updateDomain");
+ LOGGER.trace("Mapping.updateDomain");
RangeToDomain map = new RangeToDomain(g);
ArrayList<Domain> updated = new ArrayList<Domain>();
while(!modifiedRangeLinks.isEmpty()) {
- LOGGER.info(" modifiedRangeLinks.size() = " + modifiedRangeLinks.size());
+ LOGGER.trace(" modifiedRangeLinks.size() = " + modifiedRangeLinks.size());
Link<Domain,Range> link = modifiedRangeLinks.remove(modifiedRangeLinks.size()-1);
link.rangeModified = false;
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.
@Override
public synchronized Collection<Range> updateRange(ReadGraph g) throws MappingException {
- LOGGER.info("Mapping.updateRange");
+ LOGGER.trace("Mapping.updateRange");
DomainToRange map = new DomainToRange(g);
ArrayList<Range> updated = new ArrayList<Range>();
while(!modifiedDomainLinks.isEmpty()) {
- LOGGER.info(" modifiedDomainLinks.size() = " + modifiedDomainLinks.size());
+ LOGGER.trace(" modifiedDomainLinks.size() = " + modifiedDomainLinks.size());
Link<Domain,Range> link = modifiedDomainLinks.remove(modifiedDomainLinks.size()-1);
link.domainModified = false;
void domainModified(Link<Domain,Range> 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) {
*******************************************************************************/
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;
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
*/
public class MappedElementRule<Domain, Range> implements IBidirectionalMappingRule<Domain, Range> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static final Logger LOGGER = LoggerFactory.getLogger(MappedElementRule.class);
IDomainAccessor<Domain,Domain> domainAccessor;
IRangeAccessor<Range,Range> rangeAccessor;
public boolean updateDomain(WriteGraph g, IBackwardMapping<Domain, Range> 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);
public boolean updateRange(ReadGraph g, IForwardMapping<Domain, Range> 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);
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;
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;
/**
*/
public class MappedElementsRule<Domain, Range> implements IBidirectionalMappingRule<Domain, Range> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static final Logger LOGGER = LoggerFactory.getLogger(MappedElementsRule.class);
IDomainAccessor<Domain,Collection<Domain>> domainAccessor;
IRangeAccessor<Range,Collection<Range>> rangeAccessor;
public boolean updateDomain(WriteGraph g, IBackwardMapping<Domain, Range> 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.
public boolean updateRange(ReadGraph g, IForwardMapping<Domain, Range> map,
Domain domainElement, Range rangeElement)
throws MappingException {
- LOGGER.info(" MappedElementsRule.updateRange");
+ LOGGER.trace(" MappedElementsRule.updateRange");
Collection<Domain> value = domainAccessor.get(g, domainElement);
ArrayList<Range> mappedValue = new ArrayList<Range>(value.size());
for(Domain r : value)
*******************************************************************************/
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;
*/
public class ValueRule<Domain, Range> implements IBidirectionalMappingRule<Domain, Range> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(ValueRule.class);
IDomainAccessor<Domain,Object> domainAccessor;
IRangeAccessor<Range,Object> rangeAccessor;
public boolean updateDomain(WriteGraph g, IBackwardMapping<Domain, Range> 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);
}
public boolean updateRange(ReadGraph g, IForwardMapping<Domain, Range> 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);
}
*******************************************************************************/
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;
/**
*
*/
public class CompoundValueAccessor implements IDomainAccessor<Resource,Object> {
- 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<Statement> coll = g.getStatements(element, objRelation);
Map<String,Object> map = new HashMap<String, Object>();
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<String,Object> values = (Map<String, Object>)v;
valueMap.put(name, g.getRelatedValue(c.getObject(), valRelation));
}
}
+
boolean changed = false;
for (String key : values.keySet()) {
Object value = values.get(key);
}
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)) {
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);
}
}
--- /dev/null
+/*******************************************************************************
+ * 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<Resource,Collection<Resource>> {
+
+ 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<Resource> 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<Resource> value)
+ throws MappingException {
+ try {
+ LOGGER.trace(" LinkdedListAccessor.set");
+ return MappingUtils.synchronizeList(g, element, relation, listType, new ArrayList<Resource>(value), deleteExtraObjects);
+ } catch (DatabaseException e) {
+ throw new MappingException(e);
+ }
+
+ }
+
+}
/*******************************************************************************
- * 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
*
* 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.
*/
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 <code>objects</code>
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
break;
}
else if(cmp > 0) {
- LOGGER.info(" add statement");
+ LOGGER.trace(" add statement");
g.claim(subject, predicate, objects[j]);
modified = true;
++j;
return modified;
}
+ public static boolean synchronizeList(WriteGraph g, Resource element, Resource relation, Resource listType, List<Resource> 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<Resource> 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);
+ }
+
}
*******************************************************************************/
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;
*/
public class RelatedObjectAccessor implements IDomainAccessor<Resource,Resource> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(RelatedObjectAccessor.class);
Resource relation;
@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);
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)
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;
*/
public class RelatedObjectsAccessor implements IDomainAccessor<Resource,Collection<Resource>> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(RelatedObjectsAccessor.class);
Resource relation;
boolean deleteExtraObjects;
@Override
public Collection<Resource> 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);
public boolean set(WriteGraph g, Resource element, Collection<Resource> 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) {
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;
*/
public class RelatedOrderedSetElementsAccessor implements IDomainAccessor<Resource, Collection<Resource>> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(RelatedOrderedSetElementsAccessor.class);
boolean deleteExtraObjects;
@Override
public Collection<Resource> 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);
public boolean set(WriteGraph g, Resource element, Collection<Resource> value)
throws MappingException {
try {
- LOGGER.info(" RelatedOrderedSetElementsAccessor.set");
+ LOGGER.trace(" RelatedOrderedSetElementsAccessor.set");
return OrderedSetUtils.set(g, element, value);
// FIXME Implement deleteExtraObjects
} catch (DatabaseException e) {
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.
*/
public class RelatedValueAccessor implements IDomainAccessor<Resource,Object> {
- 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)
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 {
return false;
}
}
- Object currentValue = g.getValue(valueStatement.getObject());
+ Object currentValue = getValue(g, valueStatement.getObject());
if(equals(currentValue,value))
return false;
if (!valueStatement.isAsserted(element))
g.claim(valueResource, Layer0.getInstance(g).InstanceOf, null,
valueType);
g.claim(element, relation, valueResource);
- g.claimValue(valueResource, value);
+ claimValue(g, valueResource, value);
}
return true;
}
}
}
+
+ 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[])
if (o1 instanceof byte[])
Arrays.equals((byte[])o1,(byte[])o2);
return o1.equals(o2);
-
}
}
import java.lang.reflect.Field;
-import org.apache.log4j.Logger;
import org.simantics.objmap.exceptions.MappingException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
*/
public class FieldAccessor<Range,T> implements IRangeAccessor<Range,T> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static final Logger LOGGER = LoggerFactory.getLogger(FieldAccessor.class);
Field field;
@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
);
try {
Object currentValue = field.get(element);
- if(LOGGER.isInfoEnabled())
- LOGGER.info(" FieldAccessor.set " +
+ if(LOGGER.isTraceEnabled())
+ LOGGER.trace(" FieldAccessor.set " +
field.getName() + " " + currentValue +
" -> " + value
);
*******************************************************************************/
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;
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);
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) {
/*******************************************************************************
- * 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
*
* 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;
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;
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;
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<Object> fromAnnotations(ReadGraph g, Class<?> clazz) throws DatabaseException, InstantiationException, IllegalAccessException {
- GraphType graphType = clazz.getAnnotation(GraphType.class);
-
- if (graphType != null) {
- ArrayList<IBidirectionalMappingRule<Resource, Object>> rules = new ArrayList<IBidirectionalMappingRule<Resource, Object>>();
- collectRulesFromAnnotations(g, clazz, rules);
-
- return new SimpleLinkType<Object>(g.getResource(graphType.value()), clazz, rules);
- }
- DynamicGraphType dynamicType = clazz.getAnnotation(DynamicGraphType.class);
- if (dynamicType != null) {
- ArrayList<IBidirectionalMappingRule<Resource, Object>> rules = new ArrayList<IBidirectionalMappingRule<Resource, Object>>();
- collectRulesFromAnnotations(g, clazz, rules);
-
- return new DynamicSimpleLinkType<Object>(g.getResource(dynamicType.value()), clazz, rules);
- }
- OrderedSetType orderedSetType = clazz.getAnnotation(OrderedSetType.class);
- if (orderedSetType != null) {
- ArrayList<IBidirectionalMappingRule<Resource, Object>> rules = new ArrayList<IBidirectionalMappingRule<Resource, Object>>();
- collectRulesFromAnnotations(g, clazz, rules);
-
- return new OrderedSetSimpleLinkType<Object>(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<IBidirectionalMappingRule<Resource, Object>> rules) throws DatabaseException, InstantiationException, IllegalAccessException {
- Class<?> superclass = clazz.getSuperclass();
- if(superclass != null)
- collectRulesFromAnnotations(g, superclass, rules);
-
+ public static SimpleLinkType<Object> fromAnnotations(ReadGraph g, Class<?> clazz) throws DatabaseException, InstantiationException, IllegalAccessException {
+ GraphType graphType = clazz.getAnnotation(GraphType.class);
+
+ if (graphType != null) {
+ ArrayList<IBidirectionalMappingRule<Resource, Object>> rules = new ArrayList<IBidirectionalMappingRule<Resource, Object>>();
+ collectRulesFromAnnotations(g, clazz, rules);
+
+ return new SimpleLinkType<Object>(g.getResource(graphType.value()), clazz, rules);
+ }
+ DynamicGraphType dynamicType = clazz.getAnnotation(DynamicGraphType.class);
+ if (dynamicType != null) {
+ ArrayList<IBidirectionalMappingRule<Resource, Object>> rules = new ArrayList<IBidirectionalMappingRule<Resource, Object>>();
+ collectRulesFromAnnotations(g, clazz, rules);
+
+ return new DynamicSimpleLinkType<Object>(g.getResource(dynamicType.value()), clazz, rules);
+ }
+ OrderedSetType orderedSetType = clazz.getAnnotation(OrderedSetType.class);
+ if (orderedSetType != null) {
+ ArrayList<IBidirectionalMappingRule<Resource, Object>> rules = new ArrayList<IBidirectionalMappingRule<Resource, Object>>();
+ collectRulesFromAnnotations(g, clazz, rules);
+
+ return new OrderedSetSimpleLinkType<Object>(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<IBidirectionalMappingRule<Resource, Object>> 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<Resource, Object> ruleFactory = createClassRule(g, annotation, clazz);
+ if (ruleFactory != null)
+ rules.add(ruleFactory.create(g, annotation, clazz));
+ else
+ LOGGER.warn("No rule factory found for {}", annotation);
}
}
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<Resource, Object> ruleFactory = createFieldRule(g, annotation, f);
+ if (ruleFactory != null)
+ rules.add(ruleFactory.create(g, annotation, f));
+ else
+ LOGGER.warn("No rule factory found for {}", annotation);
}
}
}
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<Resource, Object> 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<? extends Annotation> annotationType = annotation.annotationType();
-
- IsGetSetRule tag =
- annotationType.getAnnotation(IsGetSetRule.class);
- if (tag != null) {
-
- HasSetter setterAnnType = annotationType.getAnnotation(HasSetter.class);
-
- Class<? extends Annotation> setterAnn = setterAnnType.value();
-
- Method getter = m;
-
- IGetSetRuleFactory<Resource,Object> 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<? extends Annotation> annotationType = annotation.annotationType();
+
+ IsGetSetRule tag =
+ annotationType.getAnnotation(IsGetSetRule.class);
+ if (tag != null) {
+
+ HasSetter setterAnnType = annotationType.getAnnotation(HasSetter.class);
+
+ Class<? extends Annotation> setterAnn = setterAnnType.value();
+
+ Method getter = m;
+
+ IGetSetRuleFactory<Resource,Object> 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<? extends Annotation> 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<? extends Annotation> adderAnn = adderAnnType.value();
- Class<? extends Annotation> removerAnn = removerAnnType.value();
-
- Method getter = m;
-
- ICollectionRuleFactory<Resource,Object> 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<? extends Annotation> 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<? extends Annotation> adderAnn = adderAnnType.value();
+ Class<? extends Annotation> removerAnn = removerAnnType.value();
+
+ Method getter = m;
+
+ ICollectionRuleFactory<Resource,Object> 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<Resource, Object> createClassRule(ReadGraph g, Annotation annotation, Class<?> clazz) {
- return null;
- }
-
- public static IFieldRuleFactory<Resource,Object> createFieldRule(ReadGraph g, Annotation annotation, Field field) {
- if (annotation.annotationType().equals(RelatedElements.class))
- return new RelatedElementsRuleFactory<Object>();
- if (annotation.annotationType().equals(RelatedValue.class))
- return new RelatedValueRuleFactory<Object>();
- if (annotation.annotationType().equals(OptionalRelatedElements.class))
- return new OptionalRelatedElementsRuleFactory<Object>();
- if (annotation.annotationType().equals(RelatedOrderedSetElements.class))
- return new RelatedOrderedSetElementsRuleFactory<Object>();
- return null;
- }
-
- public static IMethodRuleFactory<Resource, Object> createMethodRule(ReadGraph g, Annotation annotation, Method m) {
- if (annotation.annotationType().equals(UpdateMethod.class))
- return new UpdateMethodFactory<Resource,Object>();
- return null;
- }
-
- public static IGetSetRuleFactory<Resource,Object> createGetSetRuleFactory(ReadGraph g, Annotation annotation, Method getter) {
- if (annotation.annotationType().equals(RelatedGetValue.class))
- return new RelatedGetSetValueRuleFactory<Object>();
- if (annotation.annotationType().equals(RelatedGetObj.class))
- return new RelatedGetSetObjRuleFactory<Object>();
- if (annotation.annotationType().equals(CompoundRelatedGetValue.class))
- return new CompoundRelatedGetSetValueRuleFactory<Object>();
- return null;
- }
-
- public static ICollectionRuleFactory<Resource,Object> createCollectionRuleFactory(ReadGraph g, Annotation annotation, Method getter) {
- if (annotation.annotationType().equals(RelatedElementsGet.class))
- return new RelatedElementsRuleFactory2<Object>();
- if (annotation.annotationType().equals(OrderedElementsGet.class))
- return new OrderedElementsRuleFactory<Object>();
- return null;
- }
-
- /**
+
+ public static IClassRuleFactory<Resource, Object> createClassRule(ReadGraph g, Annotation annotation, Class<?> clazz) {
+ return null;
+ }
+
+ public static IFieldRuleFactory<Resource,Object> createFieldRule(ReadGraph g, Annotation annotation, Field field) {
+ if (annotation.annotationType().equals(RelatedElement.class))
+ return new RelatedElementRuleFactory<Object>();
+ if (annotation.annotationType().equals(RelatedElements.class))
+ return new RelatedElementsRuleFactory<Object>();
+ if (annotation.annotationType().equals(RelatedValue.class))
+ return new RelatedValueRuleFactory<Object>();
+ if (annotation.annotationType().equals(OptionalRelatedElements.class))
+ return new OptionalRelatedElementsRuleFactory<Object>();
+ if (annotation.annotationType().equals(RelatedOrderedSetElements.class))
+ return new RelatedOrderedSetElementsRuleFactory<Object>();
+ if (annotation.annotationType().equals(LinkedList.class))
+ return new LinkedListRuleFactory<Object>();
+ return null;
+ }
+
+ public static IMethodRuleFactory<Resource, Object> createMethodRule(ReadGraph g, Annotation annotation, Method m) {
+ if (annotation.annotationType().equals(UpdateMethod.class))
+ return new UpdateMethodFactory<Resource,Object>();
+ return null;
+ }
+
+ public static IGetSetRuleFactory<Resource,Object> createGetSetRuleFactory(ReadGraph g, Annotation annotation, Method getter) {
+ if (annotation.annotationType().equals(RelatedGetValue.class))
+ return new RelatedGetSetValueRuleFactory<Object>();
+ if (annotation.annotationType().equals(RelatedGetObj.class))
+ return new RelatedGetSetObjRuleFactory<Object>();
+ if (annotation.annotationType().equals(CompoundRelatedGetValue.class))
+ return new CompoundRelatedGetSetValueRuleFactory<Object>();
+ return null;
+ }
+
+ public static ICollectionRuleFactory<Resource,Object> createCollectionRuleFactory(ReadGraph g, Annotation annotation, Method getter) {
+ if (annotation.annotationType().equals(RelatedElementsGet.class))
+ return new RelatedElementsRuleFactory2<Object>();
+ if (annotation.annotationType().equals(OrderedElementsGet.class))
+ return new OrderedElementsRuleFactory<Object>();
+ 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<Object> fromAdaptable(ReadGraph g, String type, Class<?> clazz) throws DatabaseException, InstantiationException, IllegalAccessException {
-
-
- return new AdaptedLinkType<Object>(g.getResource(type), clazz);
- }
-
-
+
+ public static AdaptedLinkType<Object> fromAdaptable(ReadGraph g, String type, Class<?> clazz) throws DatabaseException, InstantiationException, IllegalAccessException {
+
+
+ return new AdaptedLinkType<Object>(g.getResource(type), clazz);
+ }
+
+
}
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);
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;
*/
public class SimpleLinkType<Range> implements ILinkType<Resource,Range> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(SimpleLinkType.class);
public Resource domainType;
public Class<?> rangeType;
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();
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) {
};
public boolean updateDomain(WriteGraph g, IBackwardMapping<Resource,Range> 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()
);
public boolean updateRange(ReadGraph g, IForwardMapping<Resource,Range> 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);
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;
public class UpdateMethodFactory<Domain, Range> implements IMethodRuleFactory<Domain, Range> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(UpdateMethodFactory.class);
@Override
public IBidirectionalMappingRule<Domain, Range> create(ReadGraph g,
public boolean updateRange(ReadGraph g, IForwardMapping<Domain, Range> 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) {
*******************************************************************************/
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;
public class RelatedObjectAccessor implements IDomainAccessor<StructuralResource,StructuralResource> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(RelatedObjectAccessor.class);
Resource relation;
boolean useTypeResource;
@Override
public StructuralResource get(ReadGraph g, StructuralResource element) throws MappingException {
try {
- LOGGER.info(" RelatedObjectAccessor.get");
+ LOGGER.trace(" RelatedObjectAccessor.get");
Resource res = getServiceResource(g, element);
if (res == null)
return null;
public boolean set(WriteGraph g, StructuralResource selement, StructuralResource value)
throws MappingException {
try {
- LOGGER.info(" RelatedObjectAccessor.set");
+ LOGGER.trace(" RelatedObjectAccessor.set");
Resource element = getServiceResource(g, selement);
if (element == null)
return false;
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;
public class RelatedObjectsAccessor implements IDomainAccessor<StructuralResource,Collection<StructuralResource>> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(RelatedObjectsAccessor.class);
Resource relation;
boolean deleteExtraObjects;
@Override
public Collection<StructuralResource> get(ReadGraph g, StructuralResource element) throws MappingException {
try {
- LOGGER.info(" RelatedObjectsAccessor.get");
+ LOGGER.trace(" RelatedObjectsAccessor.get");
Resource res = getServiceResource(g, element);
public boolean set(WriteGraph g, StructuralResource element, Collection<StructuralResource> value)
throws MappingException {
try {
- LOGGER.info(" RelatedObjectsAccessor.set");
+ LOGGER.trace(" RelatedObjectsAccessor.set");
Resource res = getServiceResource(g, element);
if (res == null)
return false;
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;
public class RelatedOrderedSetElementsAccessor implements IDomainAccessor<StructuralResource, Collection<StructuralResource>> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(RelatedOrderedSetElementsAccessor.class);
boolean deleteExtraObjects;
boolean useTypeResource;
@Override
public Collection<StructuralResource> 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();
public boolean set(WriteGraph g, StructuralResource element, Collection<StructuralResource> value)
throws MappingException {
try {
- LOGGER.info(" RelatedOrderedSetElementsAccessor.set");
+ LOGGER.trace(" RelatedOrderedSetElementsAccessor.set");
Resource res = getServiceResource(g, element);
if (res == null)
return false;
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;
public class RelatedValueAccessor implements IDomainAccessor<StructuralResource,Object> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(RelatedValueAccessor.class);
Resource relation;
Resource valueType;
@Override
public Object get(ReadGraph g, StructuralResource element) throws MappingException {
try {
- LOGGER.info(" RelatedValueAccessor.get");
+ LOGGER.trace(" RelatedValueAccessor.get");
Resource res = getServiceResource(g, element);
if (res == null)
return null;
public boolean set(WriteGraph g, StructuralResource relement, Object value)
throws MappingException {
try {
- LOGGER.info(" RelatedValueAccessor.set");
+ LOGGER.trace(" RelatedValueAccessor.set");
Resource element = getServiceResource(g, relement);
if (element == null)
import java.util.ArrayList;
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;
public class StructuralRelatedObjectAccessor implements IDomainAccessor<StructuralResource,StructuralResource> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(StructuralRelatedObjectAccessor.class);
Resource relation;
boolean useTypeResource;
public StructuralResource get(ReadGraph g, StructuralResource element) throws MappingException {
try {
- LOGGER.info(" RelatedObjectAccessor.get");
+ LOGGER.trace(" RelatedObjectAccessor.get");
if (!element.isStructural())
return null;
public boolean set(WriteGraph g, StructuralResource element, StructuralResource value)
throws MappingException {
try {
- LOGGER.info(" RelatedObjectAccessor.set");
+ LOGGER.trace(" RelatedObjectAccessor.set");
Resource instance = StructuralUtils.getContainingInstance(element);
Resource publicRelation = null;
if (instance == null)
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;
public class StructuralRelatedObjectsAccessor implements IDomainAccessor<StructuralResource,Collection<StructuralResource>> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(StructuralRelatedObjectsAccessor.class);
Resource relation;
boolean deleteExtraObjects;
@Override
public Collection<StructuralResource> get(ReadGraph g, StructuralResource element) throws MappingException {
try {
- LOGGER.info(" RelatedObjectsAccessor.get");
+ LOGGER.trace(" RelatedObjectsAccessor.get");
if (!element.isStructural())
return Collections.emptyList();
public boolean set(WriteGraph g, StructuralResource element, Collection<StructuralResource> value)
throws MappingException {
try {
- LOGGER.info(" RelatedObjectsAccessor.set");
+ LOGGER.trace(" RelatedObjectsAccessor.set");
if (!element.isStructural())
return false;
*******************************************************************************/
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;
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;
public class SimpleLinkType implements ILinkType<StructuralResource,IStructuralObject> {
- static Logger LOGGER = Logger.getLogger("org.simantics.objmap");
+ static Logger LOGGER = LoggerFactory.getLogger(SimpleLinkType.class);
public Resource domainType;
public Class<?> rangeType;
public StructuralResource createDomainElement(WriteGraph g, IStructuralObject rangeElement)
throws MappingException {
try {
- if(LOGGER.isInfoEnabled())
- LOGGER.info("SimpleLinkType.createDomainElement " +
+ if(LOGGER.isTraceEnabled())
+ LOGGER.trace("SimpleLinkType.createDomainElement " +
rangeElement.toString()
);
if (rangeElement.getContext().size() == 0) {
public IStructuralObject createRangeElement(ReadGraph g, StructuralResource domainElement)
throws MappingException {
try {
- if(LOGGER.isInfoEnabled())
+ if(LOGGER.isTraceEnabled())
try {
- LOGGER.info("SimpleLinkType.createRangeElement " + NameUtils.getSafeName(g, domainElement.getResource()));
+ LOGGER.trace("SimpleLinkType.createRangeElement " + NameUtils.getSafeName(g, domainElement.getResource()));
} catch(DatabaseException e) {
throw new MappingException(e);
}
}
public boolean updateDomain(WriteGraph g, IBackwardMapping<StructuralResource,IStructuralObject> 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()
);
public boolean updateRange(ReadGraph g, IForwardMapping<StructuralResource, IStructuralObject> 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()
);
*******************************************************************************/
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;
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
+++ /dev/null
-# 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
StringBuilder signature = new StringBuilder();
signature.append("<div id=\"")
.append(HtmlEscape.escape(name))
- .append("\" class=\"code-doc-box\"><div class=\"code\">");
+ .append("\" class=\"code-doc-box\"><div class=\"code value\">");
char firstChar = name.charAt(0);
if(!Character.isAlphabetic(firstChar) && firstChar != '_')
name = "(" + name + ")";
TypeUnparsingContext tuc = new TypeUnparsingContext();
StringBuilder signature = new StringBuilder();
- signature.append("<div class=\"code-doc-box\"><div class=\"code\">");
+ signature.append("<div id=\"class-")
+ .append(HtmlEscape.escape(name))
+ .append("\" class=\"code-doc-box\"><div class=\"code class\">");
signature.append("class ");
if(typeClass.context.length > 0) {
signature.append('(');
TypeUnparsingContext tuc = new TypeUnparsingContext();
StringBuilder signature = new StringBuilder();
- signature.append("<div class=\"code-doc-box\"><div class=\"code\">");
+ signature.append("<div id=\"data-")
+ .append(HtmlEscape.escape(name))
+ .append("\" class=\"code-doc-box\"><div class=\"code data\">");
signature.append("data ");
signature.append(typeDescriptor.name.name);
if(typeDescriptor instanceof TypeConstructor) {
.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;
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;
}
@JavaName denyValue
denyValue :: Resource -> <WriteGraph> ()
-claimAssertion :: Resource -> Resource -> Resource -> <WriteGraph> ()
-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 -> <WriteGraph> ()
addMetadataListener :: ChangeListener -> <Proc> ()
removeMetadataListener :: ChangeListener -> <Proc> ()
+ @JavaName assert_
+ claimAssertion :: Resource -> Resource -> Resource -> <WriteGraph> ()
+
copyTo :: Resource -> Resource -> <WriteGraph> Resource
copyTo targetContainer source = do
(collectionToList $ copyTo_ targetContainer source)!0
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;
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;
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<RuntimeModule> 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<TCon> getEffects(SCLValue value) throws ValueNotFoundException, ValueNotFound, MatchException {
+
+ Type type = value.getType();
+ MultiFunction mfun = Types.matchFunction(type, 1);
+ ArrayList<TCon> concreteEffects = new ArrayList<>();
+ mfun.effect.collectConcreteEffects(concreteEffects);
+ return concreteEffects;
+
+ }
+
+ public static List<TCon> getEffects(RuntimeModule rm, String function) throws ValueNotFoundException, ValueNotFound, MatchException {
+ return getEffects(resolveSCLValue(rm, function));
+ }
+
+ public static List<TCon> getEffects(String module, String function) throws ValueNotFoundException, ValueNotFound, MatchException {
+ return getEffects(resolveSCLValue(resolveRuntimeModule(module), function));
+ }
+
+ private static <T> T evaluate(Function function, Object ... args) {
+ return (T)function.applyArray(args);
+ }
+
+ private static <T> T evaluate(RuntimeModule rm, String function, Object ... args) throws ValueNotFound {
+ return evaluate(resolveFunction(rm, function));
+ }
+
+ public static <T> T evaluate(String module, String function, Object ... args) throws ValueNotFound {
+ return evaluate(resolveRuntimeModule(module), function, args);
+ }
+
+ public static <T> T evaluateDB(String module, String function, Object ... args) throws DatabaseException {
+ try {
+ RuntimeModule rm = resolveRuntimeModule(module);
+ List<TCon> 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> 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 <T> 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
}
public static <T> T syncRead(final Function f) throws DatabaseException {
+ return syncRead(f, NO_ARGS);
+ }
+
+ public static <T> 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<T>() {
@Override
});
}
}
-
+
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() {
SCLContext.push(context);
context.put(GRAPH, graph);
try {
- f.apply(Tuple0.INSTANCE);
+ f.apply(args);
} finally {
SCLContext.pop();
}
}
public static <T> T syncWrite(final Function f) throws DatabaseException {
+ return syncWrite(f, NO_ARGS);
+ }
+
+ public static <T> T syncWrite(final Function f, final Object ... args) throws DatabaseException {
final SCLContext context = SCLContext.getCurrent();
Object graph = context.get(GRAPH);
if (graph != null) {
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);
public static <T> T delayedSyncWrite(final Function f) throws DatabaseException {
final SCLContext context = SCLContext.getCurrent();
- final DataContainer<T> dc = new DataContainer<T>(null);
+ final DataContainer<T> dc = new DataContainer<T>(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));
}
}
};
-
+
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> T virtualSyncWriteMem(WriteGraph graph, String virtualGraphId, final Function f) throws DatabaseException {
@Override
public T perform(ReadGraph graph) throws DatabaseException {
return Variables.getVariable(graph, uri).getValue(graph);
- }
+ }
});
}
@Override
public void perform(WriteGraph graph) throws DatabaseException {
Variables.getVariable(graph, uri).setValue(graph, value);
- }
+ }
});
}
public static class SCLUnaryRead extends BinaryRead<Function1<Object,Object>, Object, Object> {
- public SCLUnaryRead(Function1<Object, Object> parameter1, Object parameter2) {
- super(parameter1, parameter2);
- }
+ public SCLUnaryRead(Function1<Object, Object> 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<Object,Object> 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<Object,Object> fn, Object value) throws DatabaseException {
- return graph.syncRequest(new SCLUnaryRead(fn, value), TransientCacheAsyncListener.<Object>instance());
+ return graph.syncRequest(new SCLUnaryRead(fn, value), TransientCacheAsyncListener.<Object>instance());
}
}
public static Object possibleFromDynamic(Type expectedType, String moduleName, Object value) {
-
+
try {
-
+
Failable<Module> 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);
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();
}
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 {
@Override
public void notifyAboutUpdate() {
- parent.getDisplay().asyncExec(() -> {
+ if (parent.isDisposed())
+ return;
+
+ Failable<Module> 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> module = SCLOsgi.MODULE_REPOSITORY.getModule(moduleSource.getModuleName(), updateListener);
- Module result = module.getResult();
- outlineViewer.setInput(result);
+
+ updateListener.notifyAboutUpdate();
}
@Override
L0.readOnly true
@L0.assert SEL.HasDisplayValue
_ : SEL.DisplayValue
- SEL.HasEnumerationValues _ : L0.Value
- L0.ConvertsToValueWith SEL.Functions.getEnumerationValues
+ SEL.HasEnumerationValues SEL.Functions.getEnumerationValues
@L0.assert SEL.HasDisplayUnit
_ : SEL.DisplayUnit
L0.readOnly true
L0.HasValueType "String"
STR.Component
- L0.HasConstraint STR.ConnectionConstraint : L0.Constraint
+ L0.HasConstraint STR.ConnectionValidationConstraint : L0.Constraint
L0.Constraint.Validator
STR.Functions.connectionValidator : L0.Function
-STR.ConnectionConstraint.ErrorIssue
+STR.ConnectionValidationConstraint.ErrorIssue
@ISSUE.issue ISSUE.Severity.Error
STR.Functions.connectionIssueDescription : L0.Function
L0.HasValueType "String"
-STR.ConnectionConstraint.Source <T ISSUE.Sources.DependencyTracker
+STR.ConnectionValidationConstraint.Source <T ISSUE.Sources.DependencyTracker
L0.HasLabel "Structural connection validity"
@L0.assert ISSUE.Sources.DependencyTracker.HasType STR.Component
@L0.assert ISSUE.Sources.DependencyTracker.HasSearchType STR.Connection
for(Resource req : requiredConnections) {
if(!connections.contains(req)) {
- result.add(new StandardIssue(sr.ConnectionConstraint_ErrorIssue, component, req));
+ result.add(new StandardIssue(sr.ConnectionValidationConstraint_ErrorIssue, component, req));
}
}
needDrill = new THashSet<VariableConnectionPointDescriptor>(climbed.size());
needDrill.add(desc);
} else {
+ if(relationType != null) {
+ if(!filterByRelationType(graph, desc, relationType))
+ continue;
+ }
if(result == null)
result = new THashSet<VariableConnectionPointDescriptor>(climbed.size());
result.add(desc);
}
}
- if(needDrill == null) {
- /*
- * All descriptors were already flat - just take case of filtering
- */
- if(relationType != null) {
- ArrayList<VariableConnectionPointDescriptor> filtered = new ArrayList<VariableConnectionPointDescriptor>(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<VariableConnectionPointDescriptor> 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<VariableConnectionPointDescriptor>(climbed.size());
+ result.add(drill);
+ }
+ }
}
}
-
- /*
- * There were some descriptors that require drill
- */
- for(VariableConnectionPointDescriptor top : needDrill) {
- Collection<VariableConnectionPointDescriptor> 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<VariableConnectionPointDescriptor>(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 {
public void widgetSelected(SelectionEvent e) {
String[] name = openDialog();
if (name != null) {
- setFilename(name);
+ setFilename(name,true);
}
}
});
@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);
}
});
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;
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;
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",
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",
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;
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;
}
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",
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;
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;
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;
}
+ 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.
String message = "Session context created";
LOGGER.info(message);
if (init) {
- sessionContext.registerServices();
+ registerServices(sessionContext);
message = "Session services registered";
LOGGER.info(message);
}
+++ /dev/null
-/*******************************************************************************
- * 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.
- *
- * <p>
- * To get up and running, simply invoke:
- * <pre>
- * SessionUtil util = new SessionUtil("my-client-id");
- * try {
- * File workspaceLocation = ...;
- * Session session = util.openSession(workspaceLocation);
- * // do something with the database session
- * } finally {
- * util.close();
- * }
- * </pre>
- *
- * <p>
- * 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;
- }
-
-}
<module>org.simantics.db.layer0</module>
<module>org.simantics.db.management</module>
<module>org.simantics.db.procore</module>
- <module>org.simantics.db.procore.server.environment</module>
<module>org.simantics.db.procore.ui</module>
<module>org.simantics.db.server</module>
<module>org.simantics.db.services</module>
version="0.0.0"
unpack="false"/>
- <plugin
- id="org.simantics.db.procore.server.environment"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
<plugin
id="org.simantics.workbench"
download-size="0"