Merge branch 'develop' into feature/soql

This commit is contained in:
Robert von Burg 2018-02-27 17:05:50 +01:00
commit ae405492e9
300 changed files with 8227 additions and 9058 deletions

View File

@ -10,7 +10,7 @@ fi
bundle_name="${projectName}-${projectVersion}"
workDir="${ROOT}/target/${bundle_name}"
DIST_STROLCH="/var/www/eitch/strolch.li/dist/${projectVersion}"
DIST_STROLCH="/opt/www/eitch/strolch.li/dist/${projectVersion}"
DEPLOY_SERVER="hosting.eitchnet.ch"
echo "INFO: Creating bundle ${bundle_name}"

View File

@ -56,9 +56,9 @@ public interface AuditTrail {
public void addAll(StrolchTransaction tx, List<Audit> audits);
public Audit update(StrolchTransaction tx, Audit audit);
public void update(StrolchTransaction tx, Audit audit);
public List<Audit> updateAll(StrolchTransaction tx, List<Audit> audits);
public void updateAll(StrolchTransaction tx, List<Audit> audits);
public void remove(StrolchTransaction tx, Audit audit);

View File

@ -444,7 +444,7 @@ public interface ElementMap<T extends StrolchRootElement> {
* <p>
* <b>Note:</b> This method should only be used in the same transaction where the element was created to undo a
* change in the same transaction. If there is a requirement to revert to a previous version, then the
* {@link #revertToVersion(StrolchTransaction, StrolchRootElement)} method.
* {@link #revertToVersion(StrolchTransaction, StrolchRootElement)} method should be used.
* </p>
*
* @param tx

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -23,7 +23,7 @@ import li.strolch.model.Tags;
* Implementing the observer pattern by allowing {@link Observer} to register themselves for updates to
* {@link StrolchRootElement}
* </p>
*
*
* <p>
* Note: The key in all the methods can be any string, but as a convenience it is mostly one of the following:
* </p>
@ -32,51 +32,51 @@ import li.strolch.model.Tags;
* <li>{@link Tags#ORDER}</li>
* <li>{@link Tags#ACTIVITY}</li>
* </ul>
*
*
* <p>
* Should a special case arise, then it a contract must be defined by which a key is negotiated between an event
* distributer and the observer
* </p>
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public interface ObserverHandler {
/**
* Update observers with the given event
*
*
* @param observerEvent
* containing the updates
* containing the updates
*/
public void notify(ObserverEvent observerEvent);
void notify(ObserverEvent observerEvent);
/**
* Registers the {@link Observer} for notification of objects under the given key
*
*
* @param key
* the key for which to the observer wants to be notified
* the key for which to the observer wants to be notified
* @param observer
* the observer to register
* the observer to register
*/
public void registerObserver(String key, Observer observer);
void registerObserver(String key, Observer observer);
/**
* Unregister the given {@link Observer}
*
*
* @param key
* the key for which to the observer was registered
* the key for which to the observer was registered
* @param observer
* the observer unregister
* the observer unregister
*/
public void unregisterObserver(String key, Observer observer);
void unregisterObserver(String key, Observer observer);
/**
* Start the update thread
*/
public void start();
void start();
/**
* Stop the update thread
*/
public void stop();
void stop();
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -19,6 +19,8 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
@ -26,15 +28,16 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import li.strolch.agent.impl.ComponentContainerImpl;
import li.strolch.runtime.ThreadPoolFactory;
import li.strolch.runtime.configuration.ConfigurationParser;
import li.strolch.runtime.configuration.RuntimeConfiguration;
import li.strolch.runtime.configuration.StrolchConfiguration;
import li.strolch.utils.dbc.DBC;
import li.strolch.utils.helper.StringHelper;
import li.strolch.utils.helper.SystemHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -48,8 +51,9 @@ public class StrolchAgent {
private ComponentContainerImpl container;
private StrolchConfiguration strolchConfiguration;
private StrolchVersion appVersion;
private ExecutorService executor;
private ScheduledExecutorService scheduledExecutor;
private Map<String, ExecutorService> executors;
private Map<String, ScheduledExecutorService> scheduledExecutors;
public StrolchAgent(StrolchVersion appVersion) {
this.appVersion = appVersion;
@ -57,7 +61,7 @@ public class StrolchAgent {
/**
* Return the {@link StrolchConfiguration}
*
*
* @return the {@link StrolchConfiguration}
*/
public StrolchConfiguration getStrolchConfiguration() {
@ -66,7 +70,7 @@ public class StrolchAgent {
/**
* Return the container
*
*
* @return the container
*/
public ComponentContainer getContainer() {
@ -82,20 +86,42 @@ public class StrolchAgent {
/**
* Return the {@link ExecutorService} instantiated for this agent
*
*
* @return the {@link ExecutorService} instantiated for this agent
*/
public ExecutorService getExecutor() {
return this.executor;
return getExecutor("Agent");
}
public synchronized ExecutorService getExecutor(String poolName) {
DBC.PRE.assertNotEmpty("poolName must be set!", poolName);
ExecutorService executor = this.executors.get(poolName);
if (executor == null) {
executor = Executors.newCachedThreadPool(new ThreadPoolFactory(poolName));
this.executors.put(poolName, executor);
}
return executor;
}
/**
* Return the {@link ScheduledExecutorService} instantiated for this agent
*
*
* @return the {@link ScheduledExecutorService} instantiated for this agent
*/
public ScheduledExecutorService getScheduledExecutor() {
return this.scheduledExecutor;
return getScheduledExecutor("Agent");
}
public synchronized ScheduledExecutorService getScheduledExecutor(String poolName) {
DBC.PRE.assertNotEmpty("poolName must be set!", poolName);
ScheduledExecutorService executor = this.scheduledExecutors.get(poolName);
if (executor == null) {
executor = Executors.newScheduledThreadPool(4, new ThreadPoolFactory(poolName));
this.scheduledExecutors.put(poolName, executor);
}
return executor;
}
/**
@ -105,8 +131,10 @@ public class StrolchAgent {
public void initialize() {
if (this.container == null)
throw new RuntimeException("Please call setup first!");
this.executor = Executors.newCachedThreadPool();
this.scheduledExecutor = Executors.newScheduledThreadPool(4);
this.executors = new HashMap<>();
this.scheduledExecutors = new HashMap<>();
this.container.initialize(this.strolchConfiguration);
}
@ -127,17 +155,23 @@ public class StrolchAgent {
this.container.stop();
}
private void shutdownExecutorService(ExecutorService executor) {
try {
logger.info("Shutting down executor...");
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error("Was interrupted while shutting down tasks");
} finally {
if (!executor.isTerminated()) {
logger.error("Tasks not stopped after " + 5 + "s. Shutting down now.");
executor.shutdownNow();
private <T extends ExecutorService> void shutdownExecutorService(Map<String, T> executors) {
for (String poolName : executors.keySet()) {
logger.info("Shutting down executor pool " + poolName);
T executor = executors.get(poolName);
try {
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error("Was interrupted while shutting down tasks");
} finally {
if (!executor.isTerminated()) {
logger.error("Tasks not stopped after " + 5 + "s. Shutting down now.");
executor.shutdownNow();
}
}
}
}
@ -147,10 +181,10 @@ public class StrolchAgent {
*/
public void destroy() {
if (this.executor != null)
shutdownExecutorService(this.executor);
if (this.scheduledExecutor != null)
shutdownExecutorService(this.scheduledExecutor);
if (this.executors != null)
shutdownExecutorService(this.executors);
if (this.scheduledExecutors != null)
shutdownExecutorService(this.scheduledExecutors);
if (this.container != null)
this.container.destroy();
@ -161,15 +195,19 @@ public class StrolchAgent {
* <p>
* <b>Note:</b> Use {@link StrolchBootstrapper} instead of calling this method directly!
* </p>
*
*
* <p>
* Sets up the agent by parsing the configuration file and initializes the given environment
* </p>
*
*
* @param environment
* the current environment
* @param configPathF
* the path to the config directory
* @param dataPathF
* the path to the data directory
* @param tempPathF
* the path to the temp directory
*/
void setup(String environment, File configPathF, File dataPathF, File tempPathF) {
@ -180,8 +218,8 @@ public class StrolchAgent {
logger.info(" - Temp: " + tempPathF.getAbsolutePath());
logger.info(" - user.dir: " + SystemHelper.getUserDir());
this.strolchConfiguration = ConfigurationParser.parseConfiguration(environment, configPathF, dataPathF,
tempPathF);
this.strolchConfiguration = ConfigurationParser
.parseConfiguration(environment, configPathF, dataPathF, tempPathF);
ComponentContainerImpl container = new ComponentContainerImpl(this);
container.setup(this.strolchConfiguration);
@ -189,7 +227,8 @@ public class StrolchAgent {
this.container = container;
RuntimeConfiguration config = this.strolchConfiguration.getRuntimeConfiguration();
logger.info(MessageFormat.format("Setup Agent {0}:{1}", config.getApplicationName(), config.getEnvironment())); //$NON-NLS-1$
logger.info(MessageFormat
.format("Setup Agent {0}:{1}", config.getApplicationName(), config.getEnvironment())); //$NON-NLS-1$
}
protected void assertContainerStarted() {
@ -217,7 +256,7 @@ public class StrolchAgent {
/**
* Returns the version of this agent
*
*
* @return the version of this agent
*/
public VersionQueryResult getVersion() {
@ -228,13 +267,14 @@ public class StrolchAgent {
Properties properties = new Properties();
try (InputStream stream = getClass().getResourceAsStream(AGENT_VERSION_PROPERTIES);) {
try (InputStream stream = getClass().getResourceAsStream(AGENT_VERSION_PROPERTIES)) {
properties.load(stream);
AgentVersion agentVersion = new AgentVersion(
getStrolchConfiguration().getRuntimeConfiguration().getApplicationName(), properties);
queryResult.setAgentVersion(agentVersion);
} catch (IOException e) {
String msg = MessageFormat.format("Failed to read version properties for agent: {0}", e.getMessage()); //$NON-NLS-1$
String msg = MessageFormat
.format("Failed to read version properties for agent: {0}", e.getMessage()); //$NON-NLS-1$
queryResult.getErrors().add(msg);
logger.error(msg, e);
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -42,17 +42,17 @@ import li.strolch.runtime.privilege.PrivilegedRunnableWithResult;
* A {@link StrolchComponent} is a configurable extension to Strolch. Every major feature should be implemented as a
* {@link StrolchComponent} so that they can be easily added or removed from a Strolch runtime.
* </p>
*
*
* <p>
* A {@link StrolchComponent} has access to the container and can perform different operations. They can be passive or
* active and their life cycle is bound to the container's life cycle
* </p>
*
*
* <p>
* A {@link StrolchComponent} is registered in the Strolch configuration file and can have different configuration
* depending on the container's runtime environment
* </p>
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class StrolchComponent {
@ -68,11 +68,11 @@ public class StrolchComponent {
/**
* Constructor which takes a reference to the container and the component's name under which it can be retrieved at
* runtime (although one mostly retrieves the component by interface class for automatic casting)
*
*
* @param container
* the container
* the container
* @param componentName
* the component name
* the component name
*/
public StrolchComponent(ComponentContainer container, String componentName) {
this.container = container;
@ -89,7 +89,7 @@ public class StrolchComponent {
/**
* Returns the current component's state
*
*
* @return the component's current state
*/
public ComponentState getState() {
@ -98,7 +98,7 @@ public class StrolchComponent {
/**
* Returns the reference to the container for sub classes
*
*
* @return the reference to the container
*/
protected ComponentContainer getContainer() {
@ -107,7 +107,7 @@ public class StrolchComponent {
/**
* The components current configuration dependent on the environment which is loaded
*
*
* @return the component's configuration
*/
protected ComponentConfiguration getConfiguration() {
@ -116,22 +116,46 @@ public class StrolchComponent {
/**
* Return the {@link ExecutorService} instantiated for this agent
*
*
* @return the {@link ExecutorService} instantiated for this agent
*/
protected ExecutorService getExecutorService() {
return this.container.getAgent().getExecutor();
}
/**
* Return the {@link ExecutorService} for the given poolName instantiated for this agent
*
* @param poolName
* the name of the pool
*
* @return the {@link ExecutorService} for the given poolName instantiated for this agent
*/
protected ExecutorService getExecutorService(String poolName) {
return this.container.getAgent().getExecutor(poolName);
}
/**
* Return the {@link ScheduledExecutorService} instantiated for this agent
*
*
* @return the {@link ScheduledExecutorService} instantiated for this agent
*/
protected ScheduledExecutorService getScheduledExecutor() {
return this.container.getAgent().getScheduledExecutor();
}
/**
* Return the {@link ScheduledExecutorService} for the given poolName instantiated for this agent
*
* @param poolName
* the name of the pool
*
* @return the {@link ScheduledExecutorService} instantiated for this agent
*/
protected ScheduledExecutorService getScheduledExecutor(String poolName) {
return this.container.getAgent().getScheduledExecutor(poolName);
}
/**
* Can be used by sub classes to assert that the component is started and thus ready to use, before any component
* methods are used
@ -156,8 +180,9 @@ public class StrolchComponent {
/**
* Life cycle step setup. This is a very early step in the container's startup phase.
*
*
* @param configuration
* the configuration
*/
public void setup(ComponentConfiguration configuration) {
this.state = this.state.validateStateChange(ComponentState.SETUP, getName());
@ -165,9 +190,12 @@ public class StrolchComponent {
/**
* Life cycle step initialize. Here you would typically read configuration values
*
*
* @param configuration
* the configuration
*
* @throws Exception
* if something goes wrong
*/
public void initialize(ComponentConfiguration configuration) throws Exception {
this.configuration = configuration;
@ -177,8 +205,9 @@ public class StrolchComponent {
/**
* Life cycle step start. This is the last step of startup and is where threads and connections etc. would be
* prepared. Can also be called after stop, to restart the component.
*
*
* @throws Exception
* if something goes wrong
*/
public void start() throws Exception {
this.state = this.state.validateStateChange(ComponentState.STARTED, getName());
@ -187,8 +216,9 @@ public class StrolchComponent {
/**
* Life cycle step stop. This is the first step in the tearing down of the container. Stop all active threads and
* connections here. After stop is called, another start might also be called to restart the component.
*
*
* @throws Exception
* if something goes wrong
*/
public void stop() throws Exception {
this.state = this.state.validateStateChange(ComponentState.STOPPED, getName());
@ -197,8 +227,9 @@ public class StrolchComponent {
/**
* Life cycle step destroy. This is the last step in the tearing down of the container. Here you would release
* remaining resources and the component can not be started anymore afterwards
*
*
* @throws Exception
* if something goes wrong
*/
public void destroy() throws Exception {
this.state = this.state.validateStateChange(ComponentState.DESTROYED, getName());
@ -207,13 +238,14 @@ public class StrolchComponent {
/**
* Returns the reference to the {@link StrolchComponent} with the given name, if it exists. If it does not exist, an
* {@link IllegalArgumentException} is thrown
*
*
* @param clazz
*
* the type of component to return
*
* @return the component with the given name
*
*
* @throws IllegalArgumentException
* if the component does not exist
* if the component does not exist
*/
protected <V> V getComponent(Class<V> clazz) {
return this.container.getComponent(clazz);
@ -221,13 +253,14 @@ public class StrolchComponent {
/**
* Performs the given {@link PrivilegedRunnable} as the given system user
*
*
* @param username
* the name of the system user to perform the action as
* the name of the system user to perform the action as
* @param action
* the action to perform
*
* the action to perform
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
*/
protected void runAs(String username, SystemAction action) throws PrivilegeException {
this.container.getPrivilegeHandler().runAs(username, action);
@ -235,15 +268,16 @@ public class StrolchComponent {
/**
* Performs the given {@link PrivilegedRunnable} as the given system user
*
*
* @param username
* the name of the system user to perform the action as
* the name of the system user to perform the action as
* @param action
* the action to perform
*
* the action to perform
*
* @return the result
*
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
*/
protected <T> T runWithResult(String username, SystemActionWithResult<T> action) throws PrivilegeException {
return this.container.getPrivilegeHandler().runWithResult(username, action);
@ -251,13 +285,14 @@ public class StrolchComponent {
/**
* Performs the given {@link PrivilegedRunnable} as the given system user
*
*
* @param username
* the name of the system user to perform the action as
* the name of the system user to perform the action as
* @param runnable
* the runnable to perform
*
* the runnable to perform
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
*/
protected void runAs(String username, PrivilegedRunnable runnable) throws PrivilegeException {
this.container.getPrivilegeHandler().runAs(username, runnable);
@ -265,15 +300,16 @@ public class StrolchComponent {
/**
* Performs the given {@link PrivilegedRunnable} as the given system user
*
*
* @param username
* the name of the system user to perform the action as
* the name of the system user to perform the action as
* @param runnable
* the runnable to perform
*
* the runnable to perform
*
* @return the result
*
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
*/
protected <T> T runWithResult(String username, PrivilegedRunnableWithResult<T> runnable) throws PrivilegeException {
return this.container.getPrivilegeHandler().runWithResult(username, runnable);
@ -281,13 +317,12 @@ public class StrolchComponent {
/**
* Performs the given {@link PrivilegedRunnable} as the given system user
*
* @param username
* the name of the system user to perform the action as
*
* @param action
* the action to perform
*
* the action to perform
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
*/
protected void runAsAgent(SystemAction action) throws PrivilegeException {
this.container.getPrivilegeHandler().runAsAgent(action);
@ -295,15 +330,14 @@ public class StrolchComponent {
/**
* Performs the given {@link PrivilegedRunnable} as the given system user
*
* @param username
* the name of the system user to perform the action as
*
* @param action
* the action to perform
*
* the action to perform
*
* @return the result
*
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
*/
protected <T> T runAsAgentWithResult(SystemActionWithResult<T> action) throws PrivilegeException {
return this.container.getPrivilegeHandler().runAsAgentWithResult(action);
@ -312,11 +346,12 @@ public class StrolchComponent {
/**
* Performs the given {@link PrivilegedRunnable} as the privileged system user
* {@link StrolchConstants#SYSTEM_USER_AGENT}
*
*
* @param runnable
* the runnable to perform
*
* the runnable to perform
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
*/
protected void runAsAgent(PrivilegedRunnable runnable) throws PrivilegeException {
this.container.getPrivilegeHandler().runAsAgent(runnable);
@ -325,13 +360,14 @@ public class StrolchComponent {
/**
* Performs the given {@link PrivilegedRunnable} as the privileged system user
* {@link StrolchConstants#SYSTEM_USER_AGENT}
*
*
* @param runnable
* the runnable to perform
*
* the runnable to perform
*
* @return the result
*
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
*/
protected <T> T runAsAgentWithResult(PrivilegedRunnableWithResult<T> runnable) throws PrivilegeException {
return this.container.getPrivilegeHandler().runAsAgentWithResult(runnable);
@ -339,10 +375,10 @@ public class StrolchComponent {
/**
* Opens a {@link StrolchTransaction} for the default realm and certificate
*
*
* @param cert
* the certificate authorizing the transaction
*
* the certificate authorizing the transaction
*
* @return the newly created transaction
*/
protected StrolchTransaction openTx(Certificate cert) {
@ -351,12 +387,12 @@ public class StrolchComponent {
/**
* Opens a {@link StrolchTransaction} for the given realm and certificate
*
*
* @param realm
* the name of the realm in which to open the transaction
* the name of the realm in which to open the transaction
* @param cert
* the certificate authorizing the transaction
*
* the certificate authorizing the transaction
*
* @return the newly created transaction
*/
protected StrolchTransaction openTx(String realm, Certificate cert) {
@ -365,14 +401,14 @@ public class StrolchComponent {
/**
* Opens a {@link StrolchTransaction} for the given realm and certificate
*
*
* @param realm
* the name of the realm in which to open the transaction
* the name of the realm in which to open the transaction
* @param cert
* the certificate authorizing the transaction
* the certificate authorizing the transaction
* @param clazz
* the clazz describing the transaction context
*
* the clazz describing the transaction context
*
* @return the newly created transaction
*/
protected StrolchTransaction openTx(String realm, Certificate cert, Class<?> clazz) {
@ -382,9 +418,11 @@ public class StrolchComponent {
/**
* Returns the version of this component. The version should be stored in the file
* {@link #COMPONENT_VERSION_PROPERTIES}. See {@link ComponentVersion} for more information
*
*
* @return the component's version.
*
* @throws IOException
* if the properties file containing the version could not be read
*/
public ComponentVersion getVersion() throws IOException {
if (this.version == null) {
@ -395,8 +433,7 @@ public class StrolchComponent {
Properties properties = new Properties();
properties.load(stream);
ComponentVersion componentVersion = new ComponentVersion(getName(), properties);
this.version = componentVersion;
this.version = new ComponentVersion(getName(), properties);
}
}

View File

@ -52,9 +52,9 @@ public class AuditingActivityMap extends AuditingElementMapFacade<Activity> impl
@Override
public <U> List<U> doQuery(StrolchTransaction tx, ActivityQuery<U> query) {
ActivityVisitor<U> activityVisitor = query.getActivityVisitor();
ActivityVisitor<U> activityVisitor = query.getVisitor();
DBC.PRE.assertNotNull("activityVisitor on query", activityVisitor);
query.setActivityVisitor(activity -> {
query.setVisitor(activity -> {
this.read.add(activity);
return activity.accept(activityVisitor);
});

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -34,12 +34,12 @@ import li.strolch.utils.dbc.DBC;
* This {@link AuditTrail} facade registers all actions performed i.e. it registers which {@link Audit Audits} are
* retrieved, created, updated and deleted.
* </p>
*
*
* <p>
* In a single transaction an Audit may be created, updated and then deleted - this implementation does not "squash"
* such actions, but registers them separately
* </p>
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class AuditingAuditMapFacade implements AuditTrail {
@ -163,17 +163,15 @@ public class AuditingAuditMapFacade implements AuditTrail {
}
@Override
public Audit update(StrolchTransaction tx, Audit audit) {
Audit replaced = this.auditTrail.update(tx, audit);
public void update(StrolchTransaction tx, Audit audit) {
this.auditTrail.update(tx, audit);
this.updated.add(audit);
return replaced;
}
@Override
public List<Audit> updateAll(StrolchTransaction tx, List<Audit> audits) {
List<Audit> replaced = this.auditTrail.updateAll(tx, audits);
public void updateAll(StrolchTransaction tx, List<Audit> audits) {
this.auditTrail.updateAll(tx, audits);
this.updated.addAll(audits);
return replaced;
}
@Override
@ -198,13 +196,14 @@ public class AuditingAuditMapFacade implements AuditTrail {
byType = byType + removed;
this.deletedAllByType.put(type, byType);
this.deletedAll += removed;
return removed;
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, AuditQuery<U> query) {
AuditVisitor<U> auditVisitor = query.getAuditVisitor();
query.setAuditVisitor(audit -> {
AuditVisitor<U> auditVisitor = query.getVisitor();
query.setVisitor(audit -> {
this.read.add(audit);
return auditVisitor.visitAudit(audit);
});

View File

@ -52,9 +52,9 @@ public class AuditingOrderMap extends AuditingElementMapFacade<Order> implements
@Override
public <U> List<U> doQuery(StrolchTransaction tx, OrderQuery<U> query) {
OrderVisitor<U> orderVisitor = query.getOrderVisitor();
OrderVisitor<U> orderVisitor = query.getVisitor();
DBC.PRE.assertNotNull("orderVisitor on query", orderVisitor);
query.setOrderVisitor(order -> {
query.setVisitor(order -> {
this.read.add(order);
return order.accept(orderVisitor);
});

View File

@ -23,7 +23,7 @@ import li.strolch.agent.api.ResourceMap;
import li.strolch.model.Resource;
import li.strolch.model.Tags;
import li.strolch.model.query.ResourceQuery;
import li.strolch.model.visitor.StrolchElementVisitor;
import li.strolch.model.visitor.ResourceVisitor;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.utils.dbc.DBC;
@ -52,9 +52,9 @@ public class AuditingResourceMap extends AuditingElementMapFacade<Resource> impl
@Override
public <U> List<U> doQuery(StrolchTransaction tx, ResourceQuery<U> query) {
StrolchElementVisitor<U> resourceVisitor = query.getResourceVisitor();
ResourceVisitor<U> resourceVisitor = query.getVisitor();
DBC.PRE.assertNotNull("resourceVisitor on query", resourceVisitor);
query.setResourceVisitor(resource -> {
query.setVisitor(resource -> {
this.read.add(resource);
return resource.accept(resourceVisitor);
});

View File

@ -1,12 +1,12 @@
/*
* Copyright 2015 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -26,16 +26,13 @@ import li.strolch.model.parameter.Parameter;
import li.strolch.model.query.ActivityQuery;
import li.strolch.persistence.api.ActivityDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.persistence.inmemory.InMemoryActivityDao;
import li.strolch.runtime.query.inmemory.InMemoryActivityQueryVisitor;
import li.strolch.runtime.query.inmemory.InMemoryQuery;
public class CachedActivityMap extends CachedElementMap<Activity> implements ActivityMap {
private ActivityDao cachedDao;
public CachedActivityMap(StrolchRealm realm) {
super(realm);
// the cached DAO should not have versioning enabled
this.cachedDao = new InMemoryActivityDao(false);
}
@Override
@ -49,12 +46,9 @@ public class CachedActivityMap extends CachedElementMap<Activity> implements Act
}
@Override
public ActivityDao getCachedDao() {
return this.cachedDao;
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, ActivityQuery<U> query) {
return getCachedDao().doQuery(query);
public <U> List<U> doQuery(StrolchTransaction tx, ActivityQuery<U> activityQuery) {
InMemoryActivityQueryVisitor visitor = new InMemoryActivityQueryVisitor();
InMemoryQuery<Activity, U> query = visitor.visit(activityQuery);
return query.doQuery(tx, this);
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,79 +17,30 @@ package li.strolch.agent.impl;
import java.text.MessageFormat;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import li.strolch.agent.api.AuditTrail;
import li.strolch.model.audit.Audit;
import li.strolch.model.audit.AuditQuery;
import li.strolch.persistence.api.AuditDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.persistence.inmemory.InMemoryAuditDao;
import li.strolch.utils.collections.DateRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class CachedAuditTrail implements AuditTrail {
public class CachedAuditTrail extends TransientAuditTrail {
private static final Logger logger = LoggerFactory.getLogger(CachedAuditTrail.class);
private AuditDao cachedDao;
public CachedAuditTrail() {
this.cachedDao = new InMemoryAuditDao();
}
@Override
public boolean isEnabled() {
return true;
}
protected AuditDao getCachedDao() {
return this.cachedDao;
}
protected AuditDao getDbDao(StrolchTransaction tx) {
private AuditDao getDbDao(StrolchTransaction tx) {
return tx.getPersistenceHandler().getAuditDao(tx);
}
@Override
public synchronized boolean hasAudit(StrolchTransaction tx, String type, Long id) {
return getCachedDao().hasElement(type, id);
}
@Override
public long querySize(StrolchTransaction tx, DateRange dateRange) {
return getCachedDao().querySize(dateRange);
}
@Override
public synchronized long querySize(StrolchTransaction tx, String type, DateRange dateRange) {
return getCachedDao().querySize(type, dateRange);
}
@Override
public synchronized Set<String> getTypes(StrolchTransaction tx) {
return getCachedDao().queryTypes();
}
@Override
public synchronized Audit getBy(StrolchTransaction tx, String type, Long id) {
return getCachedDao().queryBy(type, id);
}
@Override
public synchronized List<Audit> getAllElements(StrolchTransaction tx, String type, DateRange dateRange) {
return getCachedDao().queryAll(type, dateRange);
}
@Override
public synchronized void add(StrolchTransaction tx, Audit audit) {
// first perform cached change
getCachedDao().save(audit);
super.add(tx, audit);
// last is to perform DB changes
getDbDao(tx).save(audit);
}
@ -97,35 +48,31 @@ public class CachedAuditTrail implements AuditTrail {
@Override
public synchronized void addAll(StrolchTransaction tx, List<Audit> audits) {
// first perform cached change
getCachedDao().saveAll(audits);
super.addAll(tx, audits);
// last is to perform DB changes
getDbDao(tx).saveAll(audits);
}
// TODO for update we should return the updated elements, or remove the return value
@Override
public synchronized Audit update(StrolchTransaction tx, Audit audit) {
public synchronized void update(StrolchTransaction tx, Audit audit) {
// first perform cached change
getCachedDao().update(audit);
super.update(tx, audit);
// last is to perform DB changes
getDbDao(tx).update(audit);
return audit;
}
@Override
public synchronized List<Audit> updateAll(StrolchTransaction tx, List<Audit> audits) {
public synchronized void updateAll(StrolchTransaction tx, List<Audit> audits) {
// first perform cached change
getCachedDao().updateAll(audits);
super.updateAll(tx, audits);
// last is to perform DB changes
getDbDao(tx).updateAll(audits);
return audits;
}
@Override
public synchronized void remove(StrolchTransaction tx, Audit audit) {
// first perform cached change
getCachedDao().remove(audit);
super.remove(tx, audit);
// last is to perform DB changes
getDbDao(tx).remove(audit);
}
@ -133,15 +80,16 @@ public class CachedAuditTrail implements AuditTrail {
@Override
public synchronized void removeAll(StrolchTransaction tx, List<Audit> audits) {
// first perform cached change
getCachedDao().removeAll(audits);
super.removeAll(tx, audits);
// last is to perform DB changes
getDbDao(tx).removeAll(audits);
}
@Override
public synchronized long removeAll(StrolchTransaction tx, String type, DateRange dateRange) {
// first perform cached change
long removed = getCachedDao().removeAll(type, dateRange);
long removed = super.removeAll(tx, type, dateRange);
// last is to perform DB changes
long daoRemoved = getDbDao(tx).removeAll(type, dateRange);

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,112 +17,160 @@ package li.strolch.agent.impl;
import java.text.MessageFormat;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import li.strolch.agent.api.ElementMap;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.agent.api.StrolchRealm;
import li.strolch.exception.StrolchException;
import li.strolch.model.StrolchRootElement;
import li.strolch.model.Version;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.parameter.StringListParameter;
import li.strolch.model.parameter.StringParameter;
import li.strolch.persistence.api.StrolchDao;
import li.strolch.persistence.api.StrolchPersistenceException;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.runtime.StrolchConstants;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public abstract class CachedElementMap<T extends StrolchRootElement> implements ElementMap<T> {
private static final Logger logger = LoggerFactory.getLogger(CachedElementMap.class);
public abstract class CachedElementMap<T extends StrolchRootElement> extends TransientElementMap<T> {
private StrolchRealm realm;
public CachedElementMap(StrolchRealm realm) {
super();
this.realm = realm;
}
protected StrolchRealm getRealm() {
return this.realm;
}
protected abstract StrolchDao<T> getCachedDao();
protected abstract StrolchDao<T> getDbDao(StrolchTransaction tx);
@Override
public synchronized boolean hasType(StrolchTransaction tx, String type) {
return getCachedDao().queryTypes().contains(type);
}
@Override
public synchronized boolean hasElement(StrolchTransaction tx, String type, String id) {
return getCachedDao().hasElement(type, id);
}
@Override
public synchronized long querySize(StrolchTransaction tx) {
return getCachedDao().querySize();
}
@Override
public synchronized long querySize(StrolchTransaction tx, String type) {
return getCachedDao().querySize(type);
}
@Override
public synchronized T getTemplate(StrolchTransaction tx, String type) {
return getTemplate(tx, type, false);
}
@Override
public T getTemplate(StrolchTransaction tx, String type, boolean assertExists) {
T t = getCachedDao().queryBy(StrolchConstants.TEMPLATE, type);
if (assertExists && t == null) {
String msg = "The template with type {0} does not exist!"; //$NON-NLS-1$
throw new StrolchException(MessageFormat.format(msg, type));
public synchronized void add(StrolchTransaction tx, T element) {
if (this.realm.isVersioningEnabled()) {
int latestVersion = getLatestVersionFor(tx, element.getType(), element.getId());
Version.setInitialVersionFor(element, latestVersion, tx.getCertificate().getUsername());
} else {
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
}
if (t == null)
return null;
// first perform cached change
super.add(tx, element);
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setId(StrolchAgent.getUniqueId());
clone.setType(type);
return clone;
// last is to perform DB changes
getDbDao(tx).save(element);
}
@Override
public synchronized T getBy(StrolchTransaction tx, String type, String id) {
return getBy(tx, type, id, false);
}
@Override
public T getBy(StrolchTransaction tx, String type, String id, boolean assertExists) throws StrolchException {
T t = getCachedDao().queryBy(type, id);
if (assertExists && t == null) {
String msg = "The element with type {0} and id {1} does not exist!"; //$NON-NLS-1$
throw new StrolchException(MessageFormat.format(msg, type, id));
public synchronized void addAll(StrolchTransaction tx, List<T> elements) {
for (T element : elements) {
if (this.realm.isVersioningEnabled()) {
int latestVersion = getLatestVersionFor(tx, element.getType(), element.getId());
Version.setInitialVersionFor(element, latestVersion, tx.getCertificate().getUsername());
} else {
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
}
}
if (t == null)
return null;
// first perform cached change
super.addAll(tx, elements);
// TODO cloning has its issues, as queries don't return a clone!
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setVersion(t.getVersion());
return clone;
// last is to perform DB changes
getDbDao(tx).saveAll(elements);
}
private void updateVersion(StrolchTransaction tx, T element, boolean deleted) {
if (this.realm.isVersioningEnabled()) {
Version.updateVersionFor(element, tx.getCertificate().getUsername(), deleted);
} else {
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
}
}
@Override
public synchronized void update(StrolchTransaction tx, T element) {
updateVersion(tx, element, false);
// first perform cached change
super.update(tx, element);
// last is to perform DB changes
getDbDao(tx).update(element);
}
@Override
public synchronized void updateAll(StrolchTransaction tx, List<T> elements) {
for (T t : elements) {
updateVersion(tx, t, false);
}
// first perform cached change
super.updateAll(tx, elements);
// last is to perform DB changes
getDbDao(tx).updateAll(elements);
}
@Override
public synchronized void remove(StrolchTransaction tx, T element) {
updateVersion(tx, element, true);
// first perform cached change
super.remove(tx, element);
// last is to perform DB changes
if (this.realm.isVersioningEnabled()) {
getDbDao(tx).update(element);
} else {
getDbDao(tx).remove(element);
}
}
@Override
public synchronized void removeAll(StrolchTransaction tx, List<T> elements) {
for (T t : elements) {
updateVersion(tx, t, true);
}
// first perform cached change
super.removeAll(tx, elements);
// last is to perform DB changes
if (this.realm.isVersioningEnabled()) {
getDbDao(tx).updateAll(elements);
} else {
getDbDao(tx).removeAll(elements);
}
}
@Override
public synchronized long removeAll(StrolchTransaction tx) {
// first perform cached change
long removed = super.removeAll(tx);
// last is to perform DB changes
long daoRemoved = getDbDao(tx).removeAll();
if (removed != daoRemoved) {
String msg = "Removed {0} elements from cached map, but dao removed {1} elements!"; //$NON-NLS-1$
logger.error(MessageFormat.format(msg, removed, daoRemoved));
}
return removed;
}
@Override
public synchronized long removeAllBy(StrolchTransaction tx, String type) {
// first perform cached change
long removed = super.removeAllBy(tx, type);
// last is to perform DB changes
long daoRemoved = getDbDao(tx).removeAllBy(type);
if (removed != daoRemoved) {
String msg = "Removed {0} elements from cached map for type {1}, but dao removed {3} elements!"; //$NON-NLS-1$
logger.error(MessageFormat.format(msg, removed, type, daoRemoved));
}
return removed;
}
@Override
@ -139,34 +187,10 @@ public abstract class CachedElementMap<T extends StrolchRootElement> implements
msg = MessageFormat.format(msg, type, id, version);
throw new StrolchException(msg);
}
return t;
}
@Override
public T getBy(StrolchTransaction tx, StringParameter refP, boolean assertExists) throws StrolchException {
assertIsRefParam(refP);
String type = refP.getUom();
String id = refP.getValue();
T t = getBy(tx, type, id, false);
if (assertExists && t == null) {
String msg = "The element with type {0} and id {1} does not exist for param {2}"; //$NON-NLS-1$
throw new StrolchException(MessageFormat.format(msg, type, id, refP.getLocator()));
}
return t;
}
@Override
public List<T> getBy(StrolchTransaction tx, StringListParameter refP, boolean assertExists)
throws StrolchException {
assertIsRefParam(refP);
String type = refP.getUom();
List<String> ids = refP.getValue();
return ids.stream().map(id -> getBy(tx, type, id, assertExists)).filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public List<T> getVersionsFor(StrolchTransaction tx, String type, String id) {
return getDbDao(tx).queryVersionsFor(type, id);
@ -177,191 +201,6 @@ public abstract class CachedElementMap<T extends StrolchRootElement> implements
return getDbDao(tx).queryLatestVersionFor(type, id);
}
@Override
public synchronized List<T> getAllElements(StrolchTransaction tx) {
List<T> all = getCachedDao().queryAll();
return all.stream().map(t -> {
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setVersion(t.getVersion());
return clone;
}).collect(Collectors.toList());
}
@Override
public synchronized List<T> getElementsBy(StrolchTransaction tx, String type) {
List<T> all = getCachedDao().queryAll(type);
return all.stream().map(t -> {
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setVersion(t.getVersion());
return clone;
}).collect(Collectors.toList());
}
@Override
public synchronized Set<String> getTypes(StrolchTransaction tx) {
return getCachedDao().queryTypes();
}
@Override
public synchronized Set<String> getAllKeys(StrolchTransaction tx) {
return getCachedDao().queryKeySet();
}
@Override
public synchronized Set<String> getKeysBy(StrolchTransaction tx, String type) {
return getCachedDao().queryKeySet(type);
}
/**
* Special method used when starting the container to cache the values. Not to be used anywhere else but from the
* {@link CachedRealm}
*
* @param element
*/
synchronized void insert(T element) {
getCachedDao().save(element);
}
@Override
public synchronized void add(StrolchTransaction tx, T element) {
if (realm.isVersioningEnabled()) {
int latestVersion = getLatestVersionFor(tx, element.getType(), element.getId());
Version.setInitialVersionFor(element, latestVersion, tx.getCertificate().getUsername());
} else {
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
}
// first perform cached change
getCachedDao().save(element);
// last is to perform DB changes
getDbDao(tx).save(element);
}
@Override
public synchronized void addAll(StrolchTransaction tx, List<T> elements) {
for (T element : elements) {
if (realm.isVersioningEnabled()) {
int latestVersion = getLatestVersionFor(tx, element.getType(), element.getId());
Version.setInitialVersionFor(element, latestVersion, tx.getCertificate().getUsername());
} else {
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
}
}
// first perform cached change
getCachedDao().saveAll(elements);
// last is to perform DB changes
getDbDao(tx).saveAll(elements);
}
@Override
public synchronized void update(StrolchTransaction tx, T element) {
if (realm.isVersioningEnabled())
Version.updateVersionFor(element, tx.getCertificate().getUsername(), false);
else
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
// first perform cached change
getCachedDao().update(element);
// last is to perform DB changes
getDbDao(tx).update(element);
}
@Override
public synchronized void updateAll(StrolchTransaction tx, List<T> elements) {
for (T t : elements) {
if (realm.isVersioningEnabled())
Version.updateVersionFor(t, tx.getCertificate().getUsername(), false);
else
Version.setInitialVersionFor(t, -1, tx.getCertificate().getUsername());
}
// first perform cached change
getCachedDao().updateAll(elements);
// last is to perform DB changes
getDbDao(tx).updateAll(elements);
}
@Override
public synchronized void remove(StrolchTransaction tx, T element) {
if (realm.isVersioningEnabled())
Version.updateVersionFor(element, tx.getCertificate().getUsername(), true);
else
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
if (this.realm.isVersioningEnabled()) {
// first perform cached change
getCachedDao().remove(element);
// last is to perform DB changes
getDbDao(tx).update(element);
} else {
// first perform cached change
getCachedDao().remove(element);
// last is to perform DB changes
getDbDao(tx).remove(element);
}
}
@Override
public synchronized void removeAll(StrolchTransaction tx, List<T> elements) {
for (T t : elements) {
if (realm.isVersioningEnabled())
Version.updateVersionFor(t, tx.getCertificate().getUsername(), true);
else
Version.setInitialVersionFor(t, -1, tx.getCertificate().getUsername());
}
if (this.realm.isVersioningEnabled()) {
// first perform cached change
getCachedDao().removeAll(elements);
// last is to perform DB changes
getDbDao(tx).updateAll(elements);
} else {
// first perform cached change
getCachedDao().removeAll(elements);
// last is to perform DB changes
getDbDao(tx).removeAll(elements);
}
}
@Override
public synchronized long removeAll(StrolchTransaction tx) {
// first perform cached change
long removed = getCachedDao().removeAll();
// last is to perform DB changes
long daoRemoved = getDbDao(tx).removeAll();
if (removed != daoRemoved) {
String msg = "Removed {0} elements from cached map, but dao removed {1} elements!"; //$NON-NLS-1$
logger.error(MessageFormat.format(msg, removed, daoRemoved));
}
return removed;
}
@Override
public synchronized long removeAllBy(StrolchTransaction tx, String type) {
// first perform cached change
long removed = getCachedDao().removeAllBy(type);
// last is to perform DB changes
long daoRemoved = getDbDao(tx).removeAllBy(type);
if (removed != daoRemoved) {
String msg = "Removed {0} elements from cached map for type {1}, but dao removed {3} elements!"; //$NON-NLS-1$
logger.error(MessageFormat.format(msg, removed, type, daoRemoved));
}
return removed;
}
@Override
public T revertToVersion(StrolchTransaction tx, T element) throws StrolchException {
return revertToVersion(tx, element.getType(), element.getId(), element.getVersion().getVersion());
@ -369,9 +208,8 @@ public abstract class CachedElementMap<T extends StrolchRootElement> implements
@Override
public T revertToVersion(StrolchTransaction tx, String type, String id, int version) throws StrolchException {
if (!this.realm.isVersioningEnabled()) {
throw new StrolchPersistenceException("Can not und a version if versioning is not enabled!");
}
if (!this.realm.isVersioningEnabled())
throw new StrolchPersistenceException("Can not undo a version if versioning is not enabled!");
// get the current and specified version
T current = getBy(tx, type, id, true);
@ -380,11 +218,10 @@ public abstract class CachedElementMap<T extends StrolchRootElement> implements
// create the new version
@SuppressWarnings("unchecked")
T clone = (T) versionT.getClone();
clone.setVersion(current.getVersion().next(tx.getCertificate().getUsername(), false));
clone.setVersion(current.getVersion());
// save the new version
getCachedDao().update(clone);
getDbDao(tx).update(clone);
update(tx, clone);
// and return new version
return clone;
@ -392,9 +229,8 @@ public abstract class CachedElementMap<T extends StrolchRootElement> implements
@Override
public void undoVersion(StrolchTransaction tx, T element) throws StrolchException {
if (!this.realm.isVersioningEnabled()) {
throw new StrolchPersistenceException("Can not und a version if versioning is not enabled!");
}
if (!this.realm.isVersioningEnabled())
throw new StrolchPersistenceException("Can not undo a version if versioning is not enabled!");
String type = element.getType();
String id = element.getId();
@ -410,11 +246,11 @@ public abstract class CachedElementMap<T extends StrolchRootElement> implements
}
if (elementVersion.isFirstVersion()) {
getCachedDao().remove(element);
super.remove(tx, element);
getDbDao(tx).remove(element);
} else {
T previous = getBy(tx, type, id, elementVersion.getPreviousVersion(), true);
getCachedDao().update(previous);
super.update(tx, previous);
getDbDao(tx).removeVersion(current);
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -26,16 +26,13 @@ import li.strolch.model.parameter.Parameter;
import li.strolch.model.query.OrderQuery;
import li.strolch.persistence.api.OrderDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.persistence.inmemory.InMemoryOrderDao;
import li.strolch.runtime.query.inmemory.InMemoryOrderQueryVisitor;
import li.strolch.runtime.query.inmemory.InMemoryQuery;
public class CachedOrderMap extends CachedElementMap<Order> implements OrderMap {
private OrderDao cachedDao;
public CachedOrderMap(StrolchRealm realm) {
super(realm);
// the cached DAO should not have versioning enabled
this.cachedDao = new InMemoryOrderDao(false);
}
@Override
@ -49,12 +46,9 @@ public class CachedOrderMap extends CachedElementMap<Order> implements OrderMap
}
@Override
protected OrderDao getCachedDao() {
return this.cachedDao;
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, OrderQuery<U> query) {
return getCachedDao().doQuery(query);
public <U> List<U> doQuery(StrolchTransaction tx, OrderQuery<U> orderQuery) {
InMemoryOrderQueryVisitor visitor = new InMemoryOrderQueryVisitor();
InMemoryQuery<Order, U> query = visitor.visit(orderQuery);
return query.doQuery(tx, this);
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -102,7 +102,7 @@ public class CachedRealm extends InternalStrolchRealm {
if (isAuditTrailEnabled())
this.auditTrail = new CachedAuditTrail();
else
this.auditTrail = new NoStrategyAuditTrail();
this.auditTrail = new NoStrategyAuditTrail(getRealm());
}
@Override
@ -118,8 +118,10 @@ public class CachedRealm extends InternalStrolchRealm {
try (StrolchTransaction tx = openTx(privilegeContext.getCertificate(), "strolch_boot")) {
ResourceDao resourceDao = tx.getPersistenceHandler().getResourceDao(tx);
logger.info("Reading " + resourceDao.querySize() + " Resources from DB...");
Set<String> resourceTypes = resourceDao.queryTypes();
for (String type : resourceTypes) {
logger.info("Reading " + resourceDao.querySize(type) + " Resources of type " + type + " from DB...");
List<Resource> resources = resourceDao.queryAll(type);
for (Resource resource : resources) {
this.resourceMap.insert(resource);
@ -132,8 +134,10 @@ public class CachedRealm extends InternalStrolchRealm {
try (StrolchTransaction tx = openTx(privilegeContext.getCertificate(), "strolch_boot")) {
OrderDao orderDao = tx.getPersistenceHandler().getOrderDao(tx);
logger.info("Reading " + orderDao.querySize() + " Orders from DB...");
Set<String> orderTypes = orderDao.queryTypes();
for (String type : orderTypes) {
logger.info("Reading " + orderDao.querySize(type) + " Orders of type " + type + " from DB...");
List<Order> orders = orderDao.queryAll(type);
for (Order order : orders) {
this.orderMap.insert(order);
@ -146,8 +150,10 @@ public class CachedRealm extends InternalStrolchRealm {
try (StrolchTransaction tx = openTx(privilegeContext.getCertificate(), "strolch_boot")) {
ActivityDao activityDao = tx.getPersistenceHandler().getActivityDao(tx);
logger.info("Reading " + activityDao.querySize() + " Activities from DB...");
Set<String> activityTypes = activityDao.queryTypes();
for (String type : activityTypes) {
logger.info("Reading " + activityDao.querySize(type) + " Activities of type " + type + " from DB...");
List<Activity> activities = activityDao.queryAll(type);
for (Activity activity : activities) {
this.activityMap.insert(activity);
@ -160,7 +166,8 @@ public class CachedRealm extends InternalStrolchRealm {
long duration = System.nanoTime() - start;
String durationS = StringHelper.formatNanoDuration(duration);
logger.info(MessageFormat.format("Loading Model from Database for realm {0} took {1}.", getRealm(), durationS)); //$NON-NLS-1$
logger.info(MessageFormat
.format("Loading Model from Database for realm {0} took {1}.", getRealm(), durationS)); //$NON-NLS-1$
logger.info(MessageFormat.format("Loaded {0} Orders", nrOfOrders)); //$NON-NLS-1$
logger.info(MessageFormat.format("Loaded {0} Resources", nrOfResources)); //$NON-NLS-1$
logger.info(MessageFormat.format("Loaded {0} Activities", nrOfActivities)); //$NON-NLS-1$

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -26,16 +26,13 @@ import li.strolch.model.parameter.Parameter;
import li.strolch.model.query.ResourceQuery;
import li.strolch.persistence.api.ResourceDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.persistence.inmemory.InMemoryResourceDao;
import li.strolch.runtime.query.inmemory.InMemoryQuery;
import li.strolch.runtime.query.inmemory.InMemoryResourceQueryVisitor;
public class CachedResourceMap extends CachedElementMap<Resource> implements ResourceMap {
private ResourceDao cachedDao;
public CachedResourceMap(StrolchRealm realm) {
super(realm);
// the cached DAO should not have versioning enabled
this.cachedDao = new InMemoryResourceDao(false);
}
@Override
@ -49,12 +46,9 @@ public class CachedResourceMap extends CachedElementMap<Resource> implements Res
}
@Override
public ResourceDao getCachedDao() {
return this.cachedDao;
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, ResourceQuery<U> query) {
return getCachedDao().doQuery(query);
public <U> List<U> doQuery(StrolchTransaction tx, ResourceQuery<U> resourceQuery) {
InMemoryResourceQueryVisitor visitor = new InMemoryResourceQueryVisitor();
InMemoryQuery<Resource, U> query = visitor.visit(resourceQuery);
return query.doQuery(tx, this);
}
}

View File

@ -54,17 +54,6 @@ public enum DataStoreMode {
public InternalStrolchRealm createRealm(String realm) {
return new CachedRealm(realm);
}
}, //
TRANSACTIONAL {
@Override
public boolean isTransient() {
return false;
}
@Override
public InternalStrolchRealm createRealm(String realm) {
return new TransactionalRealm(realm);
}
}; //
public abstract InternalStrolchRealm createRealm(String realm);

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,68 +17,62 @@ package li.strolch.agent.impl;
import java.text.MessageFormat;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import li.strolch.agent.api.Observer;
import li.strolch.agent.api.ObserverEvent;
import li.strolch.agent.api.ObserverHandler;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.model.StrolchRootElement;
import li.strolch.runtime.ThreadPoolFactory;
import li.strolch.utils.collections.MapOfLists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple {@link ObserverHandler} which keeps a reference to all registered {@link Observer Observers} and notifies
* them when one of the notify methods are called
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class DefaultObserverHandler implements ObserverHandler {
private static final Logger logger = LoggerFactory.getLogger(DefaultObserverHandler.class);
private final StrolchAgent agent;
private MapOfLists<String, Observer> observerMap;
private Future<?> future;
private ExecutorService executorService;
public DefaultObserverHandler() {
public DefaultObserverHandler(StrolchAgent agent) {
this.agent = agent;
this.observerMap = new MapOfLists<>();
}
@Override
public void start() {
this.executorService = Executors.newSingleThreadExecutor(new ThreadPoolFactory("ObserverHandler"));
// nothing to do
}
@Override
public void stop() {
if (this.executorService != null) {
this.executorService.shutdown();
while (!this.executorService.isTerminated()) {
logger.info("Waiting for last update to complete...");
try {
Thread.sleep(50L);
} catch (InterruptedException e) {
logger.error("Interrupted!");
}
}
this.executorService = null;
if (this.future != null) {
this.future.cancel(false);
this.future = null;
}
}
private ScheduledExecutorService getExecutor() {
return this.agent.getScheduledExecutor("Observer");
}
@Override
public void notify(ObserverEvent event) {
if (event.added.isEmpty() && event.updated.isEmpty() && event.removed.isEmpty())
return;
this.executorService.execute(() -> {
doUpdates(event);
});
this.future = this.agent.getExecutor("Observer").submit(() -> doUpdates(event));
}
protected void doUpdates(ObserverEvent event) {

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,14 +17,8 @@ package li.strolch.agent.impl;
import java.text.MessageFormat;
import li.strolch.agent.api.ActivityMap;
import li.strolch.agent.api.AuditTrail;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.OrderMap;
import li.strolch.agent.api.ResourceMap;
import li.strolch.persistence.api.PersistenceHandler;
import li.strolch.agent.api.*;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.persistence.inmemory.InMemoryPersistence;
import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.PrivilegeContext;
import li.strolch.runtime.configuration.ComponentConfiguration;
@ -39,7 +33,6 @@ public class EmptyRealm extends InternalStrolchRealm {
private OrderMap orderMap;
private ActivityMap activityMap;
private AuditTrail auditTrail;
private PersistenceHandler persistenceHandler;
public EmptyRealm(String realm) {
super(realm);
@ -53,13 +46,13 @@ public class EmptyRealm extends InternalStrolchRealm {
@Override
public StrolchTransaction openTx(Certificate certificate, String action) {
DBC.PRE.assertNotNull("Certificate must be set!", certificate); //$NON-NLS-1$
return this.persistenceHandler.openTx(this, certificate, action);
return new TransientTransaction(this.container, this, certificate, action);
}
@Override
public StrolchTransaction openTx(Certificate certificate, Class<?> clazz) {
DBC.PRE.assertNotNull("Certificate must be set!", certificate); //$NON-NLS-1$
return this.persistenceHandler.openTx(this, certificate, clazz.getName());
return new TransientTransaction(this.container, this, certificate, clazz.getName());
}
@Override
@ -85,15 +78,14 @@ public class EmptyRealm extends InternalStrolchRealm {
@Override
public void initialize(ComponentContainer container, ComponentConfiguration configuration) {
super.initialize(container, configuration);
this.persistenceHandler = new InMemoryPersistence(container, isVersioningEnabled());
this.resourceMap = new TransactionalResourceMap(this);
this.orderMap = new TransactionalOrderMap(this);
this.activityMap = new TransactionalActivityMap(this);
this.resourceMap = new TransientResourceMap();
this.orderMap = new TransientOrderMap();
this.activityMap = new TransientActivityMap();
if (isAuditTrailEnabled())
this.auditTrail = new TransactionalAuditTrail();
this.auditTrail = new TransientAuditTrail();
else
this.auditTrail = new NoStrategyAuditTrail();
this.auditTrail = new NoStrategyAuditTrail(getRealm());
}
@Override

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,25 +17,23 @@ package li.strolch.agent.impl;
import java.text.MessageFormat;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import li.strolch.agent.api.Observer;
import li.strolch.agent.api.ObserverEvent;
import li.strolch.agent.api.ObserverHandler;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.model.StrolchRootElement;
import li.strolch.runtime.ThreadPoolFactory;
import li.strolch.utils.collections.MapOfLists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple {@link ObserverHandler} which keeps a reference to all registered {@link Observer Observers} and notifies
* them when one of the notify methods are called
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class EventCollectingObserverHandler implements ObserverHandler {
@ -44,18 +42,19 @@ public class EventCollectingObserverHandler implements ObserverHandler {
private MapOfLists<String, Observer> observerMap;
private ScheduledExecutorService executorService;
private ObserverEvent observerEvent;
private ScheduledFuture<?> future;
private StrolchAgent agent;
public EventCollectingObserverHandler() {
public EventCollectingObserverHandler(StrolchAgent agent) {
this.agent = agent;
this.observerMap = new MapOfLists<>();
}
@Override
public void start() {
this.executorService = Executors.newScheduledThreadPool(1, new ThreadPoolFactory("ObserverHandler"));
// nothing to do
}
@Override
@ -65,20 +64,10 @@ public class EventCollectingObserverHandler implements ObserverHandler {
this.future.cancel(false);
this.future = null;
}
}
if (this.executorService != null) {
this.executorService.shutdown();
while (!this.executorService.isTerminated()) {
logger.info("Waiting for last update to complete...");
try {
Thread.sleep(50L);
} catch (InterruptedException e) {
logger.error("Interrupted!");
}
}
this.executorService = null;
}
private ScheduledExecutorService getExecutor() {
return this.agent.getScheduledExecutor("Observer");
}
@Override
@ -97,7 +86,7 @@ public class EventCollectingObserverHandler implements ObserverHandler {
}
if (this.future == null || this.future.isDone()) {
this.future = this.executorService.scheduleAtFixedRate(() -> doUpdates(), 100, 100, TimeUnit.MILLISECONDS);
this.future = getExecutor().scheduleAtFixedRate(this::doUpdates, 100, 100, TimeUnit.MILLISECONDS);
}
}
@ -126,8 +115,7 @@ public class EventCollectingObserverHandler implements ObserverHandler {
synchronized (this) {
if (this.observerEvent != null) {
this.future = this.executorService.scheduleAtFixedRate(() -> doUpdates(), 100, 100,
TimeUnit.MILLISECONDS);
this.future = getExecutor().scheduleAtFixedRate(this::doUpdates, 100, 100, TimeUnit.MILLISECONDS);
}
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -56,6 +56,7 @@ public abstract class InternalStrolchRealm implements StrolchRealm {
private boolean versioningEnabled;
private boolean updateObservers;
private ObserverHandler observerHandler;
protected ComponentContainer container;
public InternalStrolchRealm(String realm) {
DBC.PRE.assertNotEmpty("RealmName may not be empty!", realm); //$NON-NLS-1$
@ -84,6 +85,7 @@ public abstract class InternalStrolchRealm implements StrolchRealm {
}
public void initialize(ComponentContainer container, ComponentConfiguration configuration) {
this.container = container;
logger.info("Initializing Realm " + getRealm() + "...");
@ -101,10 +103,10 @@ public abstract class InternalStrolchRealm implements StrolchRealm {
if (this.updateObservers) {
String delayedObserversKey = makeRealmKey(getRealm(), PROP_ENABLED_DELAYED_OBSERVER_UPDATES);
if (configuration.getBoolean(delayedObserversKey, Boolean.FALSE)) {
this.observerHandler = new DefaultObserverHandler();
} else {
this.observerHandler = new EventCollectingObserverHandler();
this.observerHandler = new EventCollectingObserverHandler(container.getAgent());
logger.info("Enabled Delayed Observer Updates.");
} else {
this.observerHandler = new DefaultObserverHandler(container.getAgent());
}
}
@ -136,7 +138,8 @@ public abstract class InternalStrolchRealm implements StrolchRealm {
else
logger.info("Versioning not enabled for realm " + getRealm()); //$NON-NLS-1$
logger.info(MessageFormat.format("Using a locking try timeout of {0}s", timeUnit.toSeconds(time))); //$NON-NLS-1$
logger.info(
MessageFormat.format("Using a locking try timeout of {0}s", timeUnit.toSeconds(time))); //$NON-NLS-1$
}
@Override

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -29,6 +29,12 @@ import li.strolch.utils.collections.DateRange;
*/
public class NoStrategyAuditTrail implements AuditTrail {
private String realm;
public NoStrategyAuditTrail(String realm) {
this.realm = realm;
}
@Override
public boolean isEnabled() {
return false;
@ -75,13 +81,13 @@ public class NoStrategyAuditTrail implements AuditTrail {
}
@Override
public Audit update(StrolchTransaction tx, Audit audit) {
return null;
public void update(StrolchTransaction tx, Audit audit) {
//
}
@Override
public List<Audit> updateAll(StrolchTransaction tx, List<Audit> audits) {
return null;
public void updateAll(StrolchTransaction tx, List<Audit> audits) {
//
}
@Override
@ -101,6 +107,6 @@ public class NoStrategyAuditTrail implements AuditTrail {
@Override
public <U> List<U> doQuery(StrolchTransaction tx, AuditQuery<U> query) {
return null;
throw new IllegalStateException("Audit trail is not enabled for realm " + this.realm);
}
}

View File

@ -1,50 +0,0 @@
/*
* Copyright 2015 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.agent.impl;
import static li.strolch.model.StrolchModelConstants.INTERPRETATION_ACTIVITY_REF;
import java.util.List;
import li.strolch.agent.api.ActivityMap;
import li.strolch.agent.api.StrolchRealm;
import li.strolch.model.activity.Activity;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.query.ActivityQuery;
import li.strolch.persistence.api.ActivityDao;
import li.strolch.persistence.api.StrolchTransaction;
public class TransactionalActivityMap extends TransactionalElementMap<Activity> implements ActivityMap {
public TransactionalActivityMap(StrolchRealm realm) {
super(realm);
}
@Override
protected void assertIsRefParam(Parameter<?> refP) {
ElementMapHelpers.assertIsRefParam(INTERPRETATION_ACTIVITY_REF, refP);
}
@Override
protected ActivityDao getDao(StrolchTransaction tx) {
return tx.getPersistenceHandler().getActivityDao(tx);
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, ActivityQuery<U> query) {
return getDao(tx).doQuery(query);
}
}

View File

@ -1,113 +0,0 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.agent.impl;
import java.util.List;
import java.util.Set;
import li.strolch.agent.api.AuditTrail;
import li.strolch.model.audit.Audit;
import li.strolch.model.audit.AuditQuery;
import li.strolch.persistence.api.AuditDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.utils.collections.DateRange;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class TransactionalAuditTrail implements AuditTrail {
protected AuditDao getDao(StrolchTransaction tx) {
return tx.getPersistenceHandler().getAuditDao(tx);
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean hasAudit(StrolchTransaction tx, String type, Long id) {
return getDao(tx).hasElement(type, id);
}
@Override
public long querySize(StrolchTransaction tx, DateRange dateRange) {
return getDao(tx).querySize(dateRange);
}
@Override
public long querySize(StrolchTransaction tx, String type, DateRange dateRange) {
return getDao(tx).querySize(type, dateRange);
}
@Override
public Set<String> getTypes(StrolchTransaction tx) {
return getDao(tx).queryTypes();
}
@Override
public Audit getBy(StrolchTransaction tx, String type, Long id) {
return getDao(tx).queryBy(type, id);
}
@Override
public List<Audit> getAllElements(StrolchTransaction tx, String type, DateRange dateRange) {
return getDao(tx).queryAll(type, dateRange);
}
@Override
public void add(StrolchTransaction tx, Audit audit) {
getDao(tx).save(audit);
}
@Override
public void addAll(StrolchTransaction tx, List<Audit> audits) {
getDao(tx).saveAll(audits);
}
@Override
public Audit update(StrolchTransaction tx, Audit audit) {
getDao(tx).update(audit);
return audit;
}
@Override
public List<Audit> updateAll(StrolchTransaction tx, List<Audit> audits) {
getDao(tx).updateAll(audits);
return audits;
}
@Override
public void remove(StrolchTransaction tx, Audit audit) {
getDao(tx).remove(audit);
}
@Override
public void removeAll(StrolchTransaction tx, List<Audit> audits) {
getDao(tx).removeAll(audits);
}
@Override
public long removeAll(StrolchTransaction tx, String type, DateRange dateRange) {
return getDao(tx).removeAll(type, dateRange);
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, AuditQuery<U> query) {
return getDao(tx).doQuery(query);
}
}

View File

@ -1,399 +0,0 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.agent.impl;
import java.text.MessageFormat;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import li.strolch.agent.api.ElementMap;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.agent.api.StrolchRealm;
import li.strolch.exception.StrolchException;
import li.strolch.model.StrolchRootElement;
import li.strolch.model.Version;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.parameter.StringListParameter;
import li.strolch.model.parameter.StringParameter;
import li.strolch.persistence.api.StrolchDao;
import li.strolch.persistence.api.StrolchPersistenceException;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.runtime.StrolchConstants;
/**
* @param <T>
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public abstract class TransactionalElementMap<T extends StrolchRootElement> implements ElementMap<T> {
private StrolchRealm realm;
public TransactionalElementMap(StrolchRealm realm) {
this.realm = realm;
}
protected StrolchRealm getRealm() {
return this.realm;
}
protected abstract StrolchDao<T> getDao(StrolchTransaction tx);
@Override
public boolean hasType(StrolchTransaction tx, String type) {
return getDao(tx).queryTypes().contains(type);
}
@Override
public boolean hasElement(StrolchTransaction tx, String type, String id) {
return getDao(tx).hasElement(type, id);
}
@Override
public long querySize(StrolchTransaction tx) {
return getDao(tx).querySize();
}
@Override
public long querySize(StrolchTransaction tx, String type) {
return getDao(tx).querySize(type);
}
@Override
public T getTemplate(StrolchTransaction tx, String type) {
return getTemplate(tx, type, false);
}
@Override
public T getTemplate(StrolchTransaction tx, String type, boolean assertExists) throws StrolchException {
T t = getBy(tx, StrolchConstants.TEMPLATE, type);
if (assertExists && t == null) {
String msg = "The template for type {0} does not exist!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, type);
throw new StrolchException(msg);
}
if (t == null)
return null;
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setId(StrolchAgent.getUniqueId());
clone.setType(type);
return clone;
}
@Override
public T getBy(StrolchTransaction tx, String type, String id) {
return getBy(tx, type, id, false);
}
@Override
public T getBy(StrolchTransaction tx, String type, String id, boolean assertExists) throws StrolchException {
T t = getDao(tx).queryBy(type, id);
if (assertExists && t == null) {
String msg = "The element for type {0} and id {1} does not exist!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, type, id);
throw new StrolchException(msg);
}
if (t == null)
return null;
if (!this.realm.getMode().isTransient())
return t;
// TODO cloning has its issues, as queries don't return a clone!
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setVersion(t.getVersion());
return clone;
}
@Override
public T getBy(StrolchTransaction tx, String type, String id, int version) {
return getBy(tx, type, id, version, false);
}
@Override
public T getBy(StrolchTransaction tx, String type, String id, int version, boolean assertExists)
throws StrolchException {
T t = getDao(tx).queryBy(type, id, version);
if (assertExists && t == null) {
String msg = "The element for type {0} and id {1} and version {2} does not exist!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, type, id, version);
throw new StrolchException(msg);
}
return t;
}
@Override
public T getBy(StrolchTransaction tx, StringParameter refP, boolean assertExists) throws StrolchException {
assertIsRefParam(refP);
String type = refP.getUom();
String id = refP.getValue();
T t = getBy(tx, type, id);
if (assertExists && t == null) {
String msg = "The element for refP {0} with id {1} does not exist!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, refP.getLocator(), id);
throw new StrolchException(msg);
}
if (t == null)
return null;
if (!this.realm.getMode().isTransient())
return t;
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setVersion(t.getVersion());
return clone;
}
@Override
public List<T> getBy(StrolchTransaction tx, StringListParameter refP, boolean assertExists)
throws StrolchException {
assertIsRefParam(refP);
String type = refP.getUom();
List<String> ids = refP.getValue();
return ids.stream().map(id -> {
T t = getBy(tx, type, id);
if (assertExists && t == null) {
String msg = "The element for refP {0} with id {1} does not exist!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, refP.getLocator(), id);
throw new StrolchException(msg);
}
return t;
}).filter(Objects::nonNull).map(t -> {
if (!this.realm.getMode().isTransient()) {
return t;
} else {
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setVersion(t.getVersion());
return clone;
}
}).collect(Collectors.toList());
}
@Override
public List<T> getVersionsFor(StrolchTransaction tx, String type, String id) {
return getDao(tx).queryVersionsFor(type, id).stream().map(t -> {
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setVersion(t.getVersion());
return clone;
}).collect(Collectors.toList());
}
@Override
public int getLatestVersionFor(StrolchTransaction tx, String type, String id) {
return getDao(tx).queryLatestVersionFor(type, id);
}
@Override
public List<T> getAllElements(StrolchTransaction tx) {
List<T> all = getDao(tx).queryAll();
if (this.realm.getMode().isTransient())
return all;
return all.stream().map(t -> {
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setVersion(t.getVersion());
return clone;
}).collect(Collectors.toList());
}
@Override
public List<T> getElementsBy(StrolchTransaction tx, String type) {
List<T> all = getDao(tx).queryAll(type);
if (this.realm.getMode().isTransient())
return all;
return all.stream().map(t -> {
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setVersion(t.getVersion());
return clone;
}).collect(Collectors.toList());
}
@Override
public Set<String> getTypes(StrolchTransaction tx) {
return getDao(tx).queryTypes();
}
@Override
public Set<String> getAllKeys(StrolchTransaction tx) {
return getDao(tx).queryKeySet();
}
@Override
public Set<String> getKeysBy(StrolchTransaction tx, String type) {
return getDao(tx).queryKeySet(type);
}
@Override
public void add(StrolchTransaction tx, T element) {
if (realm.isVersioningEnabled()) {
int latestVersion = getLatestVersionFor(tx, element.getType(), element.getId());
Version.setInitialVersionFor(element, latestVersion, tx.getCertificate().getUsername());
} else {
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
}
getDao(tx).save(element);
getDao(tx).flush();
}
@Override
public void addAll(StrolchTransaction tx, List<T> elements) {
for (T element : elements) {
if (realm.isVersioningEnabled()) {
int latestVersion = getLatestVersionFor(tx, element.getType(), element.getId());
Version.setInitialVersionFor(element, latestVersion, tx.getCertificate().getUsername());
} else {
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
}
}
getDao(tx).saveAll(elements);
getDao(tx).flush();
}
@Override
public void update(StrolchTransaction tx, T element) {
if (realm.isVersioningEnabled())
Version.updateVersionFor(element, tx.getCertificate().getUsername(), false);
else
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
getDao(tx).update(element);
getDao(tx).flush();
}
@Override
public void updateAll(StrolchTransaction tx, List<T> elements) {
for (T element : elements) {
if (realm.isVersioningEnabled())
Version.updateVersionFor(element, tx.getCertificate().getUsername(), false);
else
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
}
getDao(tx).updateAll(elements);
getDao(tx).flush();
}
@Override
public void remove(StrolchTransaction tx, T element) {
if (this.realm.isVersioningEnabled()) {
Version.updateVersionFor(element, tx.getCertificate().getUsername(), true);
getDao(tx).update(element);
} else {
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
getDao(tx).remove(element);
}
getDao(tx).flush();
}
@Override
public void removeAll(StrolchTransaction tx, List<T> elements) {
for (T element : elements) {
if (realm.isVersioningEnabled())
Version.updateVersionFor(element, tx.getCertificate().getUsername(), true);
else
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
}
if (this.realm.isVersioningEnabled()) {
getDao(tx).updateAll(elements);
} else {
getDao(tx).removeAll(elements);
}
getDao(tx).flush();
}
@Override
public long removeAll(StrolchTransaction tx) {
long removed = getDao(tx).removeAll();
getDao(tx).flush();
return removed;
}
@Override
public long removeAllBy(StrolchTransaction tx, String type) {
long removed = getDao(tx).removeAllBy(type);
getDao(tx).flush();
return removed;
}
@Override
public T revertToVersion(StrolchTransaction tx, T element) throws StrolchException {
return revertToVersion(tx, element.getType(), element.getId(), element.getVersion().getVersion());
}
@Override
public T revertToVersion(StrolchTransaction tx, String type, String id, int version) throws StrolchException {
if (!this.realm.isVersioningEnabled()) {
throw new StrolchPersistenceException("Can not revert to a version if versioning is not enabled!");
}
// get the current and specified version
T current = getBy(tx, type, id, true);
T versionT = getBy(tx, type, id, version, true);
// create the new version
@SuppressWarnings("unchecked")
T clone = (T) versionT.getClone();
clone.setVersion(current.getVersion().next(tx.getCertificate().getUsername(), false));
// save the new version
getDao(tx).update(clone);
getDao(tx).flush();
// and return new version
return clone;
}
@Override
public void undoVersion(StrolchTransaction tx, T element) throws StrolchException {
if (!this.realm.isVersioningEnabled()) {
throw new StrolchPersistenceException("Can not undo a version if versioning is not enabled!");
}
// make sure the given element is the latest version
T current = getBy(tx, element.getType(), element.getId(), true);
if (!current.getVersion().equals(element.getVersion())) {
String msg = "Can not undo the version {0} as it is not the latest {1}!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getVersion(), current.getVersion());
throw new StrolchException(msg);
}
getDao(tx).removeVersion(current);
getDao(tx).flush();
}
protected abstract void assertIsRefParam(Parameter<?> refP);
}

View File

@ -1,50 +0,0 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.agent.impl;
import static li.strolch.model.StrolchModelConstants.INTERPRETATION_ORDER_REF;
import java.util.List;
import li.strolch.agent.api.OrderMap;
import li.strolch.agent.api.StrolchRealm;
import li.strolch.model.Order;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.query.OrderQuery;
import li.strolch.persistence.api.OrderDao;
import li.strolch.persistence.api.StrolchTransaction;
public class TransactionalOrderMap extends TransactionalElementMap<Order> implements OrderMap {
public TransactionalOrderMap(StrolchRealm realm) {
super(realm);
}
@Override
protected void assertIsRefParam(Parameter<?> refP) {
ElementMapHelpers.assertIsRefParam(INTERPRETATION_ORDER_REF, refP);
}
@Override
protected OrderDao getDao(StrolchTransaction tx) {
return tx.getPersistenceHandler().getOrderDao(tx);
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, OrderQuery<U> query) {
return getDao(tx).doQuery(query);
}
}

View File

@ -1,135 +0,0 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.agent.impl;
import java.text.MessageFormat;
import li.strolch.agent.api.ActivityMap;
import li.strolch.agent.api.AuditTrail;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.OrderMap;
import li.strolch.agent.api.ResourceMap;
import li.strolch.persistence.api.PersistenceHandler;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.PrivilegeContext;
import li.strolch.runtime.configuration.ComponentConfiguration;
import li.strolch.utils.dbc.DBC;
import li.strolch.utils.helper.StringHelper;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class TransactionalRealm extends InternalStrolchRealm {
private ResourceMap resourceMap;
private OrderMap orderMap;
private ActivityMap activityMap;
private AuditTrail auditTrail;
private PersistenceHandler persistenceHandler;
public TransactionalRealm(String realm) {
super(realm);
}
@Override
public DataStoreMode getMode() {
return DataStoreMode.TRANSACTIONAL;
}
@Override
public StrolchTransaction openTx(Certificate certificate, String action) {
DBC.PRE.assertNotNull("Certificate must be set!", certificate); //$NON-NLS-1$
return this.persistenceHandler.openTx(this, certificate, action);
}
@Override
public StrolchTransaction openTx(Certificate certificate, Class<?> clazz) {
DBC.PRE.assertNotNull("Certificate must be set!", certificate); //$NON-NLS-1$
return this.persistenceHandler.openTx(this, certificate, clazz.getName());
}
@Override
public ResourceMap getResourceMap() {
return this.resourceMap;
}
@Override
public OrderMap getOrderMap() {
return this.orderMap;
}
@Override
public ActivityMap getActivityMap() {
return this.activityMap;
}
@Override
public AuditTrail getAuditTrail() {
return this.auditTrail;
}
@Override
public void initialize(ComponentContainer container, ComponentConfiguration configuration) {
super.initialize(container, configuration);
this.resourceMap = new TransactionalResourceMap(this);
this.orderMap = new TransactionalOrderMap(this);
this.activityMap = new TransactionalActivityMap(this);
if (isAuditTrailEnabled()) {
this.auditTrail = new TransactionalAuditTrail();
} else {
this.auditTrail = new NoStrategyAuditTrail();
}
this.persistenceHandler = container.getComponent(PersistenceHandler.class);
}
@Override
public void start(PrivilegeContext privilegeContext) {
super.start(privilegeContext);
long start = System.nanoTime();
int nrOfOrders = 0;
int nrOfResources = 0;
int nrOfActivities = 0;
try (StrolchTransaction tx = openTx(privilegeContext.getCertificate(), "strolch_boot")) {
nrOfOrders = this.orderMap.getAllKeys(tx).size();
}
try (StrolchTransaction tx = openTx(privilegeContext.getCertificate(), "strolch_boot")) {
nrOfResources = this.resourceMap.getAllKeys(tx).size();
}
try (StrolchTransaction tx = openTx(privilegeContext.getCertificate(), "strolch_boot")) {
nrOfActivities = this.activityMap.getAllKeys(tx).size();
}
long duration = System.nanoTime() - start;
String durationS = StringHelper.formatNanoDuration(duration);
logger.info(
MessageFormat.format("Initialized Transactional Maps for realm {0} took {1}.", getRealm(), durationS)); //$NON-NLS-1$
logger.info(MessageFormat.format("There are {0} Orders", nrOfOrders)); //$NON-NLS-1$
logger.info(MessageFormat.format("There are {0} Resources", nrOfResources)); //$NON-NLS-1$
logger.info(MessageFormat.format("There are {0} Activities", nrOfActivities)); //$NON-NLS-1$
}
@Override
public void destroy() {
//
}
}

View File

@ -1,50 +0,0 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.agent.impl;
import static li.strolch.model.StrolchModelConstants.INTERPRETATION_RESOURCE_REF;
import java.util.List;
import li.strolch.agent.api.ResourceMap;
import li.strolch.agent.api.StrolchRealm;
import li.strolch.model.Resource;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.query.ResourceQuery;
import li.strolch.persistence.api.ResourceDao;
import li.strolch.persistence.api.StrolchTransaction;
public class TransactionalResourceMap extends TransactionalElementMap<Resource> implements ResourceMap {
public TransactionalResourceMap(StrolchRealm realm) {
super(realm);
}
@Override
protected void assertIsRefParam(Parameter<?> refP) {
ElementMapHelpers.assertIsRefParam(INTERPRETATION_RESOURCE_REF, refP);
}
@Override
protected ResourceDao getDao(StrolchTransaction tx) {
return tx.getPersistenceHandler().getResourceDao(tx);
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, ResourceQuery<U> query) {
return getDao(tx).doQuery(query);
}
}

View File

@ -0,0 +1,28 @@
package li.strolch.agent.impl;
import static li.strolch.runtime.StrolchConstants.INTERPRETATION_ACTIVITY_REF;
import java.util.List;
import li.strolch.agent.api.ActivityMap;
import li.strolch.model.activity.Activity;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.query.ActivityQuery;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.runtime.query.inmemory.InMemoryActivityQueryVisitor;
import li.strolch.runtime.query.inmemory.InMemoryQuery;
public class TransientActivityMap extends TransientElementMap<Activity> implements ActivityMap {
@Override
protected void assertIsRefParam(Parameter<?> refP) {
ElementMapHelpers.assertIsRefParam(INTERPRETATION_ACTIVITY_REF, refP);
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, ActivityQuery<U> activityQuery) {
InMemoryActivityQueryVisitor visitor = new InMemoryActivityQueryVisitor();
InMemoryQuery<Activity, U> query = visitor.visit(activityQuery);
return query.doQuery(tx, this);
}
}

View File

@ -1,47 +1,31 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.persistence.inmemory;
package li.strolch.agent.impl;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import li.strolch.agent.api.AuditTrail;
import li.strolch.model.audit.Audit;
import li.strolch.model.audit.AuditQuery;
import li.strolch.persistence.api.AuditDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.runtime.query.inmemory.InMemoryAuditQuery;
import li.strolch.runtime.query.inmemory.InMemoryAuditQueryVisitor;
import li.strolch.utils.collections.DateRange;
import li.strolch.utils.collections.MapOfMaps;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class InMemoryAuditDao implements AuditDao {
public class TransientAuditTrail implements AuditTrail {
private MapOfMaps<String, Long, Audit> auditMap;
public InMemoryAuditDao() {
public TransientAuditTrail() {
this.auditMap = new MapOfMaps<>();
}
@Override
public synchronized boolean hasElement(String type, Long id) {
public boolean isEnabled() {
return true;
}
@Override
public boolean hasAudit(StrolchTransaction tx, String type, Long id) {
Map<Long, Audit> byType = this.auditMap.getMap(type);
if (byType == null)
return false;
@ -49,7 +33,7 @@ public class InMemoryAuditDao implements AuditDao {
}
@Override
public synchronized long querySize(DateRange dateRange) {
public long querySize(StrolchTransaction tx, DateRange dateRange) {
long size = 0L;
for (String type : this.auditMap.keySet()) {
Map<Long, Audit> byType = this.auditMap.getMap(type);
@ -63,7 +47,7 @@ public class InMemoryAuditDao implements AuditDao {
}
@Override
public synchronized long querySize(String type, DateRange dateRange) {
public long querySize(StrolchTransaction tx, String type, DateRange dateRange) {
Map<Long, Audit> byType = this.auditMap.getMap(type);
if (byType == null)
return 0L;
@ -77,17 +61,17 @@ public class InMemoryAuditDao implements AuditDao {
}
@Override
public synchronized Audit queryBy(String type, Long id) {
return this.auditMap.getElement(type, id);
}
@Override
public synchronized Set<String> queryTypes() {
public Set<String> getTypes(StrolchTransaction tx) {
return new HashSet<>(this.auditMap.keySet());
}
@Override
public synchronized List<Audit> queryAll(String type, DateRange dateRange) {
public Audit getBy(StrolchTransaction tx, String type, Long id) {
return this.auditMap.getElement(type, id);
}
@Override
public List<Audit> getAllElements(StrolchTransaction tx, String type, DateRange dateRange) {
List<Audit> audits = new ArrayList<>();
Map<Long, Audit> byType = this.auditMap.getMap(type);
if (byType == null)
@ -101,44 +85,43 @@ public class InMemoryAuditDao implements AuditDao {
}
@Override
public synchronized void save(Audit audit) {
public void add(StrolchTransaction tx, Audit audit) {
this.auditMap.addElement(audit.getElementType(), audit.getId(), audit);
}
@Override
public synchronized void saveAll(List<Audit> audits) {
public void addAll(StrolchTransaction tx, List<Audit> audits) {
for (Audit audit : audits) {
this.auditMap.addElement(audit.getElementType(), audit.getId(), audit);
}
}
@Override
public synchronized void update(Audit audit) {
public void update(StrolchTransaction tx, Audit audit) {
this.auditMap.addElement(audit.getElementType(), audit.getId(), audit);
}
@Override
public synchronized void updateAll(List<Audit> audits) {
public void updateAll(StrolchTransaction tx, List<Audit> audits) {
for (Audit audit : audits) {
this.auditMap.addElement(audit.getElementType(), audit.getId(), audit);
}
}
@Override
public synchronized void remove(Audit audit) {
public void remove(StrolchTransaction tx, Audit audit) {
this.auditMap.removeElement(audit.getElementType(), audit.getId());
}
@Override
public synchronized void removeAll(List<Audit> audits) {
public void removeAll(StrolchTransaction tx, List<Audit> audits) {
for (Audit audit : audits) {
this.auditMap.removeElement(audit.getElementType(), audit.getId());
}
}
@Override
public synchronized long removeAll(String type, DateRange dateRange) {
public long removeAll(StrolchTransaction tx, String type, DateRange dateRange) {
Map<Long, Audit> byType = this.auditMap.getMap(type);
if (byType == null)
return 0L;
@ -159,9 +142,9 @@ public class InMemoryAuditDao implements AuditDao {
}
@Override
public <U> List<U> doQuery(AuditQuery<U> auditQuery) {
public <U> List<U> doQuery(StrolchTransaction tx, AuditQuery<U> auditQuery) {
InMemoryAuditQueryVisitor<U> visitor = new InMemoryAuditQueryVisitor<>();
InMemoryAuditQuery<U> query = visitor.toInMemory(auditQuery);
return query.doQuery(this);
return query.doQuery(tx, this);
}
}

View File

@ -0,0 +1,420 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.agent.impl;
import static java.util.function.Function.identity;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
import li.strolch.agent.api.ElementMap;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.exception.StrolchException;
import li.strolch.model.StrolchRootElement;
import li.strolch.model.Version;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.parameter.StringListParameter;
import li.strolch.model.parameter.StringParameter;
import li.strolch.persistence.api.StrolchPersistenceException;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.runtime.StrolchConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public abstract class TransientElementMap<T extends StrolchRootElement> implements ElementMap<T> {
protected static final Logger logger = LoggerFactory.getLogger(TransientElementMap.class);
private Map<String, Map<String, T>> elementMap;
public TransientElementMap() {
this.elementMap = new HashMap<>();
}
@Override
public synchronized boolean hasType(StrolchTransaction tx, String type) {
return this.elementMap.containsKey(type);
}
@Override
public synchronized boolean hasElement(StrolchTransaction tx, String type, String id) {
Map<String, T> byType = this.elementMap.get(type);
return byType != null && byType.get(id) != null;
}
@Override
public synchronized long querySize(StrolchTransaction tx) {
return this.elementMap.entrySet().stream() //
.map(e -> e.getValue().entrySet().size()) //
.mapToInt(Integer::valueOf) //
.sum();
}
@Override
public synchronized long querySize(StrolchTransaction tx, String type) {
Map<String, T> byType = this.elementMap.get(type);
if (byType == null)
return 0;
return byType.entrySet().size();
}
@Override
public synchronized T getTemplate(StrolchTransaction tx, String type) {
return getTemplate(tx, type, false);
}
@Override
public T getTemplate(StrolchTransaction tx, String type, boolean assertExists) {
T t = getBy(tx, StrolchConstants.TEMPLATE, type);
if (assertExists && t == null) {
String msg = "The template with type {0} does not exist!"; //$NON-NLS-1$
throw new StrolchException(MessageFormat.format(msg, type));
}
if (t == null)
return null;
@SuppressWarnings("unchecked")
T clone = (T) t.getClone();
clone.setId(StrolchAgent.getUniqueId());
clone.setType(type);
return clone;
}
@Override
public synchronized T getBy(StrolchTransaction tx, String type, String id) {
return getBy(tx, type, id, false);
}
@Override
public T getBy(StrolchTransaction tx, String type, String id, boolean assertExists) throws StrolchException {
T t = null;
Map<String, T> byType = this.elementMap.get(type);
if (byType != null) {
t = byType.get(id);
}
if (assertExists && t == null) {
String msg = "The element with type {0} and id {1} does not exist!"; //$NON-NLS-1$
throw new StrolchException(MessageFormat.format(msg, type, id));
}
if (t == null)
return null;
// TODO cloning has its issues, as queries don't return a clone!
@SuppressWarnings("unchecked")
T clone = (T) t.getClone(true);
return clone;
}
@Override
public T getBy(StrolchTransaction tx, StringParameter refP, boolean assertExists) throws StrolchException {
assertIsRefParam(refP);
String type = refP.getUom();
String id = refP.getValue();
T t = getBy(tx, type, id, false);
if (assertExists && t == null) {
String msg = "The element with type {0} and id {1} does not exist for param {2}"; //$NON-NLS-1$
throw new StrolchException(MessageFormat.format(msg, type, id, refP.getLocator()));
}
return t;
}
@Override
public List<T> getBy(StrolchTransaction tx, StringListParameter refP, boolean assertExists)
throws StrolchException {
assertIsRefParam(refP);
String type = refP.getUom();
List<String> ids = refP.getValue();
return ids.stream() //
.map(id -> {
T t = getBy(tx, type, id, false);
if (assertExists && t == null) {
String msg = "The element with type {0} and id {1} does not exist for param {2}"; //$NON-NLS-1$
throw new StrolchException(MessageFormat.format(msg, type, id, refP.getLocator()));
}
return t;
}) //
.filter(Objects::nonNull) //
.collect(Collectors.toList());
}
@Override
public synchronized List<T> getAllElements(StrolchTransaction tx) {
return this.elementMap.entrySet().stream() //
.map(e -> e.getValue().entrySet().stream() //
.map(Map.Entry::getValue)) //
.flatMap(identity()) //
.map(t -> {
@SuppressWarnings("unchecked")
T clone = (T) t.getClone(true);
return clone;
}) //
.collect(Collectors.toList());
}
@Override
public synchronized List<T> getElementsBy(StrolchTransaction tx, String type) {
Map<String, T> byType = this.elementMap.get(type);
if (byType == null)
return new ArrayList<>(0);
return byType.entrySet().stream() //
.map(Map.Entry::getValue) //
.collect(Collectors.toList()).stream().map(t -> {
@SuppressWarnings("unchecked")
T clone = (T) t.getClone(true);
return clone;
}).collect(Collectors.toList());
}
@Override
public synchronized Set<String> getTypes(StrolchTransaction tx) {
return new HashSet<>(this.elementMap.keySet());
}
@Override
public synchronized Set<String> getAllKeys(StrolchTransaction tx) {
return this.elementMap.entrySet().stream() //
.map(e -> e.getValue().entrySet().stream() //
.map(Map.Entry::getKey)) //
.flatMap(identity()) //
.collect(Collectors.toSet());
}
@Override
public synchronized Set<String> getKeysBy(StrolchTransaction tx, String type) {
Map<String, T> byType = this.elementMap.get(type);
if (byType == null)
return new HashSet<>(0);
return byType.entrySet().stream() //
.map(Map.Entry::getKey) //
.collect(Collectors.toSet());
}
/**
* Special method used when starting the container to cache the values. Not to be used anywhere else but from the
* {@link CachedRealm}
*
* @param element
* the element to insert
*/
synchronized void insert(T element) {
Map<String, T> byType = this.elementMap.computeIfAbsent(element.getType(), k -> new HashMap<>());
// assert no object already exists with this id
if (byType.containsKey(element.getId())) {
String msg = "An element already exists with the id {0}. Elements of the same class must always have a unique id, regardless of their type!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getId());
throw new StrolchPersistenceException(msg);
}
byType.put(element.getId(), element);
// now make read only
element.setReadOnly();
}
@Override
public synchronized void add(StrolchTransaction tx, T element) {
if (!element.hasVersion())
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
Map<String, T> byType = this.elementMap.computeIfAbsent(element.getType(), k -> new HashMap<>());
// assert no object already exists with this id
if (byType.containsKey(element.getId())) {
String msg = "An element already exists with the id {0}. Elements of the same class must always have a unique id, regardless of their type!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getId());
throw new StrolchPersistenceException(msg);
}
byType.put(element.getId(), element);
// now make read only
element.setReadOnly();
}
@Override
public synchronized void addAll(StrolchTransaction tx, List<T> elements) {
for (T element : elements) {
if (!element.hasVersion())
Version.setInitialVersionFor(element, -1, tx.getCertificate().getUsername());
Map<String, T> byType = this.elementMap.computeIfAbsent(element.getType(), k -> new HashMap<>());
// assert no object already exists with this id
if (byType.containsKey(element.getId())) {
String msg = "An element already exists with the id {0}. Elements of the same class must always have a unique id, regardless of their type!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getId());
throw new StrolchPersistenceException(msg);
}
byType.put(element.getId(), element);
// now make read only
element.setReadOnly();
}
}
@Override
public synchronized void update(StrolchTransaction tx, T element) {
Map<String, T> byType = this.elementMap.get(element.getType());
if (byType == null) {
String msg = "The element does not yet exist with the type {0} and id {1}. Use add() for new objects!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getType(), element.getId());
throw new StrolchPersistenceException(msg);
}
// assert no object already exists with this id
if (!byType.containsKey(element.getId())) {
String msg = "The element does not yet exist with the type {0} and id {1}. Use add() for new objects!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getType(), element.getId());
throw new StrolchPersistenceException(msg);
}
byType.put(element.getId(), element);
// now make read only
element.setReadOnly();
}
@Override
public synchronized void updateAll(StrolchTransaction tx, List<T> elements) {
for (T element : elements) {
Map<String, T> byType = this.elementMap.get(element.getType());
if (byType == null) {
String msg = "The element does not yet exist with the type {0} and id {1}. Use add() for new objects!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getType(), element.getId());
throw new StrolchPersistenceException(msg);
}
// assert no object already exists with this id
if (!byType.containsKey(element.getId())) {
String msg = "The element does not yet exist with the type {0} and id {1}. Use add() for new objects!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getType(), element.getId());
throw new StrolchPersistenceException(msg);
}
byType.put(element.getId(), element);
// now make read only
element.setReadOnly();
}
}
@Override
public synchronized void remove(StrolchTransaction tx, T element) {
Map<String, T> byType = this.elementMap.get(element.getType());
if (byType != null) {
byType.remove(element.getId());
if (byType.isEmpty()) {
this.elementMap.remove(element.getType());
}
}
}
@Override
public synchronized void removeAll(StrolchTransaction tx, List<T> elements) {
for (T element : elements) {
Map<String, T> byType = this.elementMap.get(element.getType());
if (byType != null) {
byType.remove(element.getId());
if (byType.isEmpty()) {
this.elementMap.remove(element.getType());
}
}
}
}
@Override
public synchronized long removeAll(StrolchTransaction tx) {
long removed = 0;
Set<String> keySet = new HashSet<>(this.elementMap.keySet());
for (String type : keySet) {
Map<String, T> byType = this.elementMap.remove(type);
removed += byType.size();
byType.clear();
}
return removed;
}
@Override
public synchronized long removeAllBy(StrolchTransaction tx, String type) {
long removed = 0;
Map<String, T> byType = this.elementMap.remove(type);
if (byType != null) {
removed = byType.size();
byType.clear();
}
return removed;
}
@Override
public T getBy(StrolchTransaction tx, String type, String id, int version) {
return getBy(tx, type, id, version, false);
}
@Override
public T getBy(StrolchTransaction tx, String type, String id, int version, boolean assertExists)
throws StrolchException {
throw new IllegalStateException("Transient mode does not support versioning");
}
@Override
public List<T> getVersionsFor(StrolchTransaction tx, String type, String id) {
throw new IllegalStateException("Transient mode does not support versioning");
}
@Override
public int getLatestVersionFor(StrolchTransaction tx, String type, String id) {
throw new IllegalStateException("Transient mode does not support versioning");
}
@Override
public T revertToVersion(StrolchTransaction tx, T element) throws StrolchException {
throw new IllegalStateException("Transient mode does not support versioning");
}
@Override
public T revertToVersion(StrolchTransaction tx, String type, String id, int version) throws StrolchException {
throw new IllegalStateException("Transient mode does not support versioning");
}
@Override
public void undoVersion(StrolchTransaction tx, T element) throws StrolchException {
throw new IllegalStateException("Transient mode does not support versioning");
}
protected abstract void assertIsRefParam(Parameter<?> refP);
}

View File

@ -0,0 +1,28 @@
package li.strolch.agent.impl;
import static li.strolch.runtime.StrolchConstants.INTERPRETATION_ORDER_REF;
import java.util.List;
import li.strolch.agent.api.OrderMap;
import li.strolch.model.Order;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.query.OrderQuery;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.runtime.query.inmemory.InMemoryOrderQueryVisitor;
import li.strolch.runtime.query.inmemory.InMemoryQuery;
public class TransientOrderMap extends TransientElementMap<Order> implements OrderMap {
@Override
protected void assertIsRefParam(Parameter<?> refP) {
ElementMapHelpers.assertIsRefParam(INTERPRETATION_ORDER_REF, refP);
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, OrderQuery<U> orderQuery) {
InMemoryOrderQueryVisitor visitor = new InMemoryOrderQueryVisitor();
InMemoryQuery<Order, U> query = visitor.visit(orderQuery);
return query.doQuery(tx, this);
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -18,16 +18,10 @@ package li.strolch.agent.impl;
import java.io.File;
import java.text.MessageFormat;
import li.strolch.agent.api.ActivityMap;
import li.strolch.agent.api.AuditTrail;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.OrderMap;
import li.strolch.agent.api.ResourceMap;
import li.strolch.agent.api.*;
import li.strolch.model.ModelStatistics;
import li.strolch.model.xml.XmlModelSaxFileReader;
import li.strolch.persistence.api.PersistenceHandler;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.persistence.inmemory.InMemoryPersistence;
import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.PrivilegeContext;
import li.strolch.runtime.StrolchConstants;
@ -45,7 +39,6 @@ public class TransientRealm extends InternalStrolchRealm {
private OrderMap orderMap;
private ActivityMap activityMap;
private AuditTrail auditTrail;
private PersistenceHandler persistenceHandler;
private File modelFile;
@ -61,13 +54,13 @@ public class TransientRealm extends InternalStrolchRealm {
@Override
public StrolchTransaction openTx(Certificate certificate, String action) {
DBC.PRE.assertNotNull("Certificate must be set!", certificate); //$NON-NLS-1$
return this.persistenceHandler.openTx(this, certificate, action);
return new TransientTransaction(this.container, this, certificate, action);
}
@Override
public StrolchTransaction openTx(Certificate certificate, Class<?> clazz) {
DBC.PRE.assertNotNull("Certificate must be set!", certificate); //$NON-NLS-1$
return this.persistenceHandler.openTx(this, certificate, clazz.getName());
return new TransientTransaction(this.container, this, certificate, clazz.getName());
}
@Override
@ -103,15 +96,14 @@ public class TransientRealm extends InternalStrolchRealm {
this.modelFile = configuration.getDataFile(key, null, configuration.getRuntimeConfiguration(), true);
this.persistenceHandler = new InMemoryPersistence(container, isVersioningEnabled());
this.resourceMap = new TransactionalResourceMap(this);
this.orderMap = new TransactionalOrderMap(this);
this.activityMap = new TransactionalActivityMap(this);
this.resourceMap = new TransientResourceMap();
this.orderMap = new TransientOrderMap();
this.activityMap = new TransientActivityMap();
if (isAuditTrailEnabled())
this.auditTrail = new TransactionalAuditTrail();
this.auditTrail = new TransientAuditTrail();
else
this.auditTrail = new NoStrategyAuditTrail();
this.auditTrail = new NoStrategyAuditTrail(getRealm());
}
@Override
@ -135,8 +127,9 @@ public class TransientRealm extends InternalStrolchRealm {
}
String durationS = StringHelper.formatNanoDuration(statistics.durationNanos);
logger.info(MessageFormat.format("Loading XML Model file {0} for realm {1} took {2}.", this.modelFile.getName(), //$NON-NLS-1$
getRealm(), durationS));
logger.info(MessageFormat
.format("Loaded XML Model file {0} for realm {1} took {2}.", this.modelFile.getName(), //$NON-NLS-1$
getRealm(), durationS));
logger.info(MessageFormat.format("Loaded {0} Orders", statistics.nrOfOrders)); //$NON-NLS-1$
logger.info(MessageFormat.format("Loaded {0} Resources", statistics.nrOfResources)); //$NON-NLS-1$
logger.info(MessageFormat.format("Loaded {0} Activities", statistics.nrOfActivities)); //$NON-NLS-1$

View File

@ -0,0 +1,28 @@
package li.strolch.agent.impl;
import static li.strolch.model.StrolchModelConstants.INTERPRETATION_RESOURCE_REF;
import java.util.List;
import li.strolch.agent.api.ResourceMap;
import li.strolch.model.Resource;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.query.ResourceQuery;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.runtime.query.inmemory.InMemoryQuery;
import li.strolch.runtime.query.inmemory.InMemoryResourceQueryVisitor;
public class TransientResourceMap extends TransientElementMap<Resource> implements ResourceMap {
@Override
protected void assertIsRefParam(Parameter<?> refP) {
ElementMapHelpers.assertIsRefParam(INTERPRETATION_RESOURCE_REF, refP);
}
@Override
public <U> List<U> doQuery(StrolchTransaction tx, ResourceQuery<U> resourceQuery) {
InMemoryResourceQueryVisitor visitor = new InMemoryResourceQueryVisitor();
InMemoryQuery<Resource, U> query = visitor.visit(resourceQuery);
return query.doQuery(tx, this);
}
}

View File

@ -1,19 +1,19 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.persistence.inmemory;
package li.strolch.agent.impl;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.StrolchRealm;
@ -22,14 +22,11 @@ import li.strolch.persistence.api.PersistenceHandler;
import li.strolch.persistence.api.TransactionState;
import li.strolch.privilege.model.Certificate;
public class InMemoryTransaction extends AbstractTransaction {
public class TransientTransaction extends AbstractTransaction {
private InMemoryPersistence persistenceHandler;
public InMemoryTransaction(ComponentContainer container, StrolchRealm realm, Certificate certificate, String action,
InMemoryPersistence persistenceHandler) {
public TransientTransaction(ComponentContainer container, StrolchRealm realm, Certificate certificate,
String action) {
super(container, realm, certificate, action);
this.persistenceHandler = persistenceHandler;
}
@Override
@ -49,6 +46,6 @@ public class InMemoryTransaction extends AbstractTransaction {
@Override
public PersistenceHandler getPersistenceHandler() {
return this.persistenceHandler;
throw new IllegalStateException("No persistence handler for in-memory TX!");
}
}

View File

@ -39,17 +39,18 @@ public abstract class StrolchJob implements Runnable {
}
protected ScheduledExecutorService getScheduledExecutor() {
return getAgent().getScheduledExecutor();
return getAgent().getScheduledExecutor("StrolchJob");
}
/**
* Performs the given {@link PrivilegedRunnable} as the privileged system user
* {@link StrolchConstants#SYSTEM_USER_AGENT}
*
*
* @param runnable
* the runnable to perform
*
* the runnable to perform
*
* @throws PrivilegeException
* if the agent can not perform the action
*/
protected void runAsAgent(PrivilegedRunnable runnable) throws PrivilegeException {
getContainer().getPrivilegeHandler().runAsAgent(runnable);
@ -57,10 +58,10 @@ public abstract class StrolchJob implements Runnable {
/**
* Opens a {@link StrolchTransaction} for the default realm and certificate
*
*
* @param cert
* the certificate authorizing the transaction
*
* the certificate authorizing the transaction
*
* @return the newly created transaction
*/
protected StrolchTransaction openTx(Certificate cert) {

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -94,10 +94,8 @@ public abstract class AbstractTransaction implements StrolchTransaction {
private String action;
private Certificate certificate;
public AbstractTransaction(ComponentContainer container,
StrolchRealm realm,
Certificate certificate,
String action) {
public AbstractTransaction(ComponentContainer container, StrolchRealm realm, Certificate certificate,
String action) {
DBC.PRE.assertNotNull("container must be set!", container); //$NON-NLS-1$
DBC.PRE.assertNotNull("realm must be set!", realm); //$NON-NLS-1$
DBC.PRE.assertNotNull("certificate must be set!", certificate); //$NON-NLS-1$
@ -347,28 +345,28 @@ public abstract class AbstractTransaction implements StrolchTransaction {
@Override
public <U> List<U> doQuery(OrderQuery<U> query) {
assertQueryAllowed(query);
DBC.PRE.assertNotNull("orderVisitor", query.getOrderVisitor());
DBC.PRE.assertNotNull("orderVisitor", query.getVisitor());
return getOrderMap().doQuery(this, query);
}
@Override
public <U> List<U> doQuery(ResourceQuery<U> query) {
assertQueryAllowed(query);
DBC.PRE.assertNotNull("resourceVisitor", query.getResourceVisitor());
DBC.PRE.assertNotNull("resourceVisitor", query.getVisitor());
return getResourceMap().doQuery(this, query);
}
@Override
public <U> List<U> doQuery(ActivityQuery<U> query) {
assertQueryAllowed(query);
DBC.PRE.assertNotNull("activityVisitor", query.getActivityVisitor());
DBC.PRE.assertNotNull("activityVisitor", query.getVisitor());
return getActivityMap().doQuery(this, query);
}
@Override
public <U> List<U> doQuery(AuditQuery<U> query) {
assertQueryAllowed(query);
DBC.PRE.assertNotNull("auditVisitor", query.getAuditVisitor());
DBC.PRE.assertNotNull("auditVisitor", query.getVisitor());
return getAuditTrail().doQuery(this, query);
}
@ -524,10 +522,10 @@ public abstract class AbstractTransaction implements StrolchTransaction {
Order element = getElementFromFilter(Tags.ORDER, Order.locatorFor(StrolchConstants.TEMPLATE, type));
if (element == null)
element = getOrderMap().getTemplate(this, type, assertExists);
if(element != null)
if (element != null)
element.setDate(new Date());
return element;
}

View File

@ -15,15 +15,12 @@
*/
package li.strolch.persistence.api;
import java.util.List;
import li.strolch.model.activity.Activity;
import li.strolch.model.query.ActivityQuery;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public interface ActivityDao extends StrolchDao<Activity> {
public <U> List<U> doQuery(ActivityQuery<U> query);
// marker interface
}

View File

@ -15,15 +15,12 @@
*/
package li.strolch.persistence.api;
import java.util.List;
import li.strolch.model.Order;
import li.strolch.model.query.OrderQuery;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public interface OrderDao extends StrolchDao<Order> {
public <U> List<U> doQuery(OrderQuery<U> query);
// marker interface
}

View File

@ -93,9 +93,4 @@ public interface PersistenceHandler {
* @return the {@link AuditDao}
*/
public AuditDao getAuditDao(StrolchTransaction tx);
/**
* Performs a database specific initialization of the underlying database for each realm.
*/
public void performDbInitialization();
}

View File

@ -15,15 +15,12 @@
*/
package li.strolch.persistence.api;
import java.util.List;
import li.strolch.model.Resource;
import li.strolch.model.query.ResourceQuery;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public interface ResourceDao extends StrolchDao<Resource> {
public <U> List<U> doQuery(ResourceQuery<U> query);
// marker interface
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -26,192 +26,97 @@ import li.strolch.model.StrolchRootElement;
* in Strolch are always referenced by a type and an ID. The type is a categorisation/grouping of the objects, while the
* ID is a unique identifier of the object. The ID must be unique, even for multiple groups.
* </p>
*
*
* <p>
* The DAO must support versioning. i.e. if versioning is enabled, then if an object is updated or removed, the existing
* version is not modified, but a new version is persisted so that rollbacks can be done
* </p>
*
* @author Robert von Burg <eitch@eitchnet.ch>
*
* @param <T>
* the object instance being queried from the underlying persistence layer
* the object instance being queried from the underlying persistence layer
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public interface StrolchDao<T extends StrolchRootElement> {
/**
* Queries the set of IDs for all elements, regardless of types from the underlying persistence layer.
*
* @return the set of IDs for all elements
*/
public Set<String> queryKeySet();
/**
* Returns true if an element exists with the given type and id in the underlying persistence layer
*
* @param type
* the type of elements
* @param id
* the id of the element to return
*
* @return true if an element exists with the given type and id
*/
public boolean hasElement(String type, String id);
/**
* Returns the number of elements in the underlying persistence layer, regardless of type
*
*
* @return the number of elements in the underlying persistence layer
*/
public long querySize();
/**
* Returns the number of elements in the underlying persistence layer for the given type
*
*
* @return the number of elements in the underlying persistence layer for the given type
*/
public long querySize(String type);
/**
* Queries the set of IDs for the elements with the given type
*
* @return the set of IDs for the elements with the given type
*/
public Set<String> queryKeySet(String type);
/**
* Queries the current list of types from the underlying persistence layer
*
*
* @return the list of types
*/
public Set<String> queryTypes();
/**
* Queries the latest version of the element with the given type and ID
*
* @param type
* the type of the element to be queried
* @param id
* the id of the element to be queried
*
* @return the element with the given type and ID, or null if it does not exist
*/
public T queryBy(String type, String id);
/**
* <p>
* Queries a specific version of the element with the given type and ID.
* </p>
*
* <p>
* <b>Note:</b> If you want to query the latest version, then use the method with out the version parameter
* </p>
*
* @param type
* the type of the element to be queried
* @param id
* the id of the element to be queried
* @param version
* the version of the element to be returned
*
* @return the element with the given type and ID, or null if it does not exist
*/
public T queryBy(String type, String id, int version);
/**
* Queries and returns all the versions of the element with the given type and ID
*
* @param type
* the type of the element to be queried
* @param id
* the id of the element to be queried
*
* @return all the versions of the element with the given type and ID
*/
public List<T> queryVersionsFor(String type, String id);
/**
* Queries and returns the latest version of the element with the given type and ID, -1 if no version available
*
* @param type
* the type of the element to be queried
* @param id
* the id of the element to be queried
*
* @return the latest version of the element with the given type and ID, -1 if no version available
* @throws StrolchPersistenceException
* if something goes wrong
*/
public int queryLatestVersionFor(String type, String id);
/**
* Queries and returns the number of versions for the element with the given type and ID
*
* @param type
* the type of the element to be queried
* @param id
* the id of the element to be queried
*
* @return the number of versions for the element with the given type and ID
*/
public long queryVersionsSizeFor(String type, String id);
/**
* Queries and returns all elements regardless of type
*
* @return all elements regardless of type
*/
public List<T> queryAll();
public Set<String> queryTypes() throws StrolchPersistenceException;
/**
* Queries and returns all elements of the given type
*
*
* @param type
* the type of element to return
*
* the type of element to return
*
* @return all elements of the given type
*
* @throws StrolchPersistenceException
* if something goes wrong
*/
public List<T> queryAll(String type);
public List<T> queryAll(String type) throws StrolchPersistenceException;
/**
* Persists the given element. The element must not yet exist
*
*
* @param element
* the element to be persisted
*
* the element to be persisted
*
* @throws StrolchPersistenceException
* if the element already exists
* if the element already exists
*/
public void save(T element) throws StrolchPersistenceException;
/**
* Persists the given list of elements. None of the elements may already exists
*
*
* @param elements
* the list of elements to be persisted
*
* the list of elements to be persisted
*
* @throws StrolchPersistenceException
* if any of the elements already exist
* if any of the elements already exist
*/
public void saveAll(List<T> elements) throws StrolchPersistenceException;
/**
* Updates the given element. The element must already exist
*
*
* @param element
* the element to be updated
*
* the element to be updated
*
* @throws StrolchPersistenceException
* if the element does not exist
* if the element does not exist
*/
public void update(T element) throws StrolchPersistenceException;
/**
* Updates the given list of elements. Each element must already exist
*
*
* @param elements
* the elements to be updated
*
* the elements to be updated
*
* @throws StrolchPersistenceException
* if any of the elements do not exist
* if any of the elements do not exist
*/
public void updateAll(List<T> elements) throws StrolchPersistenceException;
@ -219,17 +124,17 @@ public interface StrolchDao<T extends StrolchRootElement> {
* <p>
* Removes the given element from the underlying persistence layer
* </p>
*
*
* <p>
* <b>Note:</b> This method deletes the given object including its versions! Do not call this method if you want to
* use versioning!
* </p>
*
*
* @param element
* the element to be removed
*
* the element to be removed
*
* @throws StrolchPersistenceException
* if the element does not exist
* if the element does not exist
*/
public void remove(T element) throws StrolchPersistenceException;
@ -237,18 +142,17 @@ public interface StrolchDao<T extends StrolchRootElement> {
* <p>
* Removes the given elements from the underlying persistence layer
* </p>
*
*
* <p>
* <b>Note:</b> This method deletes the given objects including their versions! Do not call this method if you want
* to use versioning!
* </p>
*
*
*
* @param elements
* the elements to be removed
*
* the elements to be removed
*
* @throws StrolchPersistenceException
* if any of the elements do not exist
* if any of the elements do not exist
*/
public void removeAll(List<T> elements) throws StrolchPersistenceException;
@ -256,34 +160,116 @@ public interface StrolchDao<T extends StrolchRootElement> {
* <p>
* Removes all elements regardless of type from the underlying persistence layer
* </p>
*
*
* <p>
* <b>Note:</b> This method does not support versioning. This method completely removes all objects regardless of
* type and their versions!
* </p>
*
*
* @return the number of elements removed
*
*
* @throws StrolchPersistenceException
* if something goes wrong
*/
public long removeAll();
public long removeAll() throws StrolchPersistenceException;
/**
* <p>
* Removes all elements of the given type from the underlying persistence layer
* </p>
*
*
* <p>
* <b>Note:</b> This method does not support versioning. This method completely removes all objects of the given
* type and their versions!
* </p>
*
*
* @param type
* the type of element to remove
*
* the type of element to remove
*
* @return the number of elements removed
*
* @throws StrolchPersistenceException
* if something goes wrong
*/
public long removeAllBy(String type);
public long removeAllBy(String type) throws StrolchPersistenceException;
/**
* <p>
* Queries a specific version of the element with the given type and ID.
* </p>
*
* <p>
* <b>Note:</b> If you want to query the latest version, then use the method with out the version parameter
* </p>
*
* @param type
* the type of the element to be queried
* @param id
* the id of the element to be queried
* @param version
* the version of the element to be returned
*
* @return the element with the given type and ID, or null if it does not exist
*
* @throws StrolchPersistenceException
* if something goes wrong
*/
public T queryBy(String type, String id, int version) throws StrolchPersistenceException;
/**
* Queries and returns all the versions of the element with the given type and ID
*
* @param type
* the type of the element to be queried
* @param id
* the id of the element to be queried
*
* @return all the versions of the element with the given type and ID
*
* @throws StrolchPersistenceException
* if something goes wrong
*/
public List<T> queryVersionsFor(String type, String id) throws StrolchPersistenceException;
/**
* Queries and returns the latest version of the element with the given type and ID, -1 if no version available
*
* @param type
* the type of the element to be queried
* @param id
* the id of the element to be queried
*
* @return the latest version of the element with the given type and ID, -1 if no version available
*
* @throws StrolchPersistenceException
* if something goes wrong
*/
public int queryLatestVersionFor(String type, String id) throws StrolchPersistenceException;
/**
* Queries and returns the number of versions for the element with the given type and ID
*
* @param type
* the type of the element to be queried
* @param id
* the id of the element to be queried
*
* @return the number of versions for the element with the given type and ID
*
* @throws StrolchPersistenceException
* if something goes wrong
*/
public long queryVersionsSizeFor(String type, String id) throws StrolchPersistenceException;
/**
* Queries and returns all elements regardless of type
*
* @return all elements regardless of type
*
* @throws StrolchPersistenceException
* if something goes wrong
*/
public List<T> queryAll() throws StrolchPersistenceException;
/**
* <p>
@ -291,21 +277,24 @@ public interface StrolchDao<T extends StrolchRootElement> {
* latest version and thus always deletes the newest version. To delete multiple versions call this method multiple
* times. To remove it completely, call the {@link #remove(StrolchRootElement)} method.
* </p>
*
*
* <p>
* <b>Note:</b> This element given must be the current latest version!
* </p>
*
*
* @param element
* the latest version of the element to be removed
*
* the latest version of the element to be removed
*
* @throws StrolchPersistenceException
* if the element/version does not exist
* if the element/version does not exist
*/
public void removeVersion(T element) throws StrolchPersistenceException;
/**
* Causes the DAO to flush any actions which have not yet been sent to the underlying persistence layer
*
* @throws StrolchPersistenceException
* if something goes wrong
*/
public void flush();
public void flush() throws StrolchPersistenceException;
}

View File

@ -0,0 +1,33 @@
package li.strolch.persistence.api;
import li.strolch.model.Order;
import li.strolch.model.Resource;
import li.strolch.model.activity.Activity;
import li.strolch.model.visitor.StrolchRootElementVisitor;
public class TxAddStrolchRootElementVisitor implements StrolchRootElementVisitor<Void> {
private final StrolchTransaction tx;
public TxAddStrolchRootElementVisitor(StrolchTransaction tx) {
this.tx = tx;
}
@Override
public Void visitOrder(Order order) {
tx.add(order);
return null;
}
@Override
public Void visitResource(Resource resource) {
tx.add(resource);
return null;
}
@Override
public Void visitActivity(Activity activity) {
tx.add(activity);
return null;
}
}

View File

@ -0,0 +1,33 @@
package li.strolch.persistence.api;
import li.strolch.model.Order;
import li.strolch.model.Resource;
import li.strolch.model.activity.Activity;
import li.strolch.model.visitor.StrolchRootElementVisitor;
public class TxRemoveStrolchRootElementVisitor implements StrolchRootElementVisitor<Void> {
private final StrolchTransaction tx;
public TxRemoveStrolchRootElementVisitor(StrolchTransaction tx) {
this.tx = tx;
}
@Override
public Void visitOrder(Order order) {
tx.remove(order);
return null;
}
@Override
public Void visitResource(Resource resource) {
tx.remove(resource);
return null;
}
@Override
public Void visitActivity(Activity activity) {
tx.remove(activity);
return null;
}
}

View File

@ -0,0 +1,33 @@
package li.strolch.persistence.api;
import li.strolch.model.Order;
import li.strolch.model.Resource;
import li.strolch.model.activity.Activity;
import li.strolch.model.visitor.StrolchRootElementVisitor;
public class TxUpdateStrolchRootElementVisitor implements StrolchRootElementVisitor<Void> {
private final StrolchTransaction tx;
public TxUpdateStrolchRootElementVisitor(StrolchTransaction tx) {
this.tx = tx;
}
@Override
public Void visitOrder(Order order) {
tx.update(order);
return null;
}
@Override
public Void visitResource(Resource resource) {
tx.update(resource);
return null;
}
@Override
public Void visitActivity(Activity activity) {
tx.update(activity);
return null;
}
}

View File

@ -1,38 +0,0 @@
/*
* Copyright 2015 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.persistence.inmemory;
import java.util.List;
import li.strolch.model.activity.Activity;
import li.strolch.model.query.ActivityQuery;
import li.strolch.persistence.api.ActivityDao;
import li.strolch.runtime.query.inmemory.InMemoryActivityQueryVisitor;
import li.strolch.runtime.query.inmemory.InMemoryQuery;
public class InMemoryActivityDao extends InMemoryDao<Activity> implements ActivityDao {
public InMemoryActivityDao(boolean versioningEnabled) {
super(versioningEnabled);
}
@Override
public <U> List<U> doQuery(ActivityQuery<U> activityQuery) {
InMemoryActivityQueryVisitor visitor = new InMemoryActivityQueryVisitor();
InMemoryQuery<Activity, U> query = visitor.visit(activityQuery);
return query.doQuery(this);
}
}

View File

@ -1,331 +0,0 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.persistence.inmemory;
import java.text.MessageFormat;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import li.strolch.model.StrolchRootElement;
import li.strolch.persistence.api.StrolchDao;
import li.strolch.persistence.api.StrolchPersistenceException;
public class InMemoryDao<T extends StrolchRootElement> implements StrolchDao<T> {
private Map<String, Map<String, ArrayDeque<T>>> elementMap;
private boolean versioningEnabled;
public InMemoryDao(boolean versioningEnabled) {
this.versioningEnabled = versioningEnabled;
this.elementMap = new HashMap<>();
}
@Override
public synchronized boolean hasElement(String type, String id) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(type);
if (byType == null)
return false;
ArrayDeque<T> list = byType.get(id);
if (list == null)
return false;
return !list.getLast().getVersion().isDeleted();
}
@Override
public synchronized long querySize() {
return this.elementMap.entrySet().stream().map(e -> {
return e.getValue().entrySet().stream().filter(f -> {
return !f.getValue().getLast().getVersion().isDeleted();
}).count();
}).mapToInt(e -> e.intValue()).sum();
}
@Override
public synchronized long querySize(String type) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(type);
if (byType == null)
return 0;
return byType.entrySet().stream().filter(e -> !e.getValue().getLast().getVersion().isDeleted()).count();
}
@Override
public synchronized Set<String> queryKeySet() {
return this.elementMap.entrySet().stream() //
.map(e -> {
return e.getValue().entrySet().stream() //
.filter(f -> !f.getValue().getLast().getVersion().isDeleted()) //
.map(f -> f.getKey());
}) //
.flatMap(Function.identity()) //
.collect(Collectors.toSet());
}
@Override
public synchronized Set<String> queryKeySet(String type) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(type);
if (byType == null)
return new HashSet<>(0);
return byType.entrySet().stream() //
.filter(e -> !e.getValue().getLast().getVersion().isDeleted()) //
.map(e -> e.getKey()) //
.collect(Collectors.toSet());
}
@Override
public synchronized Set<String> queryTypes() {
return new HashSet<>(this.elementMap.keySet());
}
@Override
public synchronized T queryBy(String type, String id) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(type);
if (byType == null)
return null;
ArrayDeque<T> list = byType.get(id);
if (list == null)
return null;
T t = list.getLast();
if (t.getVersion() != null && t.getVersion().isDeleted())
return null;
return t;
}
@Override
public synchronized T queryBy(String type, String id, int version) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(type);
if (byType == null)
return null;
ArrayDeque<T> list = byType.get(id);
if (list == null)
return null;
for (T t : list) {
if (t.getVersion().getVersion() == version)
return t;
}
return null;
}
@Override
public synchronized List<T> queryVersionsFor(String type, String id) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(type);
if (byType == null)
return null;
ArrayDeque<T> list = byType.get(id);
if (list == null)
return new ArrayList<>(0);
return new ArrayList<>(list);
}
@Override
public int queryLatestVersionFor(String type, String id) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(type);
if (byType == null)
return -1;
ArrayDeque<T> list = byType.get(id);
if (list == null || list.isEmpty())
return -1;
return list.stream().mapToInt(e -> e.getVersion().getVersion()).max().orElse(-1);
}
@Override
public long queryVersionsSizeFor(String type, String id) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(type);
if (byType == null)
return 0L;
ArrayDeque<T> list = byType.get(id);
if (list == null)
return 0L;
return list.size();
}
@Override
public synchronized List<T> queryAll() {
return this.elementMap.entrySet().stream() //
.map(e -> {
return e.getValue().entrySet().stream() //
.filter(f -> !f.getValue().getLast().getVersion().isDeleted()) //
.map(f -> f.getValue().getLast());
}) //
.flatMap(Function.identity()) //
.collect(Collectors.toList());
}
@Override
public synchronized List<T> queryAll(String type) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(type);
if (byType == null)
return new ArrayList<>(0);
return byType.entrySet().stream() //
.filter(e -> !e.getValue().getLast().getVersion().isDeleted()) //
.map(e -> e.getValue().getLast()) //
.collect(Collectors.toList());
}
@Override
public synchronized void save(T element) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(element.getType());
if (byType == null) {
byType = new HashMap<>();
this.elementMap.put(element.getType(), byType);
}
ArrayDeque<T> list = byType.get(element.getId());
// only allow add for existing id, if the existing one is "deleted"
if (list != null && !list.getLast().getVersion().isDeleted()) {
String msg = "An element already exists with the id {0}. Elements of the same class must always have a unique id, regardless of their type!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getId());
throw new StrolchPersistenceException(msg);
}
if (list == null) {
list = new ArrayDeque<>(2);
byType.put(element.getId(), list);
}
list.addLast(element);
}
@Override
public synchronized void saveAll(List<T> elements) {
for (T element : elements) {
save(element);
}
}
@Override
public synchronized void update(T element) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(element.getType());
if (byType == null) {
String msg = "The element does not yet exist with the type {0} and id {1}. Use add() for new objects!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getType(), element.getId());
throw new StrolchPersistenceException(msg);
}
ArrayDeque<T> list = byType.get(element.getId());
if (list == null) {
String msg = "The element does not yet exist with the type {0} and id {1}. Use add() for new objects!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getType(), element.getId());
throw new StrolchPersistenceException(msg);
}
if (!this.versioningEnabled)
list.clear();
list.addLast(element);
}
@Override
public synchronized void updateAll(List<T> elements) {
for (T element : elements) {
update(element);
}
}
@Override
public synchronized void remove(T element) {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(element.getType());
if (byType != null) {
byType.remove(element.getId());
if (byType.isEmpty()) {
this.elementMap.remove(element.getType());
}
}
}
@Override
public synchronized void removeAll(List<T> elements) {
for (T element : elements) {
remove(element);
}
}
@Override
public synchronized long removeAll() {
long removed = 0;
Set<String> keySet = new HashSet<>(this.elementMap.keySet());
for (String type : keySet) {
Map<String, ArrayDeque<T>> byType = this.elementMap.remove(type);
removed += byType.size();
byType.clear();
}
return removed;
}
@Override
public synchronized long removeAllBy(String type) {
Map<String, ArrayDeque<T>> byType = this.elementMap.remove(type);
if (byType == null)
return 0;
long removed = byType.size();
byType.clear();
return removed;
}
@Override
public synchronized void removeVersion(T element) throws StrolchPersistenceException {
Map<String, ArrayDeque<T>> byType = this.elementMap.get(element.getType());
if (byType == null) {
String msg = "The element does not yet exist with the type {0}!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getType());
throw new StrolchPersistenceException(msg);
}
ArrayDeque<T> list = byType.get(element.getId());
if (list == null) {
String msg = "The element does not yet exist with the type {0} and id {1}!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, element.getType(), element.getId());
throw new StrolchPersistenceException(msg);
}
T last = list.getLast();
if (!last.getVersion().equals(element.getVersion())) {
String msg = "The current version {0} is not the same as the version to remove {1}!"; //$NON-NLS-1$
msg = MessageFormat.format(msg, last.getVersion(), element.getVersion());
throw new StrolchPersistenceException(msg);
}
list.removeLast();
if (list.isEmpty()) {
byType.remove(element.getId());
}
}
@Override
public void flush() {
// nothing to do
}
}

View File

@ -1,117 +0,0 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.persistence.inmemory;
import java.util.HashMap;
import java.util.Map;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.StrolchRealm;
import li.strolch.persistence.api.ActivityDao;
import li.strolch.persistence.api.AuditDao;
import li.strolch.persistence.api.OrderDao;
import li.strolch.persistence.api.PersistenceHandler;
import li.strolch.persistence.api.ResourceDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
public class InMemoryPersistence implements PersistenceHandler {
private boolean versioningEnabled;
private Map<String, DaoCache> daoCache;
private ComponentContainer container;
public InMemoryPersistence(ComponentContainer container, boolean versioningEnabled) {
this.container = container;
this.versioningEnabled = versioningEnabled;
this.daoCache = new HashMap<>();
}
@Override
public StrolchTransaction openTx(StrolchRealm realm, Certificate certificate, String action) {
return new InMemoryTransaction(this.container, realm, certificate, action, this);
}
@Override
public OrderDao getOrderDao(StrolchTransaction tx) {
DaoCache daoCache = getDaoCache(tx);
return daoCache.getOrderDao();
}
@Override
public ResourceDao getResourceDao(StrolchTransaction tx) {
DaoCache daoCache = getDaoCache(tx);
return daoCache.getResourceDao();
}
@Override
public ActivityDao getActivityDao(StrolchTransaction tx) {
DaoCache daoCache = getDaoCache(tx);
return daoCache.getActivityDao();
}
@Override
public AuditDao getAuditDao(StrolchTransaction tx) {
DaoCache daoCache = getDaoCache(tx);
return daoCache.getAuditDao();
}
@Override
public void performDbInitialization() {
// no-op
}
private synchronized DaoCache getDaoCache(StrolchTransaction tx) {
DaoCache daoCache = this.daoCache.get(tx.getRealmName());
if (daoCache == null) {
daoCache = new DaoCache(new InMemoryOrderDao(this.versioningEnabled),
new InMemoryResourceDao(this.versioningEnabled), new InMemoryActivityDao(this.versioningEnabled),
new InMemoryAuditDao());
this.daoCache.put(tx.getRealmName(), daoCache);
}
return daoCache;
}
private class DaoCache {
private OrderDao orderDao;
private ResourceDao resourceDao;
private ActivityDao activityDao;
private AuditDao auditDao;
public DaoCache(OrderDao orderDao, ResourceDao resourceDao, ActivityDao activityDao, AuditDao auditDao) {
this.orderDao = orderDao;
this.resourceDao = resourceDao;
this.activityDao = activityDao;
this.auditDao = auditDao;
}
public OrderDao getOrderDao() {
return this.orderDao;
}
public ResourceDao getResourceDao() {
return this.resourceDao;
}
public AuditDao getAuditDao() {
return this.auditDao;
}
public ActivityDao getActivityDao() {
return this.activityDao;
}
}
}

View File

@ -1,38 +0,0 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.persistence.inmemory;
import java.util.List;
import li.strolch.model.Resource;
import li.strolch.model.query.ResourceQuery;
import li.strolch.persistence.api.ResourceDao;
import li.strolch.runtime.query.inmemory.InMemoryQuery;
import li.strolch.runtime.query.inmemory.InMemoryResourceQueryVisitor;
public class InMemoryResourceDao extends InMemoryDao<Resource> implements ResourceDao {
public InMemoryResourceDao(boolean versioningEnabled) {
super(versioningEnabled);
}
@Override
public <U> List<U> doQuery(ResourceQuery<U> resourceQuery) {
InMemoryResourceQueryVisitor visitor = new InMemoryResourceQueryVisitor();
InMemoryQuery<Resource, U> query = visitor.visit(resourceQuery);
return query.doQuery(this);
}
}

View File

@ -15,12 +15,10 @@
*/
package li.strolch.runtime.configuration;
import static li.strolch.db.DbConstants.PROP_DB_IGNORE_REALM;
import static li.strolch.db.DbConstants.PROP_DB_PASSWORD;
import static li.strolch.db.DbConstants.PROP_DB_URL;
import static li.strolch.db.DbConstants.PROP_DB_USERNAME;
import static li.strolch.db.DbConstants.*;
import static li.strolch.runtime.StrolchConstants.makeRealmKey;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
@ -28,15 +26,12 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.StrolchRealm;
import li.strolch.persistence.api.StrolchPersistenceException;
import li.strolch.runtime.StrolchConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -50,10 +45,6 @@ public abstract class DbConnectionBuilder {
private ComponentContainer container;
private ComponentConfiguration configuration;
/**
* @param container
* @param persistenceHandlerConfiguration
*/
public DbConnectionBuilder(ComponentContainer container, ComponentConfiguration persistenceHandlerConfiguration) {
this.container = container;
this.configuration = persistenceHandlerConfiguration;

View File

@ -2,14 +2,18 @@ package li.strolch.runtime.privilege;
import li.strolch.privilege.handler.SystemAction;
import li.strolch.privilege.model.PrivilegeContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link SystemAction} to run {@link PrivilegedRunnable} as a system user
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class StrolchSystemAction extends SystemAction {
public static final Logger logger = LoggerFactory.getLogger(StrolchSystemAction.class);
private PrivilegedRunnable runnable;
public StrolchSystemAction(PrivilegedRunnable runnable) {
@ -18,6 +22,11 @@ public class StrolchSystemAction extends SystemAction {
@Override
public void execute(PrivilegeContext privilegeContext) {
this.runnable.run(privilegeContext);
try {
this.runnable.run(privilegeContext);
} catch (Exception e) {
logger.error("Failed to execute SystemAction for " + privilegeContext.getUsername() + " due to " + e
.getMessage(), e);
}
}
}

View File

@ -17,13 +17,14 @@ package li.strolch.runtime.query.inmemory;
import java.util.List;
import li.strolch.agent.api.AuditTrail;
import li.strolch.model.audit.Audit;
import li.strolch.persistence.api.AuditDao;
import li.strolch.persistence.api.StrolchTransaction;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public interface AuditNavigator {
public abstract List<Audit> navigate(AuditDao dao);
public List<Audit> navigate(StrolchTransaction tx, AuditTrail auditTrail);
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,8 +17,9 @@ package li.strolch.runtime.query.inmemory;
import java.util.List;
import li.strolch.agent.api.AuditTrail;
import li.strolch.model.audit.Audit;
import li.strolch.persistence.api.AuditDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.utils.collections.DateRange;
import li.strolch.utils.dbc.DBC;
@ -38,7 +39,7 @@ public class AuditTypeNavigator implements AuditNavigator {
}
@Override
public List<Audit> navigate(AuditDao dao) {
return dao.queryAll(this.type, this.dateRange);
public List<Audit> navigate(StrolchTransaction tx, AuditTrail auditTrail) {
return auditTrail.getAllElements(tx, this.type, this.dateRange);
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2015 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -40,7 +40,7 @@ public class InMemoryActivityQueryVisitor extends InMemoryQueryVisitor<Activity>
}
public <U> InMemoryQuery<Activity, U> visit(ActivityQuery<U> activityQuery) {
ActivityVisitor<U> activityVisitor = activityQuery.getActivityVisitor();
ActivityVisitor<U> activityVisitor = activityQuery.getVisitor();
DBC.PRE.assertNotNull("ActivityVisitor may not be null!", activityVisitor); //$NON-NLS-1$
activityQuery.accept(this);

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -18,14 +18,16 @@ package li.strolch.runtime.query.inmemory;
import java.util.ArrayList;
import java.util.List;
import li.strolch.agent.api.AuditTrail;
import li.strolch.model.audit.Audit;
import li.strolch.model.audit.AuditVisitor;
import li.strolch.persistence.inmemory.InMemoryAuditDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.utils.dbc.DBC;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
* @param <U>
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class InMemoryAuditQuery<U> {
@ -45,10 +47,10 @@ public class InMemoryAuditQuery<U> {
this.auditVisitor = auditVisitor;
}
public List<U> doQuery(InMemoryAuditDao dao) {
public List<U> doQuery(StrolchTransaction tx, AuditTrail auditTrail) {
List<U> result = new ArrayList<>();
List<Audit> elements = this.navigator.navigate(dao);
List<Audit> elements = this.navigator.navigate(tx, auditTrail);
elements.sort((a1, a2) -> a2.getDate().compareTo(a1.getDate()));

View File

@ -36,7 +36,7 @@ public class InMemoryAuditQueryVisitor<U> implements AuditQueryVisitor {
private List<AuditSelector> selectors;
public InMemoryAuditQuery<U> toInMemory(AuditQuery<U> auditQuery) {
AuditVisitor<U> auditVisitor = auditQuery.getAuditVisitor();
AuditVisitor<U> auditVisitor = auditQuery.getVisitor();
DBC.PRE.assertNotNull("auditVisitor", auditVisitor); //$NON-NLS-1$
this.selectors = new ArrayList<>();

View File

@ -41,7 +41,7 @@ public class InMemoryOrderQueryVisitor extends InMemoryQueryVisitor<Order> imple
}
public <U> InMemoryQuery<Order, U> visit(OrderQuery<U> orderQuery) {
OrderVisitor<U> orderVisitor = orderQuery.getOrderVisitor();
OrderVisitor<U> orderVisitor = orderQuery.getVisitor();
DBC.PRE.assertNotNull("OrderVisitor may not be null!", orderVisitor); //$NON-NLS-1$
orderQuery.accept(this);

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -15,15 +15,12 @@
*/
package li.strolch.runtime.query.inmemory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.*;
import li.strolch.agent.api.ElementMap;
import li.strolch.model.StrolchRootElement;
import li.strolch.model.visitor.StrolchElementVisitor;
import li.strolch.persistence.api.StrolchDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.utils.dbc.DBC;
/**
@ -36,10 +33,6 @@ public class InMemoryQuery<T extends StrolchRootElement, U> {
private StrolchElementVisitor<U> elementVisitor;
private Comparator<T> comparator;
public InMemoryQuery() {
// empty constructor
}
public InMemoryQuery(Navigator<T> navigator, Selector<T> selector, StrolchElementVisitor<U> elementVisitor,
Comparator<T> comparator) {
this.navigator = navigator;
@ -50,7 +43,7 @@ public class InMemoryQuery<T extends StrolchRootElement, U> {
/**
* @param navigator
* the navigator to set
* the navigator to set
*/
public void setNavigator(Navigator<T> navigator) {
this.navigator = navigator;
@ -58,7 +51,7 @@ public class InMemoryQuery<T extends StrolchRootElement, U> {
/**
* @param selector
* the selector to set
* the selector to set
*/
public void setSelector(Selector<T> selector) {
this.selector = selector;
@ -66,18 +59,18 @@ public class InMemoryQuery<T extends StrolchRootElement, U> {
/**
* @param elementVisitor
* the elementVisitor to set
* the elementVisitor to set
*/
public void setElementVisitor(StrolchElementVisitor<U> elementVisitor) {
this.elementVisitor = elementVisitor;
}
public List<U> doQuery(StrolchDao<T> dao) {
public List<U> doQuery(StrolchTransaction tx, ElementMap<T> elementMap) {
if (this.selector == null)
return Collections.emptyList();
List<T> elements = this.navigator.navigate(dao);
List<T> elements = this.navigator.navigate(tx, elementMap);
if (this.comparator != null)
elements.sort(this.comparator);

View File

@ -40,7 +40,7 @@ public class InMemoryResourceQueryVisitor extends InMemoryQueryVisitor<Resource>
}
public <U> InMemoryQuery<Resource, U> visit(ResourceQuery<U> resourceQuery) {
ResourceVisitor<U> resourceVisitor = resourceQuery.getResourceVisitor();
ResourceVisitor<U> resourceVisitor = resourceQuery.getVisitor();
DBC.PRE.assertNotNull("ResourceVisitor may not be null!", resourceVisitor); //$NON-NLS-1$
resourceQuery.accept(this);

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,13 +17,14 @@ package li.strolch.runtime.query.inmemory;
import java.util.List;
import li.strolch.agent.api.ElementMap;
import li.strolch.model.StrolchRootElement;
import li.strolch.persistence.api.StrolchDao;
import li.strolch.persistence.api.StrolchTransaction;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public interface Navigator<T extends StrolchRootElement> {
public List<T> navigate(StrolchDao<T> dao);
public <U extends ElementMap<T>> List<T> navigate(StrolchTransaction tx, U elementMap);
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,8 +17,9 @@ package li.strolch.runtime.query.inmemory;
import java.util.List;
import li.strolch.agent.api.ElementMap;
import li.strolch.model.StrolchRootElement;
import li.strolch.persistence.api.StrolchDao;
import li.strolch.persistence.api.StrolchTransaction;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -32,7 +33,7 @@ public abstract class StrolchTypeNavigator<T extends StrolchRootElement> impleme
}
@Override
public List<T> navigate(StrolchDao<T> dao) {
return dao.queryAll(this.type);
public <U extends ElementMap<T>> List<T> navigate(StrolchTransaction tx, U elementMap) {
return elementMap.getElementsBy(tx, this.type);
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2015 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -41,7 +41,7 @@ import li.strolch.utils.helper.StringHelper;
/**
* Basically you should use the RuntimeMock class in the testbase project, but to mitigate circular dependencies, in
* tests of the agent project we use this implementation
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class RuntimeMock implements AutoCloseable {
@ -110,12 +110,13 @@ public class RuntimeMock implements AutoCloseable {
throw new RuntimeException(msg);
}
logger.info(MessageFormat.format("Mocking runtime from {0} to {1}", this.srcPathF.getAbsolutePath(), //$NON-NLS-1$
this.targetPathF.getAbsolutePath()));
logger.info(
MessageFormat.format("Mocking runtime from {0} to {1}", this.srcPathF.getAbsolutePath(), //$NON-NLS-1$
this.targetPathF.getAbsolutePath()));
// setup the container
this.agent = new StrolchBootstrapper(getAppVersion()).setupByCopyingRoot("dev", this.srcPathF,
this.targetPathF);
this.agent = new StrolchBootstrapper(getAppVersion())
.setupByCopyingRoot("dev", this.srcPathF, this.targetPathF);
return this;
}
@ -160,7 +161,7 @@ public class RuntimeMock implements AutoCloseable {
return this;
}
public void run(StrolchRunnable runnable) {
public void run(StrolchRunnable runnable) throws Exception {
runnable.run(getAgent());
}
@ -180,7 +181,7 @@ public class RuntimeMock implements AutoCloseable {
}
}
public static void runInStrolch(String targetPath, String srcPath, StrolchRunnable runnable) {
public static void runInStrolch(String targetPath, String srcPath, StrolchRunnable runnable) throws Exception {
try (RuntimeMock runtimeMock = new RuntimeMock(targetPath, srcPath)) {
runtimeMock.mockRuntime();
runtimeMock.startContainer();
@ -201,6 +202,6 @@ public class RuntimeMock implements AutoCloseable {
public interface StrolchRunnable {
public void run(StrolchAgent agent);
public void run(StrolchAgent agent) throws Exception;
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -15,24 +15,15 @@
*/
package li.strolch.agent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static li.strolch.model.ModelGenerator.*;
import static org.junit.Assert.*;
import li.strolch.RuntimeMock;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.OrderMap;
import li.strolch.agent.api.ResourceMap;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.model.ModelGenerator;
import li.strolch.agent.api.*;
import li.strolch.model.Order;
import li.strolch.model.Resource;
import li.strolch.persistence.api.OrderDao;
import li.strolch.persistence.api.ResourceDao;
import li.strolch.model.activity.Activity;
import li.strolch.model.activity.TimeOrdering;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.runtime.StrolchConstants;
@ -40,31 +31,28 @@ import li.strolch.runtime.configuration.model.ResourceGeneratorHandlerTest;
import li.strolch.runtime.configuration.model.ServiceHandlerTest;
import li.strolch.runtime.configuration.model.ServiceResultTest;
import li.strolch.runtime.privilege.PrivilegeHandler;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("nls")
public class ComponentContainerTest {
public static final String PATH_REALM_CONTAINER = "src/test/resources/realmtest";
public static final String PATH_TRANSIENT_CONTAINER = "src/test/resources/transienttest";
public static final String PATH_TRANSACTIONAL_CONTAINER = "src/test/resources/transactionaltest";
public static final String PATH_CACHED_CONTAINER = "src/test/resources/cachedtest";
public static final String PATH_EMPTY_CONTAINER = "src/test/resources/emptytest";
public static final String PATH_MINIMAL_CONTAINER = "src/test/resources/minimaltest";
public static final String PATH_VERSIONING_CONTAINER = "src/test/resources/versioningtest";
public static final String PATH_REALM_RUNTIME = "target/realmtest/";
public static final String PATH_TRANSIENT_RUNTIME = "target/transienttest/";
public static final String PATH_TRANSACTIONAL_RUNTIME = "target/transactionaltest/";
public static final String PATH_CACHED_RUNTIME = "target/cachedtest/";
public static final String PATH_EMPTY_RUNTIME = "target/emptytest/";
protected static final Logger logger = LoggerFactory.getLogger(ComponentContainerTest.class);
@Test
public void shouldStartEmptyContainer() {
public void shouldStartEmptyContainer() throws Exception {
try {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, PATH_EMPTY_CONTAINER, agent -> testContainer(agent));
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, PATH_EMPTY_CONTAINER, ComponentContainerTest::testContainer);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
@ -72,10 +60,10 @@ public class ComponentContainerTest {
}
@Test
public void shouldStartTransientContainer() {
public void shouldStartTransientContainer() throws Exception {
try {
RuntimeMock.runInStrolch(PATH_TRANSIENT_RUNTIME, PATH_TRANSIENT_CONTAINER, agent -> testContainer(agent));
RuntimeMock.runInStrolch(PATH_TRANSIENT_RUNTIME, PATH_TRANSIENT_CONTAINER,
ComponentContainerTest::testContainer);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
@ -83,13 +71,9 @@ public class ComponentContainerTest {
}
@Test
public void shouldStartTransactionalContainer() {
public void shouldStartRealmTestContainer() throws Exception {
try {
RuntimeMock.runInStrolch(PATH_TRANSACTIONAL_RUNTIME, PATH_TRANSACTIONAL_CONTAINER, agent -> {
testPersistenceContainer(agent);
testElementMaps(agent);
});
RuntimeMock.runInStrolch(PATH_REALM_RUNTIME, PATH_REALM_CONTAINER, ComponentContainerTest::testContainer);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
@ -97,33 +81,7 @@ public class ComponentContainerTest {
}
@Test
public void shouldStartCachedContainer() {
try {
RuntimeMock.runInStrolch(PATH_CACHED_RUNTIME, PATH_CACHED_CONTAINER, agent -> {
testPersistenceContainer(agent);
testElementMaps(agent);
});
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
}
}
@Test
public void shouldStartRealmTestContainer() {
try {
RuntimeMock.runInStrolch(PATH_REALM_RUNTIME, PATH_REALM_CONTAINER, agent -> testContainer(agent));
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
}
}
@Test
public void shouldTestRealms() {
public void shouldTestRealms() throws Exception {
try {
RuntimeMock.runInStrolch(PATH_REALM_RUNTIME, PATH_REALM_CONTAINER, agent -> {
testContainer(agent);
@ -136,8 +94,7 @@ public class ComponentContainerTest {
}
@Test
public void shouldTestMinimal() {
public void shouldTestMinimal() throws Exception {
try {
RuntimeMock.runInStrolch(PATH_REALM_RUNTIME, PATH_MINIMAL_CONTAINER, agent -> {
ComponentContainer container = agent.getContainer();
@ -181,20 +138,29 @@ public class ComponentContainerTest {
Certificate certificate = login(agent);
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate, "test")) {
ResourceDao resourceDao = tx.getPersistenceHandler().getResourceDao(tx);
resourceDao.save(ModelGenerator.createResource("@testRes0", "Test Res", "Test"));
Resource queriedRes = resourceDao.queryBy("Test", "@testRes0");
tx.add(createResource("@testRes0", "Test Res", "Test"));
Resource queriedRes = tx.getResourceBy("Test", "@testRes0");
assertNotNull(queriedRes);
assertEquals("@testRes0", queriedRes.getId());
tx.commitOnClose();
}
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate, "test")) {
OrderDao orderDao = tx.getPersistenceHandler().getOrderDao(tx);
orderDao.save(ModelGenerator.createOrder("@testOrder0", "Test Order", "Test"));
Order queriedOrder = orderDao.queryBy("Test", "@testOrder0");
tx.add(createOrder("@testOrder0", "Test Order", "Test"));
Order queriedOrder = tx.getOrderBy("Test", "@testOrder0");
assertNotNull(queriedOrder);
assertEquals("@testOrder0", queriedOrder.getId());
tx.commitOnClose();
}
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate, "test")) {
tx.add(createActivity("@testActivity0", "Test Activity", "Test", TimeOrdering.SERIES));
Activity queriedActivity = tx.getActivityBy("Test", "@testActivity0");
assertNotNull(queriedActivity);
assertEquals("@testActivity0", queriedActivity.getId());
tx.commitOnClose();
}
}
@ -206,19 +172,31 @@ public class ComponentContainerTest {
Certificate certificate = login(agent);
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate, "test")) {
ResourceMap resourceMap = tx.getResourceMap();
resourceMap.add(tx, ModelGenerator.createResource("@testRes1", "Test Res", "Test"));
resourceMap.add(tx, createResource("@testRes1", "Test Res", "Test"));
Resource queriedRes = resourceMap.getBy(tx, "Test", "@testRes1");
assertNotNull(queriedRes);
assertEquals("@testRes1", queriedRes.getId());
tx.commitOnClose();
}
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate, "test")) {
OrderMap orderMap = tx.getOrderMap();
orderMap.add(tx, ModelGenerator.createOrder("@testOrder1", "Test Order", "Test"));
orderMap.add(tx, createOrder("@testOrder1", "Test Order", "Test"));
Order queriedOrder = orderMap.getBy(tx, "Test", "@testOrder1");
assertNotNull(queriedOrder);
assertEquals("@testOrder1", queriedOrder.getId());
tx.commitOnClose();
}
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate, "test")) {
ActivityMap activityMap = tx.getActivityMap();
activityMap.add(tx, createActivity("@testActivity0", "Test Activity", "Test", TimeOrdering.SERIES));
Activity queriedActivity = activityMap.getBy(tx, "Test", "@testActivity0");
assertNotNull(queriedActivity);
assertEquals("@testActivity0", queriedActivity.getId());
tx.commitOnClose();
}
}
@ -230,16 +208,23 @@ public class ComponentContainerTest {
Certificate certificate = login(agent);
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate, "test")) {
ResourceMap resourceMap = tx.getResourceMap();
resourceMap.add(tx, ModelGenerator.createResource("@testRes1", "Test Res", "Test"));
resourceMap.add(tx, createResource("@testRes1", "Test Res", "Test"));
Resource queriedRes = resourceMap.getBy(tx, "Test", "@testRes1");
assertNotNull(queriedRes);
assertEquals("@testRes1", queriedRes.getId());
OrderMap orderMap = tx.getOrderMap();
orderMap.add(tx, ModelGenerator.createOrder("@testOrder1", "Test Order", "Test"));
orderMap.add(tx, createOrder("@testOrder1", "Test Order", "Test"));
Order queriedOrder = orderMap.getBy(tx, "Test", "@testOrder1");
assertNotNull(queriedOrder);
assertEquals("@testOrder1", queriedOrder.getId());
ActivityMap activityMap = tx.getActivityMap();
activityMap.add(tx, createActivity("@testActivity0", "Test Activity", "Test", TimeOrdering.SERIES));
Activity queriedActivity = activityMap.getBy(tx, "Test", "@testActivity0");
assertNotNull(queriedActivity);
assertEquals("@testActivity0", queriedActivity.getId());
tx.commitOnClose();
}
@ -257,8 +242,17 @@ public class ComponentContainerTest {
assertEquals("MyRealmOrder", myRealmOrder.getId());
Order otherRealmOrder = orderMap.getBy(tx, "TestType", "OtherRealmOrder");
assertNull(otherRealmOrder);
ActivityMap activityMap = tx.getActivityMap();
Activity myRealmAct = activityMap.getBy(tx, "TestType", "MyRealmAct");
assertNotNull(myRealmAct);
assertEquals("MyRealmAct", myRealmAct.getId());
Activity otherRealmAct = activityMap.getBy(tx, "TestType", "OtherRealmAct");
assertNull(otherRealmAct);
tx.commitOnClose();
}
try (StrolchTransaction tx = container.getRealm("otherRealm").openTx(certificate, "test")) {
ResourceMap resourceMap = tx.getResourceMap();
Resource otherRealmRes = resourceMap.getBy(tx, "TestType", "OtherRealmRes");
@ -274,6 +268,15 @@ public class ComponentContainerTest {
Order myRealmOrder = orderMap.getBy(tx, "TestType", "MyRealmOrder");
assertNull(myRealmOrder);
tx.commitOnClose();
ActivityMap activityMap = tx.getActivityMap();
Activity otherRealmAct = activityMap.getBy(tx, "TestType", "OtherRealmAct");
assertNotNull(otherRealmAct);
assertEquals("OtherRealmAct", otherRealmAct.getId());
Activity myRealmAct = activityMap.getBy(tx, "TestType", "MyRealmAct");
assertNull(myRealmAct);
tx.commitOnClose();
}
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -38,7 +38,7 @@ import li.strolch.agent.impl.DataStoreMode;
public class RealmTest {
@Test
public void shouldStartRealmTestContainer() {
public void shouldStartRealmTestContainer() throws Exception {
try {
RuntimeMock.runInStrolch(PATH_REALM_RUNTIME, PATH_REALM_CONTAINER, agent -> {
@ -46,17 +46,15 @@ public class RealmTest {
ComponentContainer container = agent.getContainer();
Set<String> realmNames = container.getRealmNames();
assertEquals(6, realmNames.size());
assertEquals(4, realmNames.size());
Set<String> expectedRealmNames = new HashSet<>(Arrays.asList("defaultRealm", "myRealm", "otherRealm",
"cachedRealm", "transactionalRealm", "emptyRealm"));
Set<String> expectedRealmNames = new HashSet<>(
Arrays.asList("defaultRealm", "myRealm", "otherRealm", "emptyRealm"));
assertEquals(expectedRealmNames, realmNames);
assertEquals(DataStoreMode.TRANSIENT, container.getRealm("defaultRealm").getMode());
assertEquals(DataStoreMode.TRANSIENT, container.getRealm("myRealm").getMode());
assertEquals(DataStoreMode.TRANSIENT, container.getRealm("otherRealm").getMode());
assertEquals(DataStoreMode.CACHED, container.getRealm("cachedRealm").getMode());
assertEquals(DataStoreMode.TRANSACTIONAL, container.getRealm("transactionalRealm").getMode());
assertEquals(DataStoreMode.EMPTY, container.getRealm("emptyRealm").getMode());
});
} catch (Exception e) {

View File

@ -1,12 +1,12 @@
/*
* Copyright 2015 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -37,7 +37,7 @@ public class PolicyHandlerTest {
public static final String PATH_EMPTY_RUNTIME = "target/PolicyHandlerTest/"; //$NON-NLS-1$
@Test
public void shouldInstantiatePolicies() {
public void shouldInstantiatePolicies() throws Exception {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, ComponentContainerTest.PATH_TRANSIENT_CONTAINER, agent -> {
@ -45,8 +45,8 @@ public class PolicyHandlerTest {
ComponentContainer container = agent.getContainer();
Certificate certificate = container.getPrivilegeHandler().authenticate("test", "test".toCharArray());
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
Resource res = tx.getResourceBy("TestType", "MyTestResource");

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -34,7 +34,7 @@ public class EnumHandlerTest {
private static final String ENUM_HANDLER_TEST_RUNTIME = "target/EnumHandlerTest/";
@Test
public void shouldFindByLocator() {
public void shouldFindByLocator() throws Exception {
RuntimeMock.runInStrolch(ENUM_HANDLER_TEST_RUNTIME, ComponentContainerTest.PATH_TRANSIENT_CONTAINER, agent -> {

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -15,30 +15,27 @@
*/
package li.strolch.runtime.query.inmemory;
import static li.strolch.agent.ComponentContainerTest.PATH_REALM_CONTAINER;
import static org.junit.Assert.assertEquals;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.*;
import li.strolch.RuntimeMock;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.model.ModelGenerator;
import li.strolch.model.Tags;
import li.strolch.model.audit.AccessType;
import li.strolch.model.audit.Audit;
import li.strolch.model.audit.AuditQuery;
import li.strolch.model.audit.AuditVisitor;
import li.strolch.model.audit.NoStrategyAuditVisitor;
import li.strolch.persistence.inmemory.InMemoryAuditDao;
import li.strolch.model.audit.*;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.runtime.StrolchConstants;
import li.strolch.runtime.privilege.PrivilegeHandler;
import li.strolch.utils.StringMatchMode;
import li.strolch.utils.collections.DateRange;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -46,12 +43,16 @@ import org.junit.Test;
@SuppressWarnings("nls")
public class AuditQueryTest {
public static final String PATH_RUNTIME = "target/" + AuditQueryTest.class.getSimpleName();
private static Date past;
private static Date earlier;
private static Date current;
private static Date later;
private static Date future;
protected static final Logger logger = LoggerFactory.getLogger(AuditQueryTest.class);
@BeforeClass
public static void beforeClass() throws SQLException {
@ -69,112 +70,141 @@ public class AuditQueryTest {
future = cal.getTime();
}
@Test
public void shouldQueryTypeAndDateRange() throws SQLException {
AuditVisitor<Audit> visitor = new NoStrategyAuditVisitor();
AuditQuery<Audit> query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(earlier, true).to(later,
true));
performQuery(query, Arrays.asList(0L, 1L, 2L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(current, true).to(current, true));
performQuery(query, Arrays.asList(1L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(current, true));
performQuery(query, Arrays.asList(1L, 2L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().to(current, true));
performQuery(query, Arrays.asList(0L, 1L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.RESOURCE, new DateRange().from(past, true).to(future, true));
performQuery(query, Arrays.<Long> asList());
private static Certificate login(StrolchAgent agent) {
PrivilegeHandler privilegeHandler = agent.getContainer().getPrivilegeHandler();
return privilegeHandler.authenticate("test", "test".toCharArray());
}
@Test
public void shouldQueryAudits() throws SQLException {
public void shouldQueryTypeAndDateRange() throws Exception {
try {
RuntimeMock.runInStrolch(PATH_RUNTIME, PATH_REALM_CONTAINER, agent -> {
AuditVisitor<Audit> visitor = new NoStrategyAuditVisitor();
AuditVisitor<Audit> visitor = new NoStrategyAuditVisitor();
AuditQuery<Audit> query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future,
true));
query.action().accessTypes(AccessType.CREATE, AccessType.READ);
performQuery(query, Arrays.asList(0L, 1L, 4L));
AuditQuery<Audit> query = new AuditQuery<>(visitor, Tags.AUDIT,
new DateRange().from(earlier, true).to(later, true));
performQuery(agent, query, Arrays.asList(0L, 1L, 2L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.action().accessTypes(AccessType.CREATE);
performQuery(query, Arrays.asList(0L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(current, true).to(current, true));
performQuery(agent, query, Arrays.asList(1L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.action().accessTypes(AccessType.CREATE, AccessType.READ)
.actions(StringMatchMode.EQUALS_CASE_SENSITIVE, "create", "read");
performQuery(query, Arrays.asList(0L, 1L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(current, true));
performQuery(agent, query, Arrays.asList(1L, 2L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.action().accessTypes(AccessType.CREATE, AccessType.READ)
.actions(StringMatchMode.EQUALS_CASE_SENSITIVE, "read");
performQuery(query, Arrays.asList(1L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().to(current, true));
performQuery(agent, query, Arrays.asList(0L, 1L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementAccessed(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "crea");
performQuery(query, Arrays.asList(0L, 4L));
query = new AuditQuery<>(visitor, Tags.RESOURCE, new DateRange().from(past, true).to(future, true));
performQuery(agent, query, Arrays.<Long>asList());
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementAccessed(StringMatchMode.CONTAINS_CASE_SENSITIVE, "crea");
performQuery(query, Arrays.<Long> asList());
});
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementAccessed(StringMatchMode.EQUALS_CASE_INSENSITIVE, "create");
performQuery(query, Arrays.asList(0L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().usernames(StringMatchMode.EQUALS_CASE_INSENSITIVE, "earlier");
performQuery(query, Arrays.asList(0L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().usernames(StringMatchMode.EQUALS_CASE_INSENSITIVE, "earlier", "later");
performQuery(query, Arrays.asList(0L, 2L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().usernames(StringMatchMode.EQUALS_CASE_INSENSITIVE, "earlier")
.firstnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "enn");
performQuery(query, Arrays.asList(0L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().usernames(StringMatchMode.EQUALS_CASE_INSENSITIVE, "earlier")
.firstnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "enn")
.lastnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "kennedy");
performQuery(query, Arrays.asList(0L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().firstnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "enn")
.lastnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "kennedy");
performQuery(query, Arrays.asList(0L, 1L, 2L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementSubTypes(StringMatchMode.EQUALS_CASE_SENSITIVE, "Foo");
performQuery(query, Arrays.asList(0L, 1L, 2L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementSubTypes(StringMatchMode.EQUALS_CASE_SENSITIVE, "Bar");
performQuery(query, Arrays.asList());
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.limit(1).element().elementSubTypes(StringMatchMode.EQUALS_CASE_SENSITIVE, "Foo");
performQuery(query, Arrays.asList(2L));
}
private void performQuery(AuditQuery<Audit> query, List<Long> expected) throws SQLException {
InMemoryAuditDao dao = new InMemoryAuditDao();
dao.saveAll(getAudits());
List<Audit> result = dao.doQuery(query);
Set<Long> ids = new HashSet<>();
for (Audit audit : result) {
ids.add(audit.getId());
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
}
}
@Test
public void shouldQueryAudits() throws Exception {
try {
RuntimeMock.runInStrolch(PATH_RUNTIME, PATH_REALM_CONTAINER, agent -> {
AuditVisitor<Audit> visitor = new NoStrategyAuditVisitor();
AuditQuery<Audit> query = new AuditQuery<>(visitor, Tags.AUDIT,
new DateRange().from(past, true).to(future, true));
query.action().accessTypes(AccessType.CREATE, AccessType.READ);
performQuery(agent, query, Arrays.asList(0L, 1L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.action().accessTypes(AccessType.CREATE);
performQuery(agent, query, Arrays.asList(0L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.action().accessTypes(AccessType.CREATE, AccessType.READ)
.actions(StringMatchMode.EQUALS_CASE_SENSITIVE, "create", "read");
performQuery(agent, query, Arrays.asList(0L, 1L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.action().accessTypes(AccessType.CREATE, AccessType.READ)
.actions(StringMatchMode.EQUALS_CASE_SENSITIVE, "read");
performQuery(agent, query, Arrays.asList(1L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementAccessed(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "crea");
performQuery(agent, query, Arrays.asList(0L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementAccessed(StringMatchMode.CONTAINS_CASE_SENSITIVE, "crea");
performQuery(agent, query, Arrays.<Long>asList());
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementAccessed(StringMatchMode.EQUALS_CASE_INSENSITIVE, "create");
performQuery(agent, query, Arrays.asList(0L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().usernames(StringMatchMode.EQUALS_CASE_INSENSITIVE, "earlier");
performQuery(agent, query, Arrays.asList(0L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().usernames(StringMatchMode.EQUALS_CASE_INSENSITIVE, "earlier", "later");
performQuery(agent, query, Arrays.asList(0L, 2L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().usernames(StringMatchMode.EQUALS_CASE_INSENSITIVE, "earlier")
.firstnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "enn");
performQuery(agent, query, Arrays.asList(0L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().usernames(StringMatchMode.EQUALS_CASE_INSENSITIVE, "earlier")
.firstnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "enn")
.lastnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "kennedy");
performQuery(agent, query, Arrays.asList(0L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.identity().firstnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "enn")
.lastnames(StringMatchMode.CONTAINS_CASE_INSENSITIVE, "kennedy");
performQuery(agent, query, Arrays.asList(0L, 1L, 2L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementSubTypes(StringMatchMode.EQUALS_CASE_SENSITIVE, "Foo");
performQuery(agent, query, Arrays.asList(0L, 1L, 2L, 3L, 4L));
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.element().elementSubTypes(StringMatchMode.EQUALS_CASE_SENSITIVE, "Bar");
performQuery(agent, query, Arrays.asList());
query = new AuditQuery<>(visitor, Tags.AUDIT, new DateRange().from(past, true).to(future, true));
query.limit(1).element().elementSubTypes(StringMatchMode.EQUALS_CASE_SENSITIVE, "Foo");
performQuery(agent, query, Arrays.asList(2L));
});
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw e;
}
}
private void performQuery(StrolchAgent agent, AuditQuery<Audit> query, List<Long> expected) throws SQLException {
Certificate certificate = login(agent);
try (StrolchTransaction tx = agent.getContainer().getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
tx.setSuppressAudits(true);
tx.getAuditTrail().addAll(tx, getAudits());
List<Audit> result = tx.doQuery(query);
Set<Long> ids = new HashSet<>();
for (Audit audit : result) {
ids.add(audit.getId());
}
assertEquals(new HashSet<>(expected), new HashSet<>(ids));
}
assertEquals(new HashSet<>(expected), new HashSet<>(ids));
}
private static List<Audit> getAudits() {

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -57,7 +57,7 @@ public class FindByLocatorTest {
}
@Test
public void shouldFindByResource() {
public void shouldFindByResource() throws Exception {
runtimeMock.run(agent -> {
try (StrolchTransaction tx = agent.getContainer().getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
@ -79,7 +79,8 @@ public class FindByLocatorTest {
resStringParam);
// TimedState on Resource
Locator locResIntegerState = Locator.valueOf("Resource/TestType/MyTestResource/TimedState/@integerState");
Locator locResIntegerState = Locator
.valueOf("Resource/TestType/MyTestResource/TimedState/@integerState");
IntegerTimedState integerS = tx.findElement(locResIntegerState);
assertNotNull("Should have found a IntegerTimedState with the locator " + locResIntegerState, integerS);
@ -88,7 +89,7 @@ public class FindByLocatorTest {
}
@Test
public void shouldFindByOrder() {
public void shouldFindByOrder() throws Exception {
runtimeMock.run(agent -> {
try (StrolchTransaction tx = agent.getContainer().getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
@ -113,7 +114,7 @@ public class FindByLocatorTest {
}
@Test
public void shouldFindByActivity() {
public void shouldFindByActivity() throws Exception {
runtimeMock.run(agent -> {
try (StrolchTransaction tx = agent.getContainer().getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
@ -137,7 +138,7 @@ public class FindByLocatorTest {
}
@Test
public void shouldFindByAction() {
public void shouldFindByAction() throws Exception {
runtimeMock.run(agent -> {
try (StrolchTransaction tx = agent.getContainer().getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {

View File

@ -1,12 +1,7 @@
package li.strolch.runtime.query.inmemory;
import static li.strolch.model.query.ParameterSelection.booleanSelection;
import static li.strolch.model.query.ParameterSelection.floatListSelection;
import static li.strolch.model.query.ParameterSelection.floatSelection;
import static li.strolch.model.query.ParameterSelection.integerListSelection;
import static li.strolch.model.query.ParameterSelection.longListSelection;
import static li.strolch.model.query.ParameterSelection.stringListSelection;
import static li.strolch.model.query.ParameterSelection.stringSelection;
import static li.strolch.agent.ComponentContainerTest.PATH_EMPTY_CONTAINER;
import static li.strolch.model.query.ParameterSelection.*;
import static li.strolch.utils.StringMatchMode.ci;
import static li.strolch.utils.StringMatchMode.es;
import static org.junit.Assert.assertEquals;
@ -15,8 +10,8 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import li.strolch.RuntimeMock;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.model.ModelGenerator;
import li.strolch.model.ParameterBag;
import li.strolch.model.State;
@ -24,268 +19,281 @@ import li.strolch.model.Version;
import li.strolch.model.activity.Action;
import li.strolch.model.activity.Activity;
import li.strolch.model.activity.TimeOrdering;
import li.strolch.model.parameter.BooleanParameter;
import li.strolch.model.parameter.FloatListParameter;
import li.strolch.model.parameter.FloatParameter;
import li.strolch.model.parameter.IntegerListParameter;
import li.strolch.model.parameter.LongListParameter;
import li.strolch.model.parameter.StringListParameter;
import li.strolch.model.parameter.StringParameter;
import li.strolch.model.query.ActivityQuery;
import li.strolch.model.query.ActivityStateSelection;
import li.strolch.model.query.IdSelection;
import li.strolch.model.query.NameSelection;
import li.strolch.model.query.ParameterSelection;
import li.strolch.persistence.inmemory.InMemoryActivityDao;
import li.strolch.model.parameter.*;
import li.strolch.model.query.*;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.runtime.StrolchConstants;
import li.strolch.runtime.privilege.PrivilegeHandler;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class InMemoryActivityQueryTest {
protected InMemoryActivityDao daoInstance() {
return new InMemoryActivityDao(false);
public static final String PATH_RUNTIME = "target/" + InMemoryActivityQueryTest.class.getSimpleName();
private static RuntimeMock runtimeMock;
private static Certificate certificate;
private static Certificate login(StrolchAgent agent) {
PrivilegeHandler privilegeHandler = agent.getContainer().getPrivilegeHandler();
return privilegeHandler.authenticate("test", "test".toCharArray());
}
@BeforeClass
public static void beforeClass() {
runtimeMock = new RuntimeMock(PATH_RUNTIME, PATH_EMPTY_CONTAINER);
runtimeMock.mockRuntime();
runtimeMock.startContainer();
certificate = login(runtimeMock.getAgent());
try (StrolchTransaction tx = openTx()) {
getActivities().forEach(tx::add);
tx.add(getBallActivity());
tx.commitOnClose();
}
}
private static StrolchTransaction openTx() {
return runtimeMock.getAgent().getContainer().getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test");
}
@AfterClass
public static void afterClass() {
if (runtimeMock != null)
runtimeMock.close();
}
@Test
public void shouldQueryById() {
List<Activity> activitys = getActivities();
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activitys);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> activityQuery = ActivityQuery.query("MyType1");
activityQuery.with(new IdSelection("@1"));
ActivityQuery<Activity> activityQuery = ActivityQuery.query("MyType1");
activityQuery.with(new IdSelection("@1"));
List<Activity> result = dao.doQuery(activityQuery);
assertEquals(1, result.size());
assertEquals("@1", result.get(0).getId());
List<Activity> result = tx.doQuery(activityQuery);
assertEquals(1, result.size());
assertEquals("@1", result.get(0).getId());
}
}
@Test
public void shouldQueryByIdOr() {
List<Activity> activitys = getActivities();
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activitys);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> activityQuery = ActivityQuery.query("MyType2");
activityQuery.or().with(new IdSelection("@3"), new IdSelection("@4"));
ActivityQuery<Activity> activityQuery = ActivityQuery.query("MyType2");
activityQuery.or().with(new IdSelection("@3"), new IdSelection("@4"));
List<Activity> result = dao.doQuery(activityQuery);
assertEquals(2, result.size());
assertEquals("@3", result.get(0).getId());
assertEquals("@4", result.get(1).getId());
List<Activity> result = tx.doQuery(activityQuery);
assertEquals(2, result.size());
assertEquals("@3", result.get(0).getId());
assertEquals("@4", result.get(1).getId());
}
}
@Test
public void shouldQueryByIdAnd() {
List<Activity> activitys = getActivities();
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activitys);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> activityQuery = ActivityQuery.query("MyType2");
activityQuery.and().with(new IdSelection("@3"), new NameSelection("Activity 3", es()));
ActivityQuery<Activity> activityQuery = ActivityQuery.query("MyType2");
activityQuery.and().with(new IdSelection("@3"), new NameSelection("Activity 3", es()));
List<Activity> result = dao.doQuery(activityQuery);
assertEquals(1, result.size());
assertEquals("@3", result.get(0).getId());
List<Activity> result = tx.doQuery(activityQuery);
assertEquals(1, result.size());
assertEquals("@3", result.get(0).getId());
}
}
@Test
public void shouldNotQueryByIdAnd() {
List<Activity> activitys = getActivities();
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activitys);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> activityQuery = ActivityQuery.query("MyType1");
activityQuery.and().with(new IdSelection("@3"), new NameSelection("@4", es()));
ActivityQuery<Activity> activityQuery = ActivityQuery.query("MyType1");
activityQuery.and().with(new IdSelection("@3"), new NameSelection("@4", es()));
List<Activity> result = dao.doQuery(activityQuery);
assertEquals(0, result.size());
List<Activity> result = tx.doQuery(activityQuery);
assertEquals(0, result.size());
}
}
@Test
public void shouldQueryByParameter() {
List<Activity> activitys = getActivities();
activitys.add(getBallActivity());
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activitys);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(
//
stringSelection("parameters", "color", "red", es()),
booleanSelection("parameters", "forChildren", true), floatSelection("parameters", "diameter", 22.0));
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(
//
stringSelection("parameters", "color", "red", es()),
booleanSelection("parameters", "forChildren", true),
floatSelection("parameters", "diameter", 22.0));
List<Activity> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Activity> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByListParameter() {
List<Activity> activitys = getActivities();
activitys.add(getBallActivity());
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activitys);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> ballQuery;
List<Activity> result;
ActivityQuery<Activity> ballQuery;
List<Activity> result;
// string list
{
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a", "z")));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// string list
{
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a", "z")));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a")));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a")));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("c", "b", "a")));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
}
ballQuery = ActivityQuery.query("Ball");
ballQuery.and()
.with(stringListSelection("parameters", "stringListValues", Arrays.asList("c", "b", "a")));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
// integer list
{
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1, 5)));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// integer list
{
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1, 5)));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(3, 2, 1)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
}
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(3, 2, 1)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
// float list
{
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0, 8.0)));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// float list
{
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0, 8.0)));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(6.2, 5.1, 4.0)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
}
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(6.2, 5.1, 4.0)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
// long list
{
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L, 11L)));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// long list
{
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L, 11L)));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(10L, 9L, 8L)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(10L, 9L, 8L)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
}
@Test
public void shouldQueryByNullParameter1() {
List<Activity> activitys = getActivities();
activitys.add(getBallActivity());
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activitys);
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "color"));
try (StrolchTransaction tx = openTx()) {
List<Activity> result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "color"));
List<Activity> result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
}
}
@Test
public void shouldQueryByNullParameter2() {
List<Activity> activitys = getActivities();
activitys.add(getBallActivity());
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activitys);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
List<Activity> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Activity> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByNullParameter3() {
List<Activity> activitys = getActivities();
activitys.add(getBallActivity());
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activitys);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
List<Activity> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Activity> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByName() {
List<Activity> activities = getActivities();
activities.add(getBallActivity());
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activities);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.with(new NameSelection("ball ", ci()));
ActivityQuery<Activity> ballQuery = ActivityQuery.query("Ball");
ballQuery.with(new NameSelection("ball ", ci()));
List<Activity> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Activity> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByState() {
List<Activity> activities = getActivities();
InMemoryActivityDao dao = daoInstance();
dao.saveAll(activities);
try (StrolchTransaction tx = openTx()) {
ActivityQuery<Activity> ballQuery = ActivityQuery.query("MyType1");
ballQuery.with(new ActivityStateSelection(State.STOPPED));
ActivityQuery<Activity> ballQuery = ActivityQuery.query("MyType1");
ballQuery.with(new ActivityStateSelection(State.STOPPED));
List<Activity> result = dao.doQuery(ballQuery);
assertEquals(2, result.size());
List<Activity> result = tx.doQuery(ballQuery);
assertEquals(2, result.size());
ballQuery = ActivityQuery.query("MyType2");
ballQuery.with(new ActivityStateSelection(State.STOPPED));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ActivityQuery.query("MyType2");
ballQuery.with(new ActivityStateSelection(State.STOPPED));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
private Activity getBallActivity() {
private static Activity getBallActivity() {
Activity res1 = new Activity("childrensBall", "Ball 1", "Ball", TimeOrdering.SERIES);
Version.setInitialVersionFor(res1, -1, "test");
ParameterBag bag = new ParameterBag("parameters", "Ball Details", "Parameters");
@ -302,7 +310,7 @@ public class InMemoryActivityQueryTest {
return res1;
}
private List<Activity> getActivities() {
private static List<Activity> getActivities() {
Activity activity1 = ModelGenerator.createActivity("@1", "Activity 1", "MyType1", TimeOrdering.SERIES);
((Action) activity1.getElement("action_" + activity1.getId())).setState(State.STOPPED);
@ -322,18 +330,18 @@ public class InMemoryActivityQueryTest {
Activity activity6 = ModelGenerator.createActivity("@6", "Activity 6", "MyType3", TimeOrdering.SERIES);
((Action) activity6.getElement("action_" + activity6.getId())).setState(State.CLOSED);
List<Activity> activitys = new ArrayList<>();
activitys.add(activity1);
activitys.add(activity2);
activitys.add(activity3);
activitys.add(activity4);
activitys.add(activity5);
activitys.add(activity6);
List<Activity> activities = new ArrayList<>();
activities.add(activity1);
activities.add(activity2);
activities.add(activity3);
activities.add(activity4);
activities.add(activity5);
activities.add(activity6);
for (Activity activity : activitys) {
for (Activity activity : activities) {
Version.setInitialVersionFor(activity, -1, "test");
}
return activitys;
return activities;
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -15,13 +15,8 @@
*/
package li.strolch.runtime.query.inmemory;
import static li.strolch.model.query.ParameterSelection.booleanSelection;
import static li.strolch.model.query.ParameterSelection.floatListSelection;
import static li.strolch.model.query.ParameterSelection.floatSelection;
import static li.strolch.model.query.ParameterSelection.integerListSelection;
import static li.strolch.model.query.ParameterSelection.longListSelection;
import static li.strolch.model.query.ParameterSelection.stringListSelection;
import static li.strolch.model.query.ParameterSelection.stringSelection;
import static li.strolch.agent.ComponentContainerTest.PATH_EMPTY_CONTAINER;
import static li.strolch.model.query.ParameterSelection.*;
import static li.strolch.utils.StringMatchMode.ci;
import static li.strolch.utils.StringMatchMode.es;
import static org.junit.Assert.assertEquals;
@ -31,279 +26,288 @@ import java.util.Arrays;
import java.util.Date;
import java.util.List;
import li.strolch.RuntimeMock;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.model.*;
import li.strolch.model.parameter.*;
import li.strolch.model.query.*;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.runtime.StrolchConstants;
import li.strolch.runtime.privilege.PrivilegeHandler;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import li.strolch.model.ModelGenerator;
import li.strolch.model.Order;
import li.strolch.model.ParameterBag;
import li.strolch.model.State;
import li.strolch.model.Version;
import li.strolch.model.parameter.BooleanParameter;
import li.strolch.model.parameter.FloatListParameter;
import li.strolch.model.parameter.FloatParameter;
import li.strolch.model.parameter.IntegerListParameter;
import li.strolch.model.parameter.LongListParameter;
import li.strolch.model.parameter.StringListParameter;
import li.strolch.model.parameter.StringParameter;
import li.strolch.model.query.IdSelection;
import li.strolch.model.query.NameSelection;
import li.strolch.model.query.OrderQuery;
import li.strolch.model.query.OrderStateSelection;
import li.strolch.model.query.ParameterSelection;
import li.strolch.persistence.inmemory.InMemoryOrderDao;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@SuppressWarnings("nls")
public class InMemoryOrderQueryTest {
protected InMemoryOrderDao daoInstance() {
return new InMemoryOrderDao(false);
public static final String PATH_RUNTIME = "target/" + InMemoryOrderQueryTest.class.getSimpleName();
private static RuntimeMock runtimeMock;
private static Certificate certificate;
private static Certificate login(StrolchAgent agent) {
PrivilegeHandler privilegeHandler = agent.getContainer().getPrivilegeHandler();
return privilegeHandler.authenticate("test", "test".toCharArray());
}
@BeforeClass
public static void beforeClass() {
runtimeMock = new RuntimeMock(PATH_RUNTIME, PATH_EMPTY_CONTAINER);
runtimeMock.mockRuntime();
runtimeMock.startContainer();
certificate = login(runtimeMock.getAgent());
try (StrolchTransaction tx = openTx()) {
getOrders().forEach(tx::add);
tx.add(getBallOrder());
tx.commitOnClose();
}
}
private static StrolchTransaction openTx() {
return runtimeMock.getAgent().getContainer().getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test");
}
@AfterClass
public static void afterClass() {
if (runtimeMock != null)
runtimeMock.close();
}
@Test
public void shouldQueryById() {
List<Order> orders = getOrders();
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> orderQuery = OrderQuery.query("MyType1");
orderQuery.with(new IdSelection("@1"));
OrderQuery<Order> orderQuery = OrderQuery.query("MyType1");
orderQuery.with(new IdSelection("@1"));
List<Order> result = dao.doQuery(orderQuery);
assertEquals(1, result.size());
assertEquals("@1", result.get(0).getId());
List<Order> result = tx.doQuery(orderQuery);
assertEquals(1, result.size());
assertEquals("@1", result.get(0).getId());
}
}
@Test
public void shouldQueryByIdOr() {
List<Order> orders = getOrders();
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> orderQuery = OrderQuery.query("MyType2");
orderQuery.or().with(new IdSelection("@3"), new IdSelection("@4"));
OrderQuery<Order> orderQuery = OrderQuery.query("MyType2");
orderQuery.or().with(new IdSelection("@3"), new IdSelection("@4"));
List<Order> result = dao.doQuery(orderQuery);
assertEquals(2, result.size());
assertEquals("@3", result.get(0).getId());
assertEquals("@4", result.get(1).getId());
List<Order> result = tx.doQuery(orderQuery);
assertEquals(2, result.size());
assertEquals("@3", result.get(0).getId());
assertEquals("@4", result.get(1).getId());
}
}
@Test
public void shouldQueryByIdAnd() {
List<Order> orders = getOrders();
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> orderQuery = OrderQuery.query("MyType2");
orderQuery.and().with(new IdSelection("@3"), new NameSelection("Order 3", es()));
OrderQuery<Order> orderQuery = OrderQuery.query("MyType2");
orderQuery.and().with(new IdSelection("@3"), new NameSelection("Order 3", es()));
List<Order> result = dao.doQuery(orderQuery);
assertEquals(1, result.size());
assertEquals("@3", result.get(0).getId());
List<Order> result = tx.doQuery(orderQuery);
assertEquals(1, result.size());
assertEquals("@3", result.get(0).getId());
}
}
@Test
public void shouldNotQueryByIdAnd() {
List<Order> orders = getOrders();
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> orderQuery = OrderQuery.query("MyType1");
orderQuery.and().with(new IdSelection("@3"), new NameSelection("@4", es()));
OrderQuery<Order> orderQuery = OrderQuery.query("MyType1");
orderQuery.and().with(new IdSelection("@3"), new NameSelection("@4", es()));
List<Order> result = dao.doQuery(orderQuery);
assertEquals(0, result.size());
List<Order> result = tx.doQuery(orderQuery);
assertEquals(0, result.size());
}
}
@Test
public void shouldQueryByParameter() {
List<Order> orders = getOrders();
orders.add(getBallOrder());
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(
//
stringSelection("parameters", "color", "red", es()),
booleanSelection("parameters", "forChildren", true), floatSelection("parameters", "diameter", 22.0));
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(
//
stringSelection("parameters", "color", "red", es()),
booleanSelection("parameters", "forChildren", true),
floatSelection("parameters", "diameter", 22.0));
List<Order> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Order> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByListParameter() {
List<Order> orders = getOrders();
orders.add(getBallOrder());
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> ballQuery;
List<Order> result;
OrderQuery<Order> ballQuery;
List<Order> result;
// string list
{
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a", "z")));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// string list
{
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a", "z")));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a")));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a")));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("c", "b", "a")));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
}
ballQuery = OrderQuery.query("Ball");
ballQuery.and()
.with(stringListSelection("parameters", "stringListValues", Arrays.asList("c", "b", "a")));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
// integer list
{
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1, 5)));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// integer list
{
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1, 5)));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(3, 2, 1)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
}
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(3, 2, 1)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
// float list
{
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0, 8.0)));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// float list
{
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0, 8.0)));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(6.2, 5.1, 4.0)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
}
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(6.2, 5.1, 4.0)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
// long list
{
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L, 11L)));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// long list
{
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L, 11L)));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(10L, 9L, 8L)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(10L, 9L, 8L)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
}
@Test
public void shouldQueryByNullParameter1() {
List<Order> orders = getOrders();
orders.add(getBallOrder());
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "color"));
try (StrolchTransaction tx = openTx()) {
List<Order> result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "color"));
List<Order> result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
}
}
@Test
public void shouldQueryByNullParameter2() {
List<Order> orders = getOrders();
orders.add(getBallOrder());
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
List<Order> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Order> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByNullParameter3() {
List<Order> orders = getOrders();
orders.add(getBallOrder());
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
List<Order> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Order> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByName() {
List<Order> orders = getOrders();
orders.add(getBallOrder());
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.with(new NameSelection("ball ", ci()));
OrderQuery<Order> ballQuery = OrderQuery.query("Ball");
ballQuery.with(new NameSelection("ball ", ci()));
List<Order> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Order> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByState() {
List<Order> orders = getOrders();
InMemoryOrderDao dao = daoInstance();
dao.saveAll(orders);
try (StrolchTransaction tx = openTx()) {
OrderQuery<Order> ballQuery = OrderQuery.query("MyType1");
ballQuery.with(new OrderStateSelection(State.STOPPED));
OrderQuery<Order> ballQuery = OrderQuery.query("MyType1");
ballQuery.with(new OrderStateSelection(State.STOPPED));
List<Order> result = dao.doQuery(ballQuery);
assertEquals(2, result.size());
List<Order> result = tx.doQuery(ballQuery);
assertEquals(2, result.size());
ballQuery = OrderQuery.query("MyType2");
ballQuery.with(new OrderStateSelection(State.STOPPED));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = OrderQuery.query("MyType2");
ballQuery.with(new OrderStateSelection(State.STOPPED));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
private Order getBallOrder() {
private static Order getBallOrder() {
Order o1 = new Order("childrensBall", "Ball 1", "Ball");
Version.setInitialVersionFor(o1, -1, "test");
ParameterBag bag = new ParameterBag("parameters", "Ball Details", "Parameters");
@ -320,7 +324,7 @@ public class InMemoryOrderQueryTest {
return o1;
}
private List<Order> getOrders() {
private static List<Order> getOrders() {
Order res1 = ModelGenerator.createOrder("@1", "Order 1", "MyType1", new Date(), State.STOPPED);
Order res2 = ModelGenerator.createOrder("@2", "Order 2", "MyType1", new Date(), State.STOPPED);
Order res3 = ModelGenerator.createOrder("@3", "Order 3", "MyType2", new Date(), State.STOPPED);

View File

@ -1,81 +0,0 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package li.strolch.runtime.query.inmemory;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.StrolchComponent;
import li.strolch.agent.api.StrolchRealm;
import li.strolch.persistence.api.ActivityDao;
import li.strolch.persistence.api.AuditDao;
import li.strolch.persistence.api.OrderDao;
import li.strolch.persistence.api.PersistenceHandler;
import li.strolch.persistence.api.ResourceDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.persistence.inmemory.InMemoryPersistence;
import li.strolch.privilege.model.Certificate;
import li.strolch.runtime.configuration.ComponentConfiguration;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class InMemoryPersistenceHandler extends StrolchComponent implements PersistenceHandler {
private InMemoryPersistence persistence;
/**
* @param container
* @param componentName
*/
public InMemoryPersistenceHandler(ComponentContainer container, String componentName) {
super(container, componentName);
}
@Override
public void initialize(ComponentConfiguration configuration) throws Exception {
this.persistence = new InMemoryPersistence(getContainer(), false);
super.initialize(configuration);
}
@Override
public StrolchTransaction openTx(StrolchRealm realm, Certificate certificate, String action) {
return this.persistence.openTx(realm, certificate, action);
}
@Override
public OrderDao getOrderDao(StrolchTransaction tx) {
return this.persistence.getOrderDao(tx);
}
@Override
public ResourceDao getResourceDao(StrolchTransaction tx) {
return this.persistence.getResourceDao(tx);
}
@Override
public ActivityDao getActivityDao(StrolchTransaction tx) {
return this.persistence.getActivityDao(tx);
}
@Override
public AuditDao getAuditDao(StrolchTransaction tx) {
return this.persistence.getAuditDao(tx);
}
@Override
public void performDbInitialization() {
// no-op
}
}

View File

@ -1,12 +1,7 @@
package li.strolch.runtime.query.inmemory;
import static li.strolch.model.query.ParameterSelection.booleanSelection;
import static li.strolch.model.query.ParameterSelection.floatListSelection;
import static li.strolch.model.query.ParameterSelection.floatSelection;
import static li.strolch.model.query.ParameterSelection.integerListSelection;
import static li.strolch.model.query.ParameterSelection.longListSelection;
import static li.strolch.model.query.ParameterSelection.stringListSelection;
import static li.strolch.model.query.ParameterSelection.stringSelection;
import static li.strolch.agent.ComponentContainerTest.PATH_EMPTY_CONTAINER;
import static li.strolch.model.query.ParameterSelection.*;
import static li.strolch.utils.StringMatchMode.ci;
import static li.strolch.utils.StringMatchMode.es;
import static org.junit.Assert.assertEquals;
@ -15,254 +10,274 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import li.strolch.RuntimeMock;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.model.ModelGenerator;
import li.strolch.model.ParameterBag;
import li.strolch.model.Resource;
import li.strolch.model.Version;
import li.strolch.model.parameter.BooleanParameter;
import li.strolch.model.parameter.FloatListParameter;
import li.strolch.model.parameter.FloatParameter;
import li.strolch.model.parameter.IntegerListParameter;
import li.strolch.model.parameter.LongListParameter;
import li.strolch.model.parameter.StringListParameter;
import li.strolch.model.parameter.StringParameter;
import li.strolch.model.parameter.*;
import li.strolch.model.query.IdSelection;
import li.strolch.model.query.NameSelection;
import li.strolch.model.query.ParameterSelection;
import li.strolch.model.query.ResourceQuery;
import li.strolch.persistence.inmemory.InMemoryResourceDao;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.runtime.StrolchConstants;
import li.strolch.runtime.privilege.PrivilegeHandler;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class InMemoryResourceQueryTest {
protected InMemoryResourceDao daoInstance() {
return new InMemoryResourceDao(false);
public static final String PATH_RUNTIME = "target/" + InMemoryResourceQueryTest.class.getSimpleName();
private static RuntimeMock runtimeMock;
private static Certificate certificate;
private static Certificate login(StrolchAgent agent) {
PrivilegeHandler privilegeHandler = agent.getContainer().getPrivilegeHandler();
return privilegeHandler.authenticate("test", "test".toCharArray());
}
@BeforeClass
public static void beforeClass() {
runtimeMock = new RuntimeMock(PATH_RUNTIME, PATH_EMPTY_CONTAINER);
runtimeMock.mockRuntime();
runtimeMock.startContainer();
certificate = login(runtimeMock.getAgent());
try (StrolchTransaction tx = openTx()) {
getResources().forEach(tx::add);
tx.add(getBallResource());
tx.commitOnClose();
}
}
private static StrolchTransaction openTx() {
return runtimeMock.getAgent().getContainer().getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test");
}
@AfterClass
public static void afterClass() {
if (runtimeMock != null)
runtimeMock.close();
}
@Test
public void shouldQueryById() {
List<Resource> resources = getResources();
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
try (StrolchTransaction tx = openTx()) {
ResourceQuery<Resource> resourceQuery = ResourceQuery.query("MyType1");
resourceQuery.with(new IdSelection("@1"));
ResourceQuery<Resource> resourceQuery = ResourceQuery.query("MyType1");
resourceQuery.with(new IdSelection("@1"));
List<Resource> result = dao.doQuery(resourceQuery);
assertEquals(1, result.size());
assertEquals("@1", result.get(0).getId());
List<Resource> result = tx.doQuery(resourceQuery);
assertEquals(1, result.size());
assertEquals("@1", result.get(0).getId());
}
}
@Test
public void shouldQueryByIdOr() {
List<Resource> resources = getResources();
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
try (StrolchTransaction tx = openTx()) {
ResourceQuery<Resource> resourceQuery = ResourceQuery.query("MyType2");
resourceQuery.or().with(new IdSelection("@3"), new IdSelection("@4"));
ResourceQuery<Resource> resourceQuery = ResourceQuery.query("MyType2");
resourceQuery.or().with(new IdSelection("@3"), new IdSelection("@4"));
List<Resource> result = dao.doQuery(resourceQuery);
assertEquals(2, result.size());
assertEquals("@3", result.get(0).getId());
assertEquals("@4", result.get(1).getId());
List<Resource> result = tx.doQuery(resourceQuery);
assertEquals(2, result.size());
assertEquals("@3", result.get(0).getId());
assertEquals("@4", result.get(1).getId());
}
}
@Test
public void shouldQueryByIdAnd() {
List<Resource> resources = getResources();
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
try (StrolchTransaction tx = openTx()) {
ResourceQuery<Resource> resourceQuery = ResourceQuery.query("MyType2");
resourceQuery.and().with(new IdSelection("@3"), new NameSelection("Res 3", es()));
ResourceQuery<Resource> resourceQuery = ResourceQuery.query("MyType2");
resourceQuery.and().with(new IdSelection("@3"), new NameSelection("Res 3", es()));
List<Resource> result = dao.doQuery(resourceQuery);
assertEquals(1, result.size());
assertEquals("@3", result.get(0).getId());
List<Resource> result = tx.doQuery(resourceQuery);
assertEquals(1, result.size());
assertEquals("@3", result.get(0).getId());
}
}
@Test
public void shouldNotQueryByIdAnd() {
List<Resource> resources = getResources();
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
try (StrolchTransaction tx = openTx()) {
ResourceQuery<Resource> resourceQuery = ResourceQuery.query("MyType1");
resourceQuery.and().with(new IdSelection("@3"), new NameSelection("@4", es()));
ResourceQuery<Resource> resourceQuery = ResourceQuery.query("MyType1");
resourceQuery.and().with(new IdSelection("@3"), new NameSelection("@4", es()));
List<Resource> result = dao.doQuery(resourceQuery);
assertEquals(0, result.size());
List<Resource> result = tx.doQuery(resourceQuery);
assertEquals(0, result.size());
}
}
@Test
public void shouldQueryByParameter() {
List<Resource> resources = getResources();
resources.add(getBallResource());
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
try (StrolchTransaction tx = openTx()) {
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(
//
stringSelection("parameters", "color", "red", es()),
booleanSelection("parameters", "forChildren", true), floatSelection("parameters", "diameter", 22.0));
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(
//
stringSelection("parameters", "color", "red", es()),
booleanSelection("parameters", "forChildren", true),
floatSelection("parameters", "diameter", 22.0));
List<Resource> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Resource> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByListParameter() {
List<Resource> resources = getResources();
resources.add(getBallResource());
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
try (StrolchTransaction tx = openTx()) {
ResourceQuery<Resource> ballQuery;
List<Resource> result;
ResourceQuery<Resource> ballQuery;
List<Resource> result;
// string list
{
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a", "z")));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// string list
{
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a", "z")));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a")));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("a")));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(stringListSelection("parameters", "stringListValues", Arrays.asList("c", "b", "a")));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
}
ballQuery = ResourceQuery.query("Ball");
ballQuery.and()
.with(stringListSelection("parameters", "stringListValues", Arrays.asList("c", "b", "a")));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
// integer list
{
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1, 5)));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// integer list
{
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1, 5)));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(1)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(3, 2, 1)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
}
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(integerListSelection("parameters", "intListValues", Arrays.asList(3, 2, 1)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
// float list
{
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0, 8.0)));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// float list
{
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0, 8.0)));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(4.0)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(6.2, 5.1, 4.0)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
}
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(floatListSelection("parameters", "floatListValues", Arrays.asList(6.2, 5.1, 4.0)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
// long list
{
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L, 11L)));
result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
// long list
{
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L, 11L)));
result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(8L)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(10L, 9L, 8L)));
result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with(longListSelection("parameters", "longListValues", Arrays.asList(10L, 9L, 8L)));
result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
}
@Test
public void shouldQueryByNullParameter1() {
List<Resource> resources = getResources();
resources.add(getBallResource());
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "color"));
try (StrolchTransaction tx = openTx()) {
List<Resource> result = dao.doQuery(ballQuery);
assertEquals(0, result.size());
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "color"));
List<Resource> result = tx.doQuery(ballQuery);
assertEquals(0, result.size());
}
}
@Test
public void shouldQueryByNullParameter2() {
List<Resource> resources = getResources();
resources.add(getBallResource());
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
try (StrolchTransaction tx = openTx()) {
List<Resource> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
List<Resource> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByNullParameter3() {
List<Resource> resources = getResources();
resources.add(getBallResource());
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
try (StrolchTransaction tx = openTx()) {
List<Resource> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.and().with( //
ParameterSelection.nullSelection("parameters", "weight"));
List<Resource> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
@Test
public void shouldQueryByName() {
List<Resource> resources = getResources();
resources.add(getBallResource());
InMemoryResourceDao dao = daoInstance();
dao.saveAll(resources);
try (StrolchTransaction tx = openTx()) {
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.with(new NameSelection("ball ", ci()));
ResourceQuery<Resource> ballQuery = ResourceQuery.query("Ball");
ballQuery.with(new NameSelection("ball ", ci()));
List<Resource> result = dao.doQuery(ballQuery);
assertEquals(1, result.size());
List<Resource> result = tx.doQuery(ballQuery);
assertEquals(1, result.size());
}
}
private Resource getBallResource() {
private static Resource getBallResource() {
Resource res1 = new Resource("childrensBall", "Ball 1", "Ball");
Version.setInitialVersionFor(res1, -1, "test");
ParameterBag bag = new ParameterBag("parameters", "Ball Details", "Parameters");
@ -279,7 +294,7 @@ public class InMemoryResourceQueryTest {
return res1;
}
private List<Resource> getResources() {
private static List<Resource> getResources() {
Resource res1 = ModelGenerator.createResource("@1", "Res 1", "MyType1");
Resource res2 = ModelGenerator.createResource("@2", "Res 2", "MyType1");
Resource res3 = ModelGenerator.createResource("@3", "Res 3", "MyType2");

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -15,36 +15,30 @@
*/
package li.strolch.runtime.query.inmemory;
import static li.strolch.model.ModelGenerator.BAG_ID;
import static li.strolch.model.ModelGenerator.PARAM_STRING_ID;
import static li.strolch.model.ModelGenerator.createOrder;
import static li.strolch.model.ModelGenerator.createResource;
import static li.strolch.model.ModelGenerator.*;
import static li.strolch.model.query.ParameterSelection.integerSelection;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import li.strolch.RuntimeMock;
import li.strolch.agent.ComponentContainerTest;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.model.Order;
import li.strolch.model.Resource;
import li.strolch.model.activity.Activity;
import li.strolch.model.activity.TimeOrdering;
import li.strolch.model.parameter.IntegerParameter;
import li.strolch.model.query.IdSelection;
import li.strolch.model.query.OrderQuery;
import li.strolch.model.query.ParameterSelection;
import li.strolch.model.query.ResourceQuery;
import li.strolch.model.query.Selection;
import li.strolch.model.query.*;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.runtime.StrolchConstants;
import li.strolch.utils.StringMatchMode;
import org.junit.Test;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*
*/
@SuppressWarnings("nls")
public class QueryTest {
@ -56,7 +50,7 @@ public class QueryTest {
}
@Test
public void shouldQueryResourceWithParamValue() {
public void shouldQueryResourceWithParamValue() throws Exception {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, ComponentContainerTest.PATH_EMPTY_CONTAINER, agent -> {
ComponentContainer container = agent.getContainer();
@ -66,24 +60,24 @@ public class QueryTest {
Resource res1 = createResource("@1", "Test Resource", "MyType");
IntegerParameter iP = new IntegerParameter("nbOfBooks", "Number of Books", 33);
res1.addParameter(BAG_ID, iP);
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
tx.getResourceMap().add(tx, res1);
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
tx.add(res1);
tx.commitOnClose();
}
ResourceQuery<Resource> query = ResourceQuery.query("MyType");
List<Selection> elementAndSelections = new ArrayList<>();
elementAndSelections.add(new IdSelection("@1"));
elementAndSelections.add(ParameterSelection.integerSelection(BAG_ID, "nbOfBooks", 33));
elementAndSelections.add(integerSelection(BAG_ID, "nbOfBooks", 33));
query.and().with(elementAndSelections);
InMemoryResourceQueryVisitor resourceQuery = new InMemoryResourceQueryVisitor();
InMemoryQuery<Resource, Resource> inMemoryQuery = resourceQuery.visit(query);
List<Resource> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
result = inMemoryQuery.doQuery(tx.getPersistenceHandler().getResourceDao(tx));
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = inMemoryQuery.doQuery(tx, tx.getResourceMap());
}
assertEquals(1, result.size());
assertEquals("@1", result.get(0).getId());
@ -91,7 +85,7 @@ public class QueryTest {
}
@Test
public void shouldQueryOrderWithParamValue() {
public void shouldQueryOrderWithParamValue() throws Exception {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, ComponentContainerTest.PATH_EMPTY_CONTAINER, agent -> {
ComponentContainer container = agent.getContainer();
@ -101,24 +95,24 @@ public class QueryTest {
Order o1 = createOrder("@1", "Test Order", "MyType");
IntegerParameter iP = new IntegerParameter("nbOfBooks", "Number of Books", 33);
o1.addParameter(BAG_ID, iP);
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
tx.getOrderMap().add(tx, o1);
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
tx.add(o1);
tx.commitOnClose();
}
OrderQuery<Order> query = OrderQuery.query("MyType");
List<Selection> elementAndSelections = new ArrayList<>();
elementAndSelections.add(new IdSelection("@1"));
elementAndSelections.add(ParameterSelection.integerSelection(BAG_ID, "nbOfBooks", 33));
elementAndSelections.add(integerSelection(BAG_ID, "nbOfBooks", 33));
query.and().with(elementAndSelections);
InMemoryOrderQueryVisitor orderQuery = new InMemoryOrderQueryVisitor();
InMemoryQuery<Order, Order> inMemoryQuery = orderQuery.visit(query);
List<Order> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
result = inMemoryQuery.doQuery(tx.getPersistenceHandler().getOrderDao(tx));
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = inMemoryQuery.doQuery(tx, tx.getOrderMap());
}
assertEquals(1, result.size());
assertEquals("@1", result.get(0).getId());
@ -126,7 +120,42 @@ public class QueryTest {
}
@Test
public void shouldQueryContainsString() {
public void shouldQueryActivityWithParamValue() throws Exception {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, ComponentContainerTest.PATH_EMPTY_CONTAINER, agent -> {
ComponentContainer container = agent.getContainer();
Certificate certificate = login(container);
Activity a1 = createActivity("@1", "Test Activity", "MyType", TimeOrdering.SERIES);
IntegerParameter iP = new IntegerParameter("nbOfBooks", "Number of Books", 33);
a1.addParameter(BAG_ID, iP);
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
tx.add(a1);
tx.commitOnClose();
}
ActivityQuery<Activity> query = ActivityQuery.query("MyType");
List<Selection> elementAndSelections = new ArrayList<>();
elementAndSelections.add(new IdSelection("@1"));
elementAndSelections.add(integerSelection(BAG_ID, "nbOfBooks", 33));
query.and().with(elementAndSelections);
InMemoryActivityQueryVisitor orderQuery = new InMemoryActivityQueryVisitor();
InMemoryQuery<Activity, Activity> inMemoryQuery = orderQuery.visit(query);
List<Activity> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = inMemoryQuery.doQuery(tx, tx.getActivityMap());
}
assertEquals(1, result.size());
assertEquals("@1", result.get(0).getId());
});
}
@Test
public void shouldQueryContainsString() throws Exception {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, ComponentContainerTest.PATH_EMPTY_CONTAINER, agent -> {
ComponentContainer container = agent.getContainer();
@ -134,18 +163,18 @@ public class QueryTest {
Certificate certificate = login(container);
Resource res1 = createResource("@1", "Test Resource", "MyType");
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
tx.getResourceMap().add(tx, res1);
tx.commitOnClose();
}
ResourceQuery<Resource> query = ResourceQuery.query("MyType");
query.and().with(ParameterSelection.stringSelection(BAG_ID, PARAM_STRING_ID, "olch",
StringMatchMode.CONTAINS_CASE_SENSITIVE));
query.and().with(ParameterSelection
.stringSelection(BAG_ID, PARAM_STRING_ID, "olch", StringMatchMode.CONTAINS_CASE_SENSITIVE));
List<Resource> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = tx.doQuery(query);
}
assertEquals(1, result.size());
@ -154,7 +183,7 @@ public class QueryTest {
}
@Test
public void shouldNotQueryContainsString() {
public void shouldNotQueryContainsString() throws Exception {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, ComponentContainerTest.PATH_EMPTY_CONTAINER, agent -> {
ComponentContainer container = agent.getContainer();
@ -162,18 +191,18 @@ public class QueryTest {
Certificate certificate = login(container);
Resource res1 = createResource("@1", "Test Resource", "MyType");
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
tx.getResourceMap().add(tx, res1);
tx.commitOnClose();
}
ResourceQuery<Resource> query = ResourceQuery.query("MyType");
query.and().with(ParameterSelection.stringSelection(BAG_ID, PARAM_STRING_ID, "str",
StringMatchMode.CONTAINS_CASE_SENSITIVE));
query.and().with(ParameterSelection
.stringSelection(BAG_ID, PARAM_STRING_ID, "str", StringMatchMode.CONTAINS_CASE_SENSITIVE));
List<Resource> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = tx.doQuery(query);
}
assertEquals(0, result.size());
@ -181,7 +210,7 @@ public class QueryTest {
}
@Test
public void shouldQueryCaseInsensitiveString() {
public void shouldQueryCaseInsensitiveString() throws Exception {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, ComponentContainerTest.PATH_EMPTY_CONTAINER, agent -> {
ComponentContainer container = agent.getContainer();
@ -189,18 +218,18 @@ public class QueryTest {
Certificate certificate = login(container);
Resource res1 = createResource("@1", "Test Resource", "MyType");
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
tx.getResourceMap().add(tx, res1);
tx.commitOnClose();
}
ResourceQuery<Resource> query = ResourceQuery.query("MyType");
query.and().with(ParameterSelection.stringSelection(BAG_ID, PARAM_STRING_ID, "strolch",
StringMatchMode.EQUALS_CASE_INSENSITIVE));
query.and().with(ParameterSelection
.stringSelection(BAG_ID, PARAM_STRING_ID, "strolch", StringMatchMode.EQUALS_CASE_INSENSITIVE));
List<Resource> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = tx.doQuery(query);
}
assertEquals(1, result.size());
@ -209,7 +238,7 @@ public class QueryTest {
}
@Test
public void shouldNotQueryCaseInsensitiveString() {
public void shouldNotQueryCaseInsensitiveString() throws Exception {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, ComponentContainerTest.PATH_EMPTY_CONTAINER, agent -> {
ComponentContainer container = agent.getContainer();
@ -217,18 +246,18 @@ public class QueryTest {
Certificate certificate = login(container);
Resource res1 = createResource("@1", "Test Resource", "MyType");
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
tx.getResourceMap().add(tx, res1);
tx.commitOnClose();
}
ResourceQuery<Resource> query = ResourceQuery.query("MyType");
query.and().with(ParameterSelection.stringSelection(BAG_ID, PARAM_STRING_ID, "strolch",
StringMatchMode.EQUALS_CASE_SENSITIVE));
query.and().with(ParameterSelection
.stringSelection(BAG_ID, PARAM_STRING_ID, "strolch", StringMatchMode.EQUALS_CASE_SENSITIVE));
List<Resource> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = tx.doQuery(query);
}
assertEquals(0, result.size());
@ -236,7 +265,7 @@ public class QueryTest {
}
@Test
public void shouldQueryNot() {
public void shouldQueryNot() throws Exception {
RuntimeMock.runInStrolch(PATH_EMPTY_RUNTIME, ComponentContainerTest.PATH_EMPTY_CONTAINER, agent -> {
ComponentContainer container = agent.getContainer();
@ -245,8 +274,8 @@ public class QueryTest {
Resource res1 = createResource("@1", "Test Resource", "MyType");
Resource res2 = createResource("@2", "Test Resource", "MyType");
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
tx.getResourceMap().add(tx, res1);
tx.getResourceMap().add(tx, res2);
tx.commitOnClose();
@ -256,8 +285,8 @@ public class QueryTest {
ResourceQuery<Resource> query = ResourceQuery.query("MyType");
query.not(new IdSelection("@1"));
List<Resource> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = tx.doQuery(query);
}
assertEquals(1, result.size());
@ -268,8 +297,8 @@ public class QueryTest {
ResourceQuery<Resource> query = ResourceQuery.query("MyType");
query.not(new IdSelection("@2"));
List<Resource> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = tx.doQuery(query);
}
assertEquals(1, result.size());
@ -280,8 +309,8 @@ public class QueryTest {
ResourceQuery<Resource> query = ResourceQuery.query("MyType");
query.not(new IdSelection("@1", "@2"));
List<Resource> result;
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM).openTx(certificate,
"test")) {
try (StrolchTransaction tx = container.getRealm(StrolchConstants.DEFAULT_REALM)
.openTx(certificate, "test")) {
result = tx.doQuery(query);
}
assertEquals(0, result.size());

View File

@ -1,91 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Roles>
<Role name="agent">
<Privilege name="li.strolch.privilege.handler.SystemAction" policy="DefaultPrivilege">
<Allow>li.strolch.runtime.privilege.StrolchSystemAction</Allow>
<Allow>li.strolch.runtime.privilege.StrolchSystemActionWithResult</Allow>
</Privilege>
<Privilege name="GetResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
</Role>
<Role name="AppUser">
<Privilege name="li.strolch.service.api.Service" policy="DefaultPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="li.strolch.model.query.StrolchQuery" policy="DefaultPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
</Role>
</Roles>

View File

@ -16,27 +16,20 @@
<privilegeConfigFile>PrivilegeConfig.xml</privilegeConfigFile>
</Properties>
</Component>
<Component>
<name>PersistenceHandler</name>
<api>li.strolch.persistence.api.PersistenceHandler</api>
<impl>li.strolch.runtime.query.inmemory.InMemoryPersistenceHandler</impl>
</Component>
<Component>
<name>RealmHandler</name>
<api>li.strolch.agent.api.RealmHandler</api>
<impl>li.strolch.agent.impl.DefaultRealmHandler</impl>
<depends>PrivilegeHandler</depends>
<depends>PersistenceHandler</depends>
<Properties>
<realms>defaultRealm, myRealm, otherRealm, cachedRealm, transactionalRealm, emptyRealm</realms>
<realms>defaultRealm, myRealm, otherRealm, emptyRealm</realms>
<dataStoreMode>TRANSIENT</dataStoreMode>
<dataStoreFile>DefaultRealm.xml</dataStoreFile>
<enableAuditTrail>true</enableAuditTrail>
<dataStoreMode.myRealm>TRANSIENT</dataStoreMode.myRealm>
<dataStoreFile.myRealm>MyRealm.xml</dataStoreFile.myRealm>
<dataStoreMode.otherRealm>TRANSIENT</dataStoreMode.otherRealm>
<dataStoreFile.otherRealm>OtherRealm.xml</dataStoreFile.otherRealm>
<dataStoreMode.transactionalRealm>TRANSACTIONAL</dataStoreMode.transactionalRealm>
<dataStoreMode.cachedRealm>CACHED</dataStoreMode.cachedRealm>
<dataStoreMode.emptyRealm>EMPTY</dataStoreMode.emptyRealm>
</Properties>
</Component>

View File

@ -22,4 +22,25 @@
<Parameter Id="@param1" Name="Boolean Param" Type="Boolean" Value="true" />
</ParameterBag>
</Order>
<Activity Id="MyRealmAct" Name="Test Name" Type="TestType" TimeOrdering="Series">
<Policies>
<Policy Type="PlanningPolicy" Value="key:SimplePlanning" />
<Policy Type="ConfirmationPolicy" Value="key:NoConfirmation" />
</Policies>
<Action Id="action_1" Name="Action 1" ResourceId="dummyId" ResourceType="dummyType" State="Created" Type="Use">
<Policies>
<Policy Type="PlanningPolicy" Value="key:SimplePlanning" />
<Policy Type="ConfirmationPolicy" Value="key:NoConfirmation" />
</Policies>
<ValueChange StateId="dummyId" Time="2012-11-30T18:12:05.628+01:00" Value="5" Type="Integer" />
</Action>
<Activity Id="child_activity" Name="Child Activity" Type="childType" TimeOrdering="Series">
<Policies>
<Policy Type="PlanningPolicy" Value="key:SimplePlanning" />
<Policy Type="ConfirmationPolicy" Value="key:NoConfirmation" />
</Policies>
<Action Id="action_2" Name="Action 2" ResourceId="dummyId" ResourceType="dummyType" State="Planned" Type="Use" />
<Action Id="action_3" Name="Action 3" ResourceId="dummyId" ResourceType="dummyType" State="Created" Type="Use" />
</Activity>
</Activity>
</StrolchModel>

View File

@ -22,4 +22,25 @@
<Parameter Id="@param1" Name="Boolean Param" Type="Boolean" Value="true" />
</ParameterBag>
</Order>
<Activity Id="OtherRealmAct" Name="Test Name" Type="TestType" TimeOrdering="Series">
<Policies>
<Policy Type="PlanningPolicy" Value="key:SimplePlanning" />
<Policy Type="ConfirmationPolicy" Value="key:NoConfirmation" />
</Policies>
<Action Id="action_1" Name="Action 1" ResourceId="dummyId" ResourceType="dummyType" State="Created" Type="Use">
<Policies>
<Policy Type="PlanningPolicy" Value="key:SimplePlanning" />
<Policy Type="ConfirmationPolicy" Value="key:NoConfirmation" />
</Policies>
<ValueChange StateId="dummyId" Time="2012-11-30T18:12:05.628+01:00" Value="5" Type="Integer" />
</Action>
<Activity Id="child_activity" Name="Child Activity" Type="childType" TimeOrdering="Series">
<Policies>
<Policy Type="PlanningPolicy" Value="key:SimplePlanning" />
<Policy Type="ConfirmationPolicy" Value="key:NoConfirmation" />
</Policies>
<Action Id="action_2" Name="Action 2" ResourceId="dummyId" ResourceType="dummyType" State="Planned" Type="Use" />
<Action Id="action_3" Name="Action 3" ResourceId="dummyId" ResourceType="dummyType" State="Created" Type="Use" />
</Activity>
</Activity>
</StrolchModel>

View File

@ -1,92 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Roles>
<Role name="agent">
<Privilege name="li.strolch.privilege.handler.SystemAction" policy="DefaultPrivilege">
<Allow>li.strolch.runtime.privilege.StrolchSystemAction</Allow>
<Allow>li.strolch.runtime.privilege.StrolchSystemActionWithResult</Allow>
</Privilege>
<Privilege name="GetResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
</Role>
<Role name="AppUser">
<Privilege name="li.strolch.service.api.Service" policy="DefaultPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="li.strolch.model.query.StrolchQuery" policy="DefaultPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="GetActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="AddActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="UpdateActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveResource" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveOrder" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RemoveActivity" policy="ModelPrivilege">
<AllAllowed>true</AllAllowed>
</Privilege>
</Role>
</Roles>

View File

@ -1,51 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<StrolchConfiguration>
<env id="dev">
<Runtime>
<applicationName>StrolchRuntimeTest</applicationName>
<Properties>
<verbose>true</verbose>
</Properties>
</Runtime>
<Component>
<name>PrivilegeHandler</name>
<api>li.strolch.runtime.privilege.PrivilegeHandler</api>
<impl>li.strolch.runtime.privilege.DefaultStrolchPrivilegeHandler</impl>
<Properties>
<privilegeConfigFile>PrivilegeConfig.xml</privilegeConfigFile>
</Properties>
</Component>
<Component>
<name>RealmHandler</name>
<api>li.strolch.agent.api.RealmHandler</api>
<impl>li.strolch.agent.impl.DefaultRealmHandler</impl>
<depends>PrivilegeHandler</depends>
<depends>PersistenceHandler</depends>
<Properties>
<dataStoreMode>TRANSACTIONAL</dataStoreMode>
<dataStoreFile>StrolchModel.xml</dataStoreFile>
</Properties>
</Component>
<Component>
<name>ServiceHandler</name>
<api>li.strolch.runtime.configuration.model.ServiceHandlerTest</api>
<impl>li.strolch.runtime.configuration.model.ServiceHandlerTestImpl</impl>
<depends>RealmHandler</depends>
<Properties>
</Properties>
</Component>
<Component>
<name>PostInitializer</name>
<api>li.strolch.runtime.configuration.model.PostInitializerTest</api>
<impl>li.strolch.runtime.configuration.model.PostInitializerTestImpl</impl>
<depends>ServiceHandler</depends>
<Properties>
</Properties>
</Component>
<Component>
<name>PersistenceHandler</name>
<api>li.strolch.persistence.api.PersistenceHandler</api>
<impl>li.strolch.runtime.query.inmemory.InMemoryPersistenceHandler</impl>
</Component>
</env>
</StrolchConfiguration>

View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<StrolchModel>
<Order Id="MyTestOrder" Name="Test Name" Type="TestType" Date="2013-11-20T07:42:57.699+01:00" State="CREATED">
<ParameterBag Id="@bag01" Name="Test Bag" Type="TestBag">
<Parameter Id="@param7" Name="StringList Param" Type="StringList" Value="Hello;World" />
<Parameter Id="@param6" Name="Date Param" Type="Date" Value="2012-11-30T18:12:05.628+01:00" />
<Parameter Id="@param5" Name="String Param" Type="String" Value="Strolch" />
<Parameter Id="@param4" Name="Long Param" Type="Long" Value="4453234566" />
<Parameter Id="@param3" Name="Integer Param" Type="Integer" Value="77" />
<Parameter Id="@param2" Name="Float Param" Type="Float" Value="44.3" />
<Parameter Id="@param1" Name="Boolean Param" Type="Boolean" Value="true" />
</ParameterBag>
</Order>
</StrolchModel>

View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<StrolchModel>
<Resource Id="MyTestResource" Name="Test Name" Type="TestType">
<ParameterBag Id="@bag01" Name="Test Bag" Type="TestBag">
<Parameter Id="@param7" Name="StringList Param" Type="StringList" Value="Hello;World" />
<Parameter Id="@param6" Name="Date Param" Type="Date" Value="2012-11-30T18:12:05.628+01:00" />
<Parameter Id="@param5" Name="String Param" Type="String" Value="Strolch" />
<Parameter Id="@param4" Name="Long Param" Type="Long" Value="4453234566" />
<Parameter Id="@param3" Name="Integer Param" Type="Integer" Value="77" />
<Parameter Id="@param2" Name="Float Param" Type="Float" Value="44.3" />
<Parameter Id="@param1" Name="Boolean Param" Type="Boolean" Value="true" />
</ParameterBag>
</Resource>
</StrolchModel>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<StrolchModel>
<Activity Id="activity_1" Name="Activity" Type="ActivityType" TimeOrdering="Series">
<Policies>
<Policy Type="PlanningPolicy" Value="key:SimplePlanning" />
<Policy Type="ConfirmationPolicy" Value="key:NoConfirmation" />
</Policies>
<Action Id="action_1" Name="Action 1" ResourceId="dummyId" ResourceType="dummyType" State="Created" Type="Use">
<Policies>
<Policy Type="PlanningPolicy" Value="key:SimplePlanning" />
<Policy Type="ConfirmationPolicy" Value="key:NoConfirmation" />
</Policies>
<ValueChange StateId="dummyId" Time="2012-11-30T18:12:05.628+01:00" Value="5" Type="Integer" />
</Action>
<Activity Id="child_activity" Name="Child Activity" Type="childType" TimeOrdering="Series">
<Policies>
<Policy Type="PlanningPolicy" Value="key:SimplePlanning" />
<Policy Type="ConfirmationPolicy" Value="key:NoConfirmation" />
</Policies>
<Action Id="action_2" Name="Action 2" ResourceId="dummyId" ResourceType="dummyType" State="Planned" Type="Use" />
<Action Id="action_3" Name="Action 3" ResourceId="dummyId" ResourceType="dummyType" State="Created" Type="Use" />
</Activity>
</Activity>
</StrolchModel>

View File

@ -25,5 +25,6 @@
<IncludeFile file="Resources.xml" />
<IncludeFile file="Orders.xml" />
<IncludeFile file="Activities.xml" />
</StrolchModel>

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -31,6 +31,7 @@ public abstract class AbstractStrolchElement implements StrolchElement {
protected long dbid = Long.MAX_VALUE;
protected String id;
protected String name;
protected boolean readOnly;
/**
* Empty constructor - for marshalling only!
@ -43,9 +44,9 @@ public abstract class AbstractStrolchElement implements StrolchElement {
* Default constructor
*
* @param id
* id of this {@link StrolchElement}
* id of this {@link StrolchElement}
* @param name
* name of this {@link StrolchElement}
* name of this {@link StrolchElement}
*/
public AbstractStrolchElement(String id, String name) {
setId(id);
@ -69,6 +70,7 @@ public abstract class AbstractStrolchElement implements StrolchElement {
@Override
public void setId(String id) {
assertNotReadonly();
if (StringHelper.isEmpty(id)) {
String msg = "The id may never be empty for {0}";
msg = MessageFormat.format(msg, getClass().getSimpleName());
@ -84,6 +86,7 @@ public abstract class AbstractStrolchElement implements StrolchElement {
@Override
public void setName(String name) {
assertNotReadonly();
if (StringHelper.isEmpty(name)) {
String msg = "The name may never be empty for {0} {1}";
msg = MessageFormat.format(msg, getClass().getSimpleName(), getLocator());
@ -97,7 +100,7 @@ public abstract class AbstractStrolchElement implements StrolchElement {
* implemented as parents must first add their {@link Locator} information
*
* @param locatorBuilder
* the {@link LocatorBuilder} to which the {@link StrolchElement} must add its locator information
* the {@link LocatorBuilder} to which the {@link StrolchElement} must add its locator information
*/
protected abstract void fillLocator(LocatorBuilder locatorBuilder);
@ -105,12 +108,30 @@ public abstract class AbstractStrolchElement implements StrolchElement {
* fills the {@link StrolchElement} clone with the id, name and type
*
* @param clone
* the clone to fill
*/
protected void fillClone(StrolchElement clone) {
clone.setId(getId());
clone.setName(getName());
}
@Override
public boolean isReadOnly() {
return this.readOnly;
}
@Override
public void setReadOnly() {
this.readOnly = true;
}
protected void assertNotReadonly() {
if (this.readOnly) {
throw new IllegalStateException(
"The element " + getLocator() + " is currently readOnly, to modify clone first!");
}
}
@Override
public int hashCode() {
final int prime = 31;

View File

@ -2,8 +2,7 @@ package li.strolch.model;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import li.strolch.model.json.StrolchElementToJsonVisitor;
import li.strolch.model.json.StrolchRootElementToJsonVisitor;
import li.strolch.model.xml.StrolchElementToXmlStringVisitor;
public abstract class AbstractStrolchRootElement extends GroupedParameterizedElement implements StrolchRootElement {
@ -26,12 +25,12 @@ public abstract class AbstractStrolchRootElement extends GroupedParameterizedEle
@Override
public String toJsonString() {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(this.accept(new StrolchElementToJsonVisitor()));
return gson.toJson(this.accept(new StrolchRootElementToJsonVisitor()));
}
@Override
public String toFlatJsonString() {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(this.accept(new StrolchElementToJsonVisitor().flat()));
return gson.toJson(this.accept(new StrolchRootElementToJsonVisitor().flat()));
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -48,10 +48,13 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Default Constructor
*
*
* @param id
* the id
* @param name
* the name
* @param type
* the type
*/
protected GroupedParameterizedElement(String id, String name, String type) {
super(id, name);
@ -65,11 +68,12 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Sets the type of this {@link GroupedParameterizedElement}
*
*
* @param type
* the type to set
* the type to set
*/
public void setType(String type) {
assertNotReadonly();
if (StringHelper.isEmpty(type)) {
String msg = "Type may not be empty on element {0}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, getLocator());
@ -82,12 +86,12 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns the {@link Parameter} with the given key from the {@link ParameterBag} with the given bagKey, or null if
* the {@link Parameter} or the {@link ParameterBag} does not exist
*
*
* @param bagKey
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be returned
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be returned
* @param paramKey
* the key of the {@link Parameter} which is to be returned
*
* the key of the {@link Parameter} which is to be returned
*
* @return the found {@link Parameter} or null if it was not found
*/
public <U, T extends Parameter<U>> T getParameter(String bagKey, String paramKey) {
@ -97,18 +101,18 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns the {@link Parameter} with the given key from the {@link ParameterBag} with the given bagKey, or null if
* the {@link Parameter} or the {@link ParameterBag} does not exist
*
*
* @param bagKey
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be returned
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be returned
* @param paramKey
* the key of the {@link Parameter} which is to be returned
* the key of the {@link Parameter} which is to be returned
* @param assertExists
* if set to true, and the parameter does not exist, a {@link StrolchModelException} is thrown
*
* if set to true, and the parameter does not exist, a {@link StrolchModelException} is thrown
*
* @return the found {@link Parameter} or null if it was not found
*
*
* @throws StrolchModelException
* if the element does not exist and <code>assertExists</code> is true
* if the element does not exist and <code>assertExists</code> is true
*/
public <U, T extends Parameter<U>> T getParameter(String bagKey, String paramKey, boolean assertExists)
throws StrolchModelException {
@ -142,12 +146,12 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns a list of all the {@link Parameter Parameters} with the given interpretation
*
*
* @param bagKey
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be returned
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be returned
* @param interpretation
* the interpretation for which the parameters are to be returned
*
* the interpretation for which the parameters are to be returned
*
* @return the parameters with the given interpretation
*/
public List<Parameter<?>> getParametersByInterpretation(String bagKey, String interpretation) {
@ -160,14 +164,14 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns a list of all the {@link Parameter Parameters} with the given interpretation
*
*
* @param bagKey
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be returned
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be returned
* @param interpretation
* the interpretation for which the parameters are to be returned
* the interpretation for which the parameters are to be returned
* @param uom
* the uom for which the parameters are to be returned
*
* the uom for which the parameters are to be returned
*
* @return the parameters with the given interpretation
*/
public List<Parameter<?>> getParametersByInterpretationAndUom(String bagKey, String interpretation, String uom) {
@ -180,16 +184,17 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Adds a new {@link Parameter} to the {@link ParameterBag} with the given key
*
*
* @param bagKey
* the key of the {@link ParameterBag} to which the {@link Parameter} should be added
* the key of the {@link ParameterBag} to which the {@link Parameter} should be added
* @param parameter
* the {@link Parameter} to be added to the {@link ParameterBag}
*
* the {@link Parameter} to be added to the {@link ParameterBag}
*
* @throws StrolchException
* if the {@link ParameterBag} does not exist
* if the {@link ParameterBag} does not exist
*/
public void addParameter(String bagKey, Parameter<?> parameter) throws StrolchException {
assertNotReadonly();
if (this.parameterBagMap == null) {
this.parameterBagMap = new HashMap<>(1, 1.0F);
}
@ -205,15 +210,16 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Removes the {@link Parameter} with the given paramKey from the {@link ParameterBag} with the given bagKey
*
*
* @param bagKey
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be removed
* the key of the {@link ParameterBag} from which the {@link Parameter} is to be removed
* @param paramKey
* the key of the {@link Parameter} which is to be removed
*
* the key of the {@link Parameter} which is to be removed
*
* @return the removed {@link Parameter} or null if it did not exist
*/
public <U, T extends Parameter<U>> T removeParameter(String bagKey, String paramKey) {
assertNotReadonly();
if (this.parameterBagMap == null) {
return null;
}
@ -227,10 +233,10 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns the {@link ParameterBag} with the given key, or null if it does not exist
*
*
* @param key
* the key of the {@link ParameterBag} to return
*
* the key of the {@link ParameterBag} to return
*
* @return the {@link ParameterBag} with the given key, or null if it does not exist
*/
public ParameterBag getParameterBag(String key) {
@ -239,12 +245,12 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns the {@link ParameterBag} with the given key, or null if it does not exist
*
*
* @param key
* the key of the {@link ParameterBag} to return
* the key of the {@link ParameterBag} to return
* @param assertExists
* if set to true, and the parameter bag does not exist, a {@link StrolchModelException} is thrown
*
* if set to true, and the parameter bag does not exist, a {@link StrolchModelException} is thrown
*
* @return the {@link ParameterBag} with the given key, or null if it does not exist
*/
public ParameterBag getParameterBag(String key, boolean assertExists) {
@ -267,10 +273,10 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns the {@link ParameterBag ParameterBags} of the given type
*
*
* @param type
* the type of {@link ParameterBag} to return
*
* the type of {@link ParameterBag} to return
*
* @return the {@link ParameterBag ParameterBags} of the given type
*/
public List<ParameterBag> getParameterBagsByType(String type) {
@ -282,11 +288,12 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Adds the given {@link ParameterBag} to this {@link GroupedParameterizedElement}
*
*
* @param bag
* the {@link ParameterBag} to add
* the {@link ParameterBag} to add
*/
public void addParameterBag(ParameterBag bag) {
assertNotReadonly();
if (this.parameterBagMap == null) {
this.parameterBagMap = new HashMap<>(1, 1.0F);
}
@ -301,13 +308,14 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Removes the {@link ParameterBag} with the given key
*
*
* @param key
* the key of the {@link ParameterBag} to remove
*
* the key of the {@link ParameterBag} to remove
*
* @return the removed {@link ParameterBag}, or null if it does not exist
*/
public ParameterBag removeParameterBag(String key) {
assertNotReadonly();
if (this.parameterBagMap == null) {
return null;
}
@ -316,7 +324,7 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns true if this {@link GroupedParameterizedElement} has any {@link ParameterBag ParameterBag}
*
*
* @return true if this {@link GroupedParameterizedElement} has any {@link ParameterBag ParameterBag}
*/
public boolean hasParameterBags() {
@ -325,9 +333,10 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns true if the {@link ParameterBag} with the given key exists on this {@link GroupedParameterizedElement}.
*
*
* @param bagKey
* the key of the {@link ParameterBag} which is to be checked for existence
* the key of the {@link ParameterBag} which is to be checked for existence
*
* @return true if the {@link ParameterBag} with the given key exists on this {@link GroupedParameterizedElement}.
*/
public boolean hasParameterBag(String bagKey) {
@ -337,15 +346,15 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns true if the {@link Parameter} with the given paramKey exists on the {@link ParameterBag} with the given
* bagKey
*
*
* @param bagKey
* the key of the {@link ParameterBag} on which to find the {@link Parameter}
* the key of the {@link ParameterBag} on which to find the {@link Parameter}
* @param paramKey
* the key of the {@link Parameter} to be found
*
* the key of the {@link Parameter} to be found
*
* @return true if the {@link Parameter} with the given paramKey exists on the {@link ParameterBag} with the given
* bagKey. False is returned if the {@link ParameterBag} does not exist, or the {@link Parameter} does not
* exist on the {@link ParameterBag}
* bagKey. False is returned if the {@link ParameterBag} does not exist, or the {@link Parameter} does not
* exist on the {@link ParameterBag}
*/
public boolean hasParameter(String bagKey, String paramKey) {
if (this.parameterBagMap == null) {
@ -361,7 +370,7 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Returns the {@link Set} of keys for the {@link ParameterBag}s on this {@link GroupedParameterizedElement}
*
*
* @return the {@link Set} of keys for the {@link ParameterBag}s on this {@link GroupedParameterizedElement}
*/
public Set<String> getParameterBagKeySet() {
@ -373,7 +382,7 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
/**
* Fills {@link GroupedParameterizedElement} properties of this clone
*
*
* @param clone
*/
protected void fillClone(GroupedParameterizedElement clone) {
@ -386,4 +395,14 @@ public abstract class GroupedParameterizedElement extends AbstractStrolchElement
}
}
}
@Override
public void setReadOnly() {
if (this.parameterBagMap != null) {
for (ParameterBag bag : this.parameterBagMap.values()) {
bag.setReadOnly();
}
}
super.setReadOnly();
}
}

View File

@ -68,7 +68,7 @@ public class Locator {
* if the path is invalid, meaning has less than two elements in it
*/
private Locator(List<String> pathElements) throws StrolchException {
if (pathElements == null || pathElements.isEmpty()) {
if (pathElements == null) {
throw new StrolchException("The path elements may not be null and must contain at least 1 item"); //$NON-NLS-1$
}
this.pathElements = Collections.unmodifiableList(new ArrayList<>(pathElements));

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -55,8 +55,11 @@ public class Order extends AbstractStrolchRootElement implements StrolchRootElem
* Default Constructor
*
* @param id
* the id
* @param name
* the name
* @param type
* the type
*/
public Order(String id, String name, String type) {
super(id, name, type);
@ -69,10 +72,15 @@ public class Order extends AbstractStrolchRootElement implements StrolchRootElem
* Extended Constructor for date and {@link State}
*
* @param id
* the id
* @param name
* the name
* @param type
* the type
* @param date
* the date
* @param state
* the state
*/
public Order(String id, String name, String type, Date date, State state) {
super(id, name, type);
@ -111,6 +119,7 @@ public class Order extends AbstractStrolchRootElement implements StrolchRootElem
}
public void setDate(Date date) {
assertNotReadonly();
this.date = date;
}
@ -119,6 +128,7 @@ public class Order extends AbstractStrolchRootElement implements StrolchRootElem
}
public void setState(State state) {
assertNotReadonly();
this.state = state;
}
@ -129,6 +139,11 @@ public class Order extends AbstractStrolchRootElement implements StrolchRootElem
return this.policyDefs;
}
@Override
public PolicyDef getPolicyDef(Class<?> clazz) {
return getPolicyDefs().getPolicyDef(clazz.getSimpleName());
}
@Override
public PolicyDef getPolicyDef(String type) {
return getPolicyDefs().getPolicyDef(type);
@ -146,12 +161,19 @@ public class Order extends AbstractStrolchRootElement implements StrolchRootElem
@Override
public void setPolicyDefs(PolicyDefs policyDefs) {
assertNotReadonly();
this.policyDefs = policyDefs;
this.policyDefs.setParent(this);
}
@Override
public Order getClone() {
return getClone(false);
}
@Override
public Order getClone(boolean withVersion) {
Order clone = new Order();
super.fillClone(clone);
@ -162,9 +184,19 @@ public class Order extends AbstractStrolchRootElement implements StrolchRootElem
if (this.policyDefs != null)
clone.setPolicyDefs(this.policyDefs.getClone());
if (withVersion)
clone.setVersion(this.version);
return clone;
}
@Override
public void setReadOnly() {
if (this.policyDefs != null)
this.policyDefs.setReadOnly();
super.setReadOnly();
}
@Override
protected void fillLocator(LocatorBuilder lb) {
lb.append(Tags.ORDER).append(getType()).append(getId());

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -16,6 +16,7 @@
package li.strolch.model;
import li.strolch.model.Locator.LocatorBuilder;
import li.strolch.model.visitor.StrolchElementVisitor;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -35,8 +36,11 @@ public class ParameterBag extends ParameterizedElement {
* Default constructor
*
* @param id
* the id
* @param name
* the name
* @param type
* the type
*/
public ParameterBag(String id, String name, String type) {
super(id, name, type);
@ -61,4 +65,9 @@ public class ParameterBag extends ParameterizedElement {
public boolean isRootElement() {
return false;
}
@Override
public <T> T accept(StrolchElementVisitor<T> visitor) {
return visitor.visitParameterBag(this);
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -51,10 +51,13 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Default Constructor
*
*
* @param id
* the id
* @param name
* the name
* @param type
* the type
*/
public ParameterizedElement(String id, String name, String type) {
setId(id);
@ -69,11 +72,12 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Sets the type of this {@link ParameterizedElement}
*
*
* @param type
* the type to set
* the type to set
*/
public void setType(String type) {
assertNotReadonly();
if (StringHelper.isEmpty(type)) {
String msg = "Type may not be empty on element {0}"; //$NON-NLS-1$
msg = MessageFormat.format(msg, getLocator());
@ -85,10 +89,10 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Returns the {@link Parameter} with the given id, or null if it does not exist
*
*
* @param key
* the id of the parameter to return
*
* the id of the parameter to return
*
* @return the {@link Parameter} with the given id, or null if it does not exist
*/
public <U, T extends Parameter<U>> T getParameter(String key) {
@ -97,12 +101,12 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Returns the {@link Parameter} with the given id, or null if it does not exist
*
*
* @param key
* the id of the parameter to return
* the id of the parameter to return
* @param assertExists
* if set to true, and the parameter does not exist, a {@link StrolchModelException} is thrown
*
* if set to true, and the parameter does not exist, a {@link StrolchModelException} is thrown
*
* @return the {@link Parameter} with the given id, or null if it does not exist
*/
@SuppressWarnings("unchecked")
@ -128,11 +132,12 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Adds the given {@link Parameter} to the {@link ParameterizedElement}
*
*
* @param parameter
* the {@link Parameter} to add
* the {@link Parameter} to add
*/
public void addParameter(Parameter<?> parameter) {
assertNotReadonly();
if (this.parameterMap == null) {
this.parameterMap = new HashMap<>(1, 1.0F);
}
@ -147,14 +152,15 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Removes the {@link Parameter} with the given key
*
*
* @param key
* the key of the {@link Parameter} to remove
*
* the key of the {@link Parameter} to remove
*
* @return the removed {@link Parameter}, or null if it does not exist
*/
@SuppressWarnings("unchecked")
public <U, T extends Parameter<U>> T removeParameter(String key) {
assertNotReadonly();
if (this.parameterMap == null) {
return null;
}
@ -163,7 +169,7 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Returns a list of all the {@link Parameter}s in this {@link ParameterizedElement}
*
*
* @return a list of all the {@link Parameter}s in this {@link ParameterizedElement}
*/
public List<Parameter<?>> getParameters() {
@ -175,10 +181,10 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Returns a list of all the {@link Parameter Parameters} with the given interpretation
*
*
* @param interpretation
* the interpretation for which the parameters are to be returned
*
* the interpretation for which the parameters are to be returned
*
* @return the parameters with the given interpretation
*/
public List<Parameter<?>> getParametersByInterpretation(String interpretation) {
@ -192,12 +198,12 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Returns a list of all the {@link Parameter Parameters} with the given interpretation
*
*
* @param interpretation
* the interpretation for which the parameters are to be returned
* the interpretation for which the parameters are to be returned
* @param uom
* the uom for which the parameters are to be returned
*
* the uom for which the parameters are to be returned
*
* @return the parameters with the given interpretation
*/
public List<Parameter<?>> getParametersByInterpretationAndUom(String interpretation, String uom) {
@ -212,7 +218,7 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Returns true, if the this {@link ParameterizedElement} has any {@link Parameter Parameters}, false otherwise
*
*
* @return true, if the this {@link ParameterizedElement} has any {@link Parameter Parameters}, false otherwise
*/
public boolean hasParameters() {
@ -221,10 +227,10 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Returns true, if the {@link Parameter} exists with the given key, false otherwise
*
*
* @param key
* the key of the {@link Parameter} to check for
*
* the key of the {@link Parameter} to check for
*
* @return true, if the {@link Parameter} exists with the given key, false otherwise
*/
public boolean hasParameter(String key) {
@ -236,7 +242,7 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Returns a {@link Set} of all the {@link Parameter} keys in this {@link ParameterizedElement}
*
*
* @return a {@link Set} of all the {@link Parameter} keys in this {@link ParameterizedElement}
*/
public Set<String> getParameterKeySet() {
@ -268,6 +274,16 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
}
}
@Override
public void setReadOnly() {
if (this.parameterMap != null) {
for (Parameter<?> param : this.parameterMap.values()) {
param.setReadOnly();
}
}
super.setReadOnly();
}
@Override
public GroupedParameterizedElement getParent() {
return this.parent;
@ -275,11 +291,12 @@ public abstract class ParameterizedElement extends AbstractStrolchElement {
/**
* Set the parent for this {@link ParameterizedElement}
*
*
* @param parent
* the parent to set
* the parent to set
*/
public void setParent(GroupedParameterizedElement parent) {
assertNotReadonly();
this.parent = parent;
}

View File

@ -7,18 +7,18 @@ import li.strolch.model.policy.PolicyDefs;
/**
* A {@link PolicyContainer} has a reference to {@link PolicyDefs} on which Policy configurations are stored for the
* given object
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public interface PolicyContainer {
/**
* Returns the reference to the {@link PolicyDefs}
*
*
* @return the reference to the {@link PolicyDefs}
*
*
* @throws StrolchPolicyException
* if no {@link PolicyDefs} are available
* if no {@link PolicyDefs} are available
*/
public PolicyDefs getPolicyDefs() throws StrolchPolicyException;
@ -29,29 +29,39 @@ public interface PolicyContainer {
/**
* Returns true if this container has the {@link PolicyDef} with the given type, false if not
*
*
* @param type
* the type of policy def to return
*
* the type of policy def to return
*
* @return true if this container has the {@link PolicyDef} with the given type, false if not
*/
public boolean hasPolicyDef(String type);
/**
* Returns the {@link PolicyDef} for the given type
*
*
* @param type
* the type of policy def to return
*
* the type of policy def to return
*
* @return the policy def of the given type
*/
public PolicyDef getPolicyDef(String type);
/**
* Returns the {@link PolicyDef} for the given class
*
* @param clazz
* the type of policy def to return
*
* @return the policy def of the given class
*/
public PolicyDef getPolicyDef(Class<?> clazz);
/**
* Set the reference to the {@link PolicyDefs}
*
*
* @param policyDefs
* the {@link PolicyDefs} to set
* the {@link PolicyDefs} to set
*/
public void setPolicyDefs(PolicyDefs policyDefs);
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -56,8 +56,11 @@ public class Resource extends AbstractStrolchRootElement implements StrolchRootE
* Default constructor
*
* @param id
* the id
* @param name
* the name
* @param type
* the type
*/
public Resource(String id, String name, String type) {
super(id, name, type);
@ -90,6 +93,7 @@ public class Resource extends AbstractStrolchRootElement implements StrolchRootE
@SuppressWarnings("unchecked")
public void addTimedState(StrolchTimedState<?> strolchTimedState) {
assertNotReadonly();
if (this.timedStateMap == null) {
this.timedStateMap = new HashMap<>(1, 1.0F);
}
@ -127,6 +131,7 @@ public class Resource extends AbstractStrolchRootElement implements StrolchRootE
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T extends StrolchTimedState> T removeTimedState(String id) {
assertNotReadonly();
if (this.timedStateMap == null) {
return null;
}
@ -162,6 +167,11 @@ public class Resource extends AbstractStrolchRootElement implements StrolchRootE
return this.policyDefs;
}
@Override
public PolicyDef getPolicyDef(Class<?> clazz) {
return getPolicyDefs().getPolicyDef(clazz.getSimpleName());
}
@Override
public PolicyDef getPolicyDef(String type) {
return getPolicyDefs().getPolicyDef(type);
@ -179,12 +189,19 @@ public class Resource extends AbstractStrolchRootElement implements StrolchRootE
@Override
public void setPolicyDefs(PolicyDefs policyDefs) {
assertNotReadonly();
this.policyDefs = policyDefs;
this.policyDefs.setParent(this);
}
@Override
public Resource getClone() {
return getClone(false);
}
@Override
public Resource getClone(boolean withVersion) {
Resource clone = new Resource();
super.fillClone(clone);
@ -198,9 +215,24 @@ public class Resource extends AbstractStrolchRootElement implements StrolchRootE
if (this.policyDefs != null)
clone.setPolicyDefs(this.policyDefs.getClone());
if (withVersion)
clone.setVersion(this.version);
return clone;
}
@Override
public void setReadOnly() {
if (this.policyDefs != null)
this.policyDefs.setReadOnly();
if (this.timedStateMap != null) {
for (StrolchTimedState<IValue<?>> timedState : this.timedStateMap.values()) {
timedState.setReadOnly();
}
}
super.setReadOnly();
}
@Override
public void fillLocator(LocatorBuilder lb) {
lb.append(Tags.RESOURCE).append(getType()).append(getId());

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,6 +17,8 @@ package li.strolch.model;
import java.io.Serializable;
import li.strolch.model.visitor.StrolchElementVisitor;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@ -63,7 +65,7 @@ public interface StrolchElement extends Serializable {
* Set the currently set long value which defines the primary key for use in RDBM-Systems
*
* @param dbid
* the dbid to set
* the dbid to set
*/
public void setDbid(long dbid);
@ -88,14 +90,14 @@ public interface StrolchElement extends Serializable {
/**
* Returns the {@link StrolchRootElement} for this {@link StrolchElement}
*
*
* @return the {@link StrolchRootElement} for this {@link StrolchElement}
*/
public StrolchRootElement getRootElement();
/**
* Returns true if this element is a {@link StrolchRootElement}, false if not
*
*
* @return true if this element is a {@link StrolchRootElement}, false if not
*/
public boolean isRootElement();
@ -107,19 +109,31 @@ public interface StrolchElement extends Serializable {
*/
public StrolchElement getClone();
/**
* Returns true if this element is read only, in which case modifications will throw an exception. To modify it, call {@link #getClone()}
*
* @return true if this element is read only
*/
public boolean isReadOnly();
/**
* Sets this element to readOnly, so that it may not be modified. To modify it, call {@link #getClone()}
*/
public void setReadOnly();
/**
* <p>
* Returns the hashcode of this element.
* </p>
*
*
* <p>
* For most {@link StrolchElement} the equals and hashcode methods would only take into account the ID of the
* element, but certain implementations might require more specific attributes
* </p>
*
* @see Object#hashCode()
*
*
* @return the hashcode of this element
*
* @see Object#hashCode()
*/
@Override
public int hashCode();
@ -128,19 +142,21 @@ public interface StrolchElement extends Serializable {
* <p>
* Returns true if this object equals the given parameter object
* </p>
*
*
* <p>
* For most {@link StrolchElement} the equals and hashcode methods would only take into account the ID of the
* element, but certain implementations might require more specific attributes
* </p>
*
* @see Object#equals(Object)
*
*
* @param obj
* the object to which to check for equality
*
* the object to which to check for equality
*
* @return true if this object equals the given parameter object
*
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object obj);
public <U> U accept(StrolchElementVisitor<U> visitor);
}

View File

@ -15,6 +15,7 @@
*/
package li.strolch.model;
import li.strolch.model.activity.Activity;
import li.strolch.model.parameter.Parameter;
public class StrolchModelConstants {

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -37,7 +37,8 @@ public interface StrolchRootElement extends StrolchElement, PolicyContainer, Par
* Set the type of this {@link StrolchRootElement}. Not that this method should only be called for new elements, not
* if this element has already been persisted!
*
* @param type the new type
* @param type
* the new type
*/
public void setType(String type);
@ -76,6 +77,13 @@ public interface StrolchRootElement extends StrolchElement, PolicyContainer, Par
@Override
public StrolchRootElement getClone();
/**
* Return a clone of this {@link StrolchElement}
*
* @return a clone of this {@link StrolchElement}
*/
public StrolchRootElement getClone(boolean withVersion);
/**
* Visitor pattern accept method. Takes a {@link StrolchRootElementVisitor} to visit this element
*

View File

@ -1,12 +1,12 @@
/*
* Copyright 2015 Martin Smock <martin.smock@bluewin.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -17,33 +17,24 @@
package li.strolch.model.activity;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.*;
import li.strolch.exception.StrolchModelException;
import li.strolch.exception.StrolchPolicyException;
import li.strolch.model.GroupedParameterizedElement;
import li.strolch.model.Locator;
import li.strolch.model.*;
import li.strolch.model.Locator.LocatorBuilder;
import li.strolch.model.PolicyContainer;
import li.strolch.model.Resource;
import li.strolch.model.State;
import li.strolch.model.Tags;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.policy.PolicyDef;
import li.strolch.model.policy.PolicyDefs;
import li.strolch.model.timevalue.IValue;
import li.strolch.model.timevalue.IValueChange;
import li.strolch.model.visitor.IActivityElementVisitor;
import li.strolch.model.visitor.StrolchElementVisitor;
/**
* An {@link Action} represents a single step within an {@link Activity}, that is, one that is not further decomposed
* within the {@link Activity}. A {@link Activity} applies {@link IValueChange} objects at the start and end time of the
* {@link Activity}.
*
*
* @author Martin Smock <martin.smock@bluewin.ch>
*/
public class Action extends GroupedParameterizedElement implements IActivityElement, PolicyContainer {
@ -91,9 +82,10 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
/**
* @param resourceId
* the id of the {@link Resource} the {@link Action} acts on
* the id of the {@link Resource} the {@link Action} acts on
*/
public void setResourceId(String resourceId) {
assertNotReadonly();
this.resourceId = resourceId;
}
@ -107,9 +99,10 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
/**
* @param state
* the target <code>State</code> of the a<code>Action</code>
* the target <code>State</code> of the a<code>Action</code>
*/
public void setState(State state) {
assertNotReadonly();
this.state = state;
}
@ -122,14 +115,16 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
/**
* @param resourceType
* the resource type
*/
public void setResourceType(String resourceType) {
assertNotReadonly();
this.resourceType = resourceType;
}
/**
* Returns true if this {@link Action} contains any {@link IValueChange changes}, false if not
*
*
* @return true if this {@link Action} contains any {@link IValueChange changes}, false if not
*/
public boolean hasChanges() {
@ -137,12 +132,13 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
}
/**
* @param add
* <code>IValueChange</code> to be applied to the <code>Resource</code>
*
* @param change
* <code>IValueChange</code> to be applied to the <code>Resource</code>
*
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean addChange(IValueChange<? extends IValue<?>> change) {
assertNotReadonly();
initChanges();
return this.changes.add(change);
}
@ -158,7 +154,7 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
public Iterator<IValueChange<? extends IValue<?>>> changesIterator() {
if (this.changes == null)
return Collections.<IValueChange<? extends IValue<?>>> emptyList().iterator();
return Collections.<IValueChange<? extends IValue<?>>>emptyList().iterator();
return this.changes.iterator();
}
@ -195,6 +191,18 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
return clone;
}
@Override
public void setReadOnly() {
if (this.policyDefs != null)
this.policyDefs.setReadOnly();
if (this.changes != null) {
for (IValueChange<? extends IValue<?>> change : changes) {
change.setReadOnly();
}
}
super.setReadOnly();
}
@Override
public PolicyDefs getPolicyDefs() {
if (this.policyDefs == null)
@ -212,6 +220,11 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
return this.policyDefs != null;
}
@Override
public PolicyDef getPolicyDef(Class<?> clazz) {
return getPolicyDefs().getPolicyDef(clazz.getSimpleName());
}
@Override
public boolean hasPolicyDef(String type) {
return this.policyDefs != null && policyDefs.hasPolicyDef(type);
@ -219,6 +232,7 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
@Override
public void setPolicyDefs(PolicyDefs policyDefs) {
assertNotReadonly();
this.policyDefs = policyDefs;
this.policyDefs.setParent(this);
}
@ -256,6 +270,7 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
@Override
public void setParent(Activity activity) {
assertNotReadonly();
this.parent = activity;
}
@ -309,7 +324,7 @@ public class Action extends GroupedParameterizedElement implements IActivityElem
}
@Override
public <T> T accept(IActivityElementVisitor<T> visitor) {
public <T> T accept(StrolchElementVisitor<T> visitor) {
return visitor.visitAction(this);
}
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2015 Martin Smock <martin.smock@bluewin.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -15,6 +15,11 @@
*/
package li.strolch.model.activity;
import java.text.MessageFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Stream;
import li.strolch.exception.StrolchException;
import li.strolch.exception.StrolchModelException;
import li.strolch.exception.StrolchPolicyException;
@ -23,19 +28,13 @@ import li.strolch.model.Locator.LocatorBuilder;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.policy.PolicyDef;
import li.strolch.model.policy.PolicyDefs;
import li.strolch.model.visitor.IActivityElementVisitor;
import li.strolch.model.visitor.StrolchElementVisitor;
import li.strolch.utils.dbc.DBC;
import java.text.MessageFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Stream;
/**
* Parameterized object grouping a collection of {@link Activity} and {@link Action} objects defining the process to be
* scheduled
*
*
* @author Martin Smock <martin.smock@bluewin.ch>
*/
public class Activity extends AbstractStrolchRootElement
@ -61,11 +60,11 @@ public class Activity extends AbstractStrolchRootElement
* Default constructor
*
* @param id
* the id
* the id
* @param name
* the name
* the name
* @param type
* the type
* the type
*/
public Activity(String id, String name, String type, TimeOrdering timeOrdering) {
super(id, name, type);
@ -82,6 +81,7 @@ public class Activity extends AbstractStrolchRootElement
}
public void setTimeOrdering(TimeOrdering timeOrdering) {
assertNotReadonly();
this.timeOrdering = timeOrdering;
}
@ -118,7 +118,7 @@ public class Activity extends AbstractStrolchRootElement
/**
* Returns true if this {@link Activity} contains any children i.e. any of {@link Action} or {@link Activity}
*
*
* @return true if this {@link Activity} contains any children i.e. any of {@link Action} or {@link Activity}
*/
public boolean hasElements() {
@ -128,12 +128,12 @@ public class Activity extends AbstractStrolchRootElement
/**
* Returns true if this {@link Activity} contains a child with the given id. The element instance type is ignored,
* i.e. {@link Action} or {@link Activity}
*
*
* @param id
* the id of the element to check for
*
* the id of the element to check for
*
* @return true if this {@link Activity} contains a child with the given id. The element instance type is ignored,
* i.e. {@link Action} or {@link Activity}
* i.e. {@link Action} or {@link Activity}
*/
public boolean hasElement(String id) {
return this.elements != null && this.elements.containsKey(id);
@ -141,12 +141,15 @@ public class Activity extends AbstractStrolchRootElement
/**
* add an activity element to the <code>LinkedHashMap</code> of <code>IActivityElements</code>
*
*
* @param activityElement
* the element to add
*
* @return the element added
*/
@SuppressWarnings("unchecked")
public <T extends IActivityElement> T addElement(IActivityElement activityElement) {
assertNotReadonly();
DBC.PRE.assertNotEquals("Can't add element to itself!", this, activityElement);
DBC.PRE.assertNull("Parent can't already be set!", activityElement.getParent());
@ -167,14 +170,15 @@ public class Activity extends AbstractStrolchRootElement
/**
* Removes the element with the given id and returns it, if it exists
*
*
* @param id
* the id of the element to remove
*
* the id of the element to remove
*
* @return the removed element, or null if it does not exist
*/
@SuppressWarnings("unchecked")
public <T extends IActivityElement> T remove(String id) {
assertNotReadonly();
IActivityElement element = this.elements.remove(id);
if (element != null)
element.setParent(null);
@ -183,9 +187,10 @@ public class Activity extends AbstractStrolchRootElement
/**
* get <code>IActivityElement</code> by id
*
*
* @param id
* the id of the <code>IActivityElement</code>
* the id of the <code>IActivityElement</code>
*
* @return IActivityElement
*/
@SuppressWarnings("unchecked")
@ -297,7 +302,7 @@ public class Activity extends AbstractStrolchRootElement
/**
* Returns all the actions as a flat list
*
*
* @return the list of actions
*/
public List<Action> getActionsAsFlatList() {
@ -317,10 +322,10 @@ public class Activity extends AbstractStrolchRootElement
/**
* Returns all the actions in the entire hierarchy with the given state
*
*
* @param state
* the state of the action to return
*
* the state of the action to return
*
* @return the list of actions with the given state
*/
public List<Action> getActionsWithState(State state) {
@ -340,10 +345,10 @@ public class Activity extends AbstractStrolchRootElement
/**
* Returns all the actions in the entire hierarchy with the given type
*
*
* @param type
* the type of action to return
*
* the type of action to return
*
* @return the list of actions with the given type
*/
public List<Action> getActionsByType(String type) {
@ -366,7 +371,7 @@ public class Activity extends AbstractStrolchRootElement
*/
public Iterator<Entry<String, IActivityElement>> elementIterator() {
if (this.elements == null)
return Collections.<String, IActivityElement> emptyMap().entrySet().iterator();
return Collections.<String, IActivityElement>emptyMap().entrySet().iterator();
return this.elements.entrySet().iterator();
}
@ -375,7 +380,7 @@ public class Activity extends AbstractStrolchRootElement
*/
public Stream<Entry<String, IActivityElement>> elementStream() {
if (this.elements == null)
return Collections.<String, IActivityElement> emptyMap().entrySet().stream();
return Collections.<String, IActivityElement>emptyMap().entrySet().stream();
return this.elements.entrySet().stream();
}
@ -419,6 +424,11 @@ public class Activity extends AbstractStrolchRootElement
return this.policyDefs;
}
@Override
public PolicyDef getPolicyDef(Class<?> clazz) {
return getPolicyDefs().getPolicyDef(clazz.getSimpleName());
}
@Override
public PolicyDef getPolicyDef(String type) {
return getPolicyDefs().getPolicyDef(type);
@ -436,6 +446,7 @@ public class Activity extends AbstractStrolchRootElement
@Override
public void setPolicyDefs(PolicyDefs policyDefs) {
assertNotReadonly();
this.policyDefs = policyDefs;
this.policyDefs.setParent(this);
}
@ -473,6 +484,12 @@ public class Activity extends AbstractStrolchRootElement
@Override
public Activity getClone() {
return getClone(false);
}
@Override
public Activity getClone(boolean withVersion) {
Activity clone = new Activity();
clone.timeOrdering = this.timeOrdering;
@ -488,9 +505,20 @@ public class Activity extends AbstractStrolchRootElement
if (this.policyDefs != null)
clone.setPolicyDefs(this.policyDefs.getClone());
if (withVersion)
clone.setVersion(this.version);
return clone;
}
@Override
public void setReadOnly() {
if (this.policyDefs != null)
this.policyDefs.setReadOnly();
elementStream().forEach(e -> e.getValue().setReadOnly());
super.setReadOnly();
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
@ -524,11 +552,6 @@ public class Activity extends AbstractStrolchRootElement
return visitor.visitActivity(this);
}
@Override
public <T> T accept(IActivityElementVisitor<T> visitor) {
return visitor.visitActivity(this);
}
@SuppressWarnings("unchecked")
@Override
public <U, T extends Parameter<U>> T findParameter(String bagKey, String paramKey) {
@ -562,6 +585,7 @@ public class Activity extends AbstractStrolchRootElement
@Override
public void setParent(Activity activity) {
assertNotReadonly();
this.parent = activity;
}

View File

@ -1,12 +1,12 @@
/*
* Copyright 2015 Martin Smock <martin.smock@bluewin.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -20,11 +20,11 @@ import li.strolch.model.GroupedParameterizedElement;
import li.strolch.model.State;
import li.strolch.model.StrolchElement;
import li.strolch.model.parameter.Parameter;
import li.strolch.model.visitor.IActivityElementVisitor;
import li.strolch.model.visitor.StrolchElementVisitor;
/**
* Marker for all child elements of {@link Activity} objects
*
*
* @author Martin Smock <martin.smock@bluewin.ch>
*/
public interface IActivityElement extends StrolchElement {
@ -46,7 +46,7 @@ public interface IActivityElement extends StrolchElement {
/**
* Set the parent
*
*
* @param activity
*/
public void setParent(Activity activity);
@ -56,11 +56,11 @@ public interface IActivityElement extends StrolchElement {
* Checks if this element contains the {@link Parameter}, or otherwise queries its parent, until the root element is
* reached.
* </p>
*
*
* <p>
* If the parameter does not exist, null is returned
* </p>
*
*
* @see GroupedParameterizedElement#getParameter(String, String)
*/
public <U, T extends Parameter<U>> T findParameter(String bagKey, String paramKey);
@ -70,11 +70,11 @@ public interface IActivityElement extends StrolchElement {
* Checks if this element contains the {@link Parameter}, or otherwise queries its parent, until the root element is
* reached.
* </p>
*
*
* <p>
* If the parameter does not exist and <code>assertExists</code> is true, then an
* </p>
*
*
* @see GroupedParameterizedElement#getParameter(String, String, boolean)
*/
public <U, T extends Parameter<U>> T findParameter(String bagKey, String paramKey, boolean assertExists)
@ -91,11 +91,11 @@ public interface IActivityElement extends StrolchElement {
/**
* Implements the visitor pattern. Concrete implementation will call the proper method on the visitor
*
*
* @param visitor
* the visitor to accept
*
* the visitor to accept
*
* @return the result of the visitor being accepted
*/
public <T> T accept(IActivityElementVisitor<T> visitor);
public <T> T accept(StrolchElementVisitor<T> visitor);
}

View File

@ -50,11 +50,11 @@ public class AuditQuery<U> implements StrolchQuery {
this.selections = new ArrayList<>();
}
public AuditVisitor<U> getAuditVisitor() {
public AuditVisitor<U> getVisitor() {
return this.auditVisitor;
}
public AuditQuery<U> setAuditVisitor(AuditVisitor<U> auditVisitor) {
public AuditQuery<U> setVisitor(AuditVisitor<U> auditVisitor) {
DBC.PRE.assertNotNull("auditVisitor", auditVisitor);
this.auditVisitor = auditVisitor;
return this;

View File

@ -1,12 +1,12 @@
/*
* Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -15,6 +15,13 @@
*/
package li.strolch.model.audit;
import java.text.MessageFormat;
import java.util.function.Consumer;
import li.strolch.model.Tags;
import li.strolch.utils.iso8601.ISO8601FormatFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
@ -22,4 +29,113 @@ import org.xml.sax.helpers.DefaultHandler;
*/
public class AuditSaxReader extends DefaultHandler {
private final Consumer<Audit> auditConsumer;
private Audit currentAudit;
private StringBuilder sb = new StringBuilder();
public AuditSaxReader(Consumer<Audit> auditConsumer) {
this.auditConsumer = auditConsumer;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch (qName) {
case Tags.AUDIT:
this.currentAudit = new Audit();
this.currentAudit.setId(Long.valueOf(attributes.getValue(Tags.Audit.ID)));
break;
case Tags.Audit.USERNAME:
case Tags.Audit.FIRSTNAME:
case Tags.Audit.LASTNAME:
case Tags.Audit.DATE:
case Tags.Audit.ELEMENT_TYPE:
case Tags.Audit.ELEMENT_SUB_TYPE:
case Tags.Audit.ELEMENT_ACCESSED:
case Tags.Audit.NEW_VERSION:
case Tags.Audit.ACTION:
case Tags.Audit.ACCESS_TYPE:
this.sb = new StringBuilder();
break;
default:
throw new IllegalArgumentException(
MessageFormat.format("The element ''{0}'' is unhandled!", qName)); //$NON-NLS-1$
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
switch (qName) {
case Tags.AUDIT:
this.auditConsumer.accept(this.currentAudit);
this.currentAudit = null;
break;
case Tags.Audit.USERNAME:
this.currentAudit.setUsername(this.sb.toString());
this.sb = null;
break;
case Tags.Audit.FIRSTNAME:
this.currentAudit.setFirstname(this.sb.toString());
this.sb = null;
break;
case Tags.Audit.LASTNAME:
this.currentAudit.setLastname(this.sb.toString());
this.sb = null;
break;
case Tags.Audit.DATE:
this.currentAudit.setDate(ISO8601FormatFactory.getInstance().parseDate(this.sb.toString()));
this.sb = null;
break;
case Tags.Audit.ELEMENT_TYPE:
this.currentAudit.setElementType(this.sb.toString());
this.sb = null;
break;
case Tags.Audit.ELEMENT_SUB_TYPE:
this.currentAudit.setElementSubType(this.sb.toString());
this.sb = null;
break;
case Tags.Audit.ELEMENT_ACCESSED:
this.currentAudit.setElementAccessed(this.sb.toString());
this.sb = null;
break;
case Tags.Audit.NEW_VERSION:
this.currentAudit.setNewVersion(ISO8601FormatFactory.getInstance().parseDate(this.sb.toString()));
this.sb = null;
break;
case Tags.Audit.ACTION:
this.currentAudit.setAction(this.sb.toString());
this.sb = null;
break;
case Tags.Audit.ACCESS_TYPE:
this.currentAudit.setAccessType(AccessType.valueOf(this.sb.toString()));
this.sb = null;
break;
default:
throw new IllegalArgumentException(
MessageFormat.format("The element ''{0}'' is unhandled!", qName)); //$NON-NLS-1$
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (this.sb != null)
this.sb.append(ch, start, length);
}
}

Some files were not shown because too many files have changed in this diff Show More