[New] Implemented a REST API to get components

Including an API to reload the configuration, which is WIP
This commit is contained in:
Robert von Burg 2023-07-27 17:41:34 +02:00
parent cc8fcc688e
commit f3d5318a6f
Signed by: eitch
GPG Key ID: 75DB9C85C74331F7
10 changed files with 473 additions and 256 deletions

View File

@ -15,8 +15,6 @@
*/
package li.strolch.agent.api;
import java.util.Set;
import li.strolch.exception.StrolchException;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.model.Certificate;
@ -25,6 +23,9 @@ import li.strolch.runtime.privilege.PrivilegeHandler;
import li.strolch.runtime.privilege.PrivilegedRunnable;
import li.strolch.runtime.privilege.PrivilegedRunnableWithResult;
import java.util.List;
import java.util.Set;
/**
* Strolch's Container for all its components
*
@ -39,8 +40,7 @@ public interface ComponentContainer {
/**
* Returns true if the given component is registered on this container
*
* @param clazz
* the type of component to check for
* @param clazz the type of component to check for
*
* @return true if the component is available
*/
@ -50,33 +50,51 @@ public interface ComponentContainer {
* 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
* @param clazz the type of component to return
*
* @return the component with the given name
*
* @throws IllegalArgumentException
* if the component does not exist
* @throws IllegalArgumentException if the component does not exist
*/
<T> T getComponent(Class<T> clazz) throws IllegalArgumentException;
/**
* 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 name the name of the component to return
*
* @return the component with the given name
*
* @throws IllegalArgumentException if the component does not exist with the given name
*/
<T extends StrolchComponent> T getComponentByName(String name) throws IllegalArgumentException;
/**
* Returns a list of all the components, sorted by their dependencies, with the first having no dependencies, sorted
* by name
*
* @return a list of all the components
*/
List<StrolchComponent> getComponentsOrderedByRoot();
PrivilegeHandler getPrivilegeHandler() throws IllegalArgumentException;
Set<Class<?>> getComponentTypes();
Set<String> getComponentNames();
Set<String> getRealmNames();
/**
* Returns the {@link StrolchRealm} with the given name. To get the default realm, use the constant {@link
* StrolchConstants#DEFAULT_REALM}.
* Returns the {@link StrolchRealm} with the given name. To get the default realm, use the constant
* {@link StrolchConstants#DEFAULT_REALM}.
*
* @param realm
* the name of the {@link StrolchRealm} to return
* @param realm the name of the {@link StrolchRealm} to return
*
* @return the {@link StrolchRealm} with the given name
*
* @throws StrolchException
* if the {@link StrolchRealm} does not exist with the given name
* @throws StrolchException if the {@link StrolchRealm} does not exist with the given name
*/
StrolchRealm getRealm(String realm) throws StrolchException;
@ -84,44 +102,37 @@ public interface ComponentContainer {
* Returns the default {@link StrolchRealm} for the user with the given {@link Certificate}. This is done by
* querying the property {@link StrolchConstants#PROP_REALM} from the certificate.
*
* @param certificate
* the {@link Certificate} from which to retrieve the name of the {@link StrolchRealm} to return
* @param certificate the {@link Certificate} from which to retrieve the name of the {@link StrolchRealm} to return
*
* @return the {@link StrolchRealm}
*
* @throws StrolchException
* if the user does not have a {@link StrolchConstants#PROP_REALM} property configured, and the default realm is
* not configured, or if the realm does not exist with the found value
* @throws StrolchException if the user does not have a {@link StrolchConstants#PROP_REALM} property configured, and
* the default realm is not configured, or if the realm does not exist with the found
* value
*/
StrolchRealm getRealm(Certificate certificate) throws StrolchException;
/**
* Performs the given {@link PrivilegedRunnable} as the privileged system user {@link
* StrolchConstants#SYSTEM_USER_AGENT}
* Performs the given {@link PrivilegedRunnable} as the privileged system user
* {@link StrolchConstants#SYSTEM_USER_AGENT}
*
* @param runnable
* the runnable to perform
* @param runnable the runnable to perform
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
* @throws Exception
* if anything else goes wrong during execution
* @throws PrivilegeException if the given username is not allowed to perform the action
* @throws Exception if anything else goes wrong during execution
*/
void runAsAgent(PrivilegedRunnable runnable) throws PrivilegeException, Exception;
/**
* Performs the given {@link PrivilegedRunnable} as the privileged system user {@link
* StrolchConstants#SYSTEM_USER_AGENT}
* Performs the given {@link PrivilegedRunnable} as the privileged system user
* {@link StrolchConstants#SYSTEM_USER_AGENT}
*
* @param runnable
* the runnable to perform
* @param runnable the runnable to perform
*
* @return the result
*
* @throws PrivilegeException
* if the given username is not allowed to perform the action
* @throws Exception
* if anything else goes wrong during execution
* @throws PrivilegeException if the given username is not allowed to perform the action
* @throws Exception if anything else goes wrong during execution
*/
<T> T runAsAgentWithResult(PrivilegedRunnableWithResult<T> runnable) throws PrivilegeException, Exception;
}

View File

@ -32,27 +32,31 @@ public enum ComponentState {
return this;
switch (this) {
case UNDEFINED -> {
if (newState != ComponentState.SETUP && newState != STOPPED)
throw getIllegalStateEx(newState, componentName);
}
case SETUP -> {
if (newState != ComponentState.INITIALIZED && newState != STOPPED && newState != DESTROYED)
throw getIllegalStateEx(newState, componentName);
}
case INITIALIZED -> {
if (newState != ComponentState.STARTED && newState != STOPPED && newState != DESTROYED)
throw getIllegalStateEx(newState, componentName);
}
case STARTED -> {
if (newState != ComponentState.STOPPED)
throw getIllegalStateEx(newState, componentName);
}
case STOPPED -> {
if (newState != ComponentState.STARTED && newState != ComponentState.DESTROYED)
throw getIllegalStateEx(newState, componentName);
}
default -> throw getIllegalStateEx(newState, componentName);
case UNDEFINED -> {
if (newState != ComponentState.SETUP && newState != STOPPED)
throw getIllegalStateEx(newState, componentName);
}
case SETUP -> {
if (newState != ComponentState.INITIALIZED && newState != STOPPED && newState != DESTROYED)
throw getIllegalStateEx(newState, componentName);
}
case INITIALIZED -> {
if (newState != ComponentState.STARTED && newState != STOPPED && newState != DESTROYED)
throw getIllegalStateEx(newState, componentName);
}
case STARTED -> {
if (newState != ComponentState.STOPPED)
throw getIllegalStateEx(newState, componentName);
}
case STOPPED -> {
if (newState != ComponentState.STARTED && newState != ComponentState.DESTROYED)
throw getIllegalStateEx(newState, componentName);
}
case DESTROYED -> {
if (newState != ComponentState.SETUP)
throw getIllegalStateEx(newState, componentName);
}
default -> throw getIllegalStateEx(newState, componentName);
}
return newState;

View File

@ -15,20 +15,6 @@
*/
package li.strolch.agent.api;
import static li.strolch.model.Tags.Json.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.*;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import li.strolch.agent.impl.ComponentContainerImpl;
@ -36,7 +22,7 @@ import li.strolch.exception.StrolchException;
import li.strolch.model.Locator;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.runtime.configuration.ConfigurationParser;
import li.strolch.runtime.configuration.ComponentConfiguration;
import li.strolch.runtime.configuration.RuntimeConfiguration;
import li.strolch.runtime.configuration.StrolchConfiguration;
import li.strolch.runtime.privilege.PrivilegeHandler;
@ -50,6 +36,19 @@ import li.strolch.utils.iso8601.ISO8601;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.*;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static li.strolch.model.Tags.Json.*;
import static li.strolch.runtime.configuration.ConfigurationParser.parseConfiguration;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@ -111,6 +110,20 @@ public class StrolchAgent {
return this.container.getComponent(clazz);
}
/**
* @see ComponentContainer#getComponentByName(String)
*/
public <T extends StrolchComponent> T getComponentByName(String name) {
return getContainer().getComponentByName(name);
}
/**
* @see ComponentContainer#getComponentsOrderedByRoot()
*/
public List<StrolchComponent> getComponentsOrderedByRoot() {
return this.container.getComponentsOrderedByRoot();
}
public PrivilegeHandler getPrivilegeHandler() throws IllegalArgumentException {
return this.container.getPrivilegeHandler();
}
@ -301,14 +314,10 @@ public class StrolchAgent {
* 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
* @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) {
@ -319,8 +328,7 @@ public class StrolchAgent {
logger.info(" - Temp: " + tempPathF.getAbsolutePath());
logger.info(" - user.dir: " + SystemHelper.getUserDir());
this.strolchConfiguration = ConfigurationParser.parseConfiguration(environment, configPathF, dataPathF,
tempPathF);
this.strolchConfiguration = parseConfiguration(environment, configPathF, dataPathF, tempPathF);
ComponentContainerImpl container = new ComponentContainerImpl(this);
container.setup(this.strolchConfiguration);
@ -400,9 +408,8 @@ public class StrolchAgent {
public JsonObject getSystemState(long updateInterval, TimeUnit updateIntervalUnit) {
if (this.systemState == null
|| System.currentTimeMillis() - this.systemStateUpdateTime > updateIntervalUnit.toMillis(
updateInterval)) {
if (this.systemState == null ||
System.currentTimeMillis() - this.systemStateUpdateTime > updateIntervalUnit.toMillis(updateInterval)) {
this.systemState = new JsonObject();
JsonObject osJ = new JsonObject();
@ -458,4 +465,24 @@ public class StrolchAgent {
return this.systemState;
}
public void reloadStrolchConfiguration() {
RuntimeConfiguration runtimeConfig = this.strolchConfiguration.getRuntimeConfiguration();
File configPathF = runtimeConfig.getConfigPath();
File dataPathF = runtimeConfig.getDataPath();
File tempPathF = runtimeConfig.getTempPath();
StrolchConfiguration newStrolchConfig = parseConfiguration(runtimeConfig.getEnvironment(), configPathF,
dataPathF, tempPathF);
Map<String, ComponentConfiguration> configurationsByComponent = new HashMap<>();
for (String name : this.container.getComponentNames()) {
StrolchComponent existingComponent = this.container.getComponentByName(name);
Map<String, String> existingComponentConfig = existingComponent.getConfiguration().getAsMap();
ComponentConfiguration newComponentConfig = newStrolchConfig.getComponentConfiguration(name);
//existingComponent.getConfiguration().updateProperties(newComponentConfig.getAsMap());
}
// this.strolchConfiguration = new StrolchConfiguration(newStrolchConfig.getRuntimeConfiguration(),
// configurationsByComponent);
}
}

View File

@ -29,6 +29,7 @@ import li.strolch.runtime.configuration.StrolchConfigurationException;
import li.strolch.runtime.privilege.PrivilegeHandler;
import li.strolch.runtime.privilege.PrivilegedRunnable;
import li.strolch.runtime.privilege.PrivilegedRunnableWithResult;
import li.strolch.utils.dbc.DBC;
import li.strolch.utils.helper.SystemHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -50,12 +51,14 @@ public class ComponentContainerImpl implements ComponentContainer {
private static final Logger logger = LoggerFactory.getLogger(ComponentContainerImpl.class);
private final StrolchAgent agent;
private Map<Class<?>, StrolchComponent> componentMap;
private Map<Class<?>, StrolchComponent> componentsByType;
private Map<String, StrolchComponent> componentsByName;
private Map<String, ComponentController> controllerMap;
private ComponentDependencyAnalyzer dependencyAnalyzer;
private ComponentState state;
private ComponentContainerStateHandler containerStateHandler;
private StrolchConfiguration strolchConfiguration;
public ComponentContainerImpl(StrolchAgent agent) {
this.agent = agent;
@ -74,18 +77,23 @@ public class ComponentContainerImpl implements ComponentContainer {
@Override
public Set<Class<?>> getComponentTypes() {
return this.componentMap.keySet();
return this.componentsByType.keySet();
}
@Override
public Set<String> getComponentNames() {
return this.componentsByName.keySet();
}
@Override
public boolean hasComponent(Class<?> clazz) {
return this.componentMap != null && this.componentMap.containsKey(clazz);
return this.componentsByType != null && this.componentsByType.containsKey(clazz);
}
@Override
@SuppressWarnings("unchecked")
public <T> T getComponent(Class<T> clazz) throws IllegalArgumentException {
T component = (T) this.componentMap.get(clazz);
T component = (T) this.componentsByType.get(clazz);
if (component == null) {
String msg = "The component does not exist for class {0}";
msg = MessageFormat.format(msg, clazz.getName());
@ -94,6 +102,42 @@ public class ComponentContainerImpl implements ComponentContainer {
return component;
}
@Override
public <T extends StrolchComponent> T getComponentByName(String name) throws IllegalArgumentException {
@SuppressWarnings("unchecked") T component = (T) this.componentsByName.get(name);
if (component == null) {
String msg = "The component {0} does not exist!";
msg = MessageFormat.format(msg, name);
throw new IllegalArgumentException(msg);
}
return component;
}
@Override
public List<StrolchComponent> getComponentsOrderedByRoot() {
DBC.PRE.assertNotNull("Not yet started!", this.dependencyAnalyzer);
List<StrolchComponent> result = new ArrayList<>();
List<StrolchComponent> components = new ArrayList<>(this.componentsByType.values());
components.sort(Comparator.comparing(StrolchComponent::getName));
while (!components.isEmpty()) {
for (Iterator<StrolchComponent> iterator = components.iterator(); iterator.hasNext(); ) {
StrolchComponent component = iterator.next();
ComponentConfiguration configuration = strolchConfiguration.getComponentConfiguration(
component.getName());
Set<String> dependencies = configuration.getDependencies();
if (!dependencies.isEmpty() &&
dependencies.stream().map(this.componentsByName::get).noneMatch(result::contains))
continue;
result.add(component);
iterator.remove();
}
}
return result;
}
@Override
public PrivilegeHandler getPrivilegeHandler() throws IllegalArgumentException {
return getComponent(PrivilegeHandler.class);
@ -117,7 +161,8 @@ public class ComponentContainerImpl implements ComponentContainer {
if (getRealmNames().contains(DEFAULT_REALM)) {
realmName = DEFAULT_REALM;
} else {
String msg = "The User {0} is missing the property {1} and the Realm {2} can not be used as it does not exist!";
String msg
= "The User {0} is missing the property {1} and the Realm {2} can not be used as it does not exist!";
throw new StrolchException(
MessageFormat.format(msg, certificate.getUsername(), PROP_REALM, DEFAULT_REALM));
}
@ -126,7 +171,8 @@ public class ComponentContainerImpl implements ComponentContainer {
try {
return getComponent(RealmHandler.class).getRealm(realmName);
} catch (StrolchException e) {
String msg = "The User {0} has property {1} with value={2}, but the Realm does not eixst, or is not accessible by this user!";
String msg
= "The User {0} has property {1} with value={2}, but the Realm does not eixst, or is not accessible by this user!";
throw new StrolchException(MessageFormat.format(msg, certificate.getUsername(), PROP_REALM, realmName), e);
}
}
@ -141,14 +187,13 @@ public class ComponentContainerImpl implements ComponentContainer {
return getPrivilegeHandler().runAsAgentWithResult(runnable);
}
private void setupComponent(Map<Class<?>, StrolchComponent> componentMap,
private StrolchComponent setupComponent(Map<Class<?>, StrolchComponent> componentMap,
Map<String, ComponentController> controllerMap, ComponentConfiguration componentConfiguration) {
String componentName = componentConfiguration.getName();
if (isEmpty(componentName))
throw new IllegalStateException(
"name missing for a component in env " + componentConfiguration.getRuntimeConfiguration()
.getEnvironment());
throw new IllegalStateException("name missing for a component in env " +
componentConfiguration.getRuntimeConfiguration().getEnvironment());
try {
String api = componentConfiguration.getApi();
@ -163,7 +208,8 @@ public class ComponentContainerImpl implements ComponentContainer {
Class<?> implClass = Class.forName(impl);
if (!apiClass.isAssignableFrom(implClass)) {
String msg = "Component {0} has invalid configuration: Impl class {1} is not assignable to Api class {2}";
String msg
= "Component {0} has invalid configuration: Impl class {1} is not assignable to Api class {2}";
msg = MessageFormat.format(msg, componentName, impl, api);
throw new StrolchConfigurationException(msg);
}
@ -174,20 +220,27 @@ public class ComponentContainerImpl implements ComponentContainer {
throw new StrolchConfigurationException(msg);
}
@SuppressWarnings("unchecked")
Class<StrolchComponent> strolchComponentClass = (Class<StrolchComponent>) implClass;
@SuppressWarnings("unchecked") Class<StrolchComponent> strolchComponentClass
= (Class<StrolchComponent>) implClass;
Constructor<StrolchComponent> constructor = strolchComponentClass.getConstructor(ComponentContainer.class,
String.class);
StrolchComponent strolchComponent = constructor.newInstance(this, componentName);
strolchComponent.setup(componentConfiguration);
componentMap.put(apiClass, strolchComponent);
StrolchComponent existing = componentMap.put(apiClass, strolchComponent);
if (existing != null)
throw new IllegalStateException(
"Overwrote component " + existing.getName() + " with " + strolchComponent.getName() +
" as they share the same API Class!");
controllerMap.put(componentName, new ComponentController(strolchComponent));
return strolchComponent;
} catch (NoSuchMethodException e) {
String msg = "Could not load class for component {0} due to missing constructor with signature (ComponentContainer.class, String.class)";
msg = MessageFormat.format(msg, componentName, e.getMessage());
String msg
= "Could not load class for component {0} due to missing constructor with signature (ComponentContainer.class, String.class)";
msg = MessageFormat.format(msg, componentName);
throw new StrolchConfigurationException(msg, e);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SecurityException |
@ -200,6 +253,7 @@ public class ComponentContainerImpl implements ComponentContainer {
}
public void setup(StrolchConfiguration strolchConfiguration) {
this.strolchConfiguration = strolchConfiguration;
this.state.validateStateChange(ComponentState.SETUP, "agent");
long start = System.nanoTime();
@ -215,6 +269,7 @@ public class ComponentContainerImpl implements ComponentContainer {
// set up the container itself
Map<Class<?>, StrolchComponent> componentMap = new HashMap<>();
Map<String, StrolchComponent> componentsByName = new HashMap<>();
Map<String, ComponentController> controllerMap = new HashMap<>();
Set<String> componentNames = strolchConfiguration.getComponentNames();
for (String componentName : componentNames) {
@ -222,7 +277,8 @@ public class ComponentContainerImpl implements ComponentContainer {
componentName);
// setup each component
setupComponent(componentMap, controllerMap, componentConfiguration);
StrolchComponent component = setupComponent(componentMap, controllerMap, componentConfiguration);
componentsByName.put(component.getName(), component);
}
// then analyze dependencies
@ -230,7 +286,8 @@ public class ComponentContainerImpl implements ComponentContainer {
this.dependencyAnalyzer.setupDependencies();
// now save references
this.componentMap = componentMap;
this.componentsByType = componentMap;
this.componentsByName = componentsByName;
this.controllerMap = controllerMap;
// and configure the state handler
@ -240,7 +297,7 @@ public class ComponentContainerImpl implements ComponentContainer {
long took = System.nanoTime() - start;
msg = "{0}:{1} Strolch Container setup with {2} components. Took {3}";
logger.info(MessageFormat.format(msg, applicationName, environment, this.componentMap.size(),
logger.info(MessageFormat.format(msg, applicationName, environment, this.componentsByType.size(),
formatNanoDuration(took)));
}
@ -306,7 +363,8 @@ public class ComponentContainerImpl implements ComponentContainer {
}
}
msg = "{0}:{1} All {2} Strolch Components started for version {3}. Took {4}. Strolch is now ready to be used. Have fun =))";
msg
= "{0}:{1} All {2} Strolch Components started for version {3}. Took {4}. Strolch is now ready to be used. Have fun =))";
logger.info(MessageFormat.format(msg, applicationName, environment, this.controllerMap.size(),
getAgent().getVersion().getAppVersion().getArtifactVersion(), tookS));
}
@ -369,13 +427,13 @@ public class ComponentContainerImpl implements ComponentContainer {
logger.info(MessageFormat.format(msg, applicationName, environment, this.controllerMap.size(),
formatNanoDuration(took)));
this.controllerMap.clear();
this.componentMap.clear();
this.componentsByType.clear();
}
this.state = ComponentState.DESTROYED;
this.controllerMap = null;
this.componentMap = null;
this.componentsByType = null;
}
private String getApplicationName() {
@ -387,8 +445,7 @@ public class ComponentContainerImpl implements ComponentContainer {
}
private String getTimezone() {
return getAgent().getStrolchConfiguration()
.getRuntimeConfiguration()
return getAgent().getStrolchConfiguration().getRuntimeConfiguration()
.getString(PROP_TIMEZONE, System.getProperty("user.timezone"));
}
}

View File

@ -151,6 +151,8 @@ public class Tags {
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String ELEMENTS = "elements";
public static final String PROPERTIES = "properties";
public static final String DEPENDENCIES = "dependencies";
public static final String NR_OF_ELEMENTS = "nrOfElements";
public static final String ELEMENT_MAPS = "elementMaps";
public static final String TYPES = "types";

View File

@ -15,9 +15,6 @@
*/
package li.strolch.rest;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.agent.api.StrolchComponent;
@ -31,6 +28,9 @@ import li.strolch.runtime.privilege.PrivilegeHandler;
import li.strolch.service.api.ServiceHandler;
import li.strolch.utils.dbc.DBC;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@ -223,16 +223,20 @@ public class RestfulStrolchComponent extends StrolchComponent {
}
public StrolchAgent getAgent() {
return super.getContainer().getAgent();
return super.getAgent();
}
public PrivilegeHandler getPrivilegeHandler() {
return super.getContainer().getAgent().getContainer().getPrivilegeHandler();
return getAgent().getPrivilegeHandler();
}
@Override
public <T> T getComponent(Class<T> clazz) {
return getContainer().getComponent(clazz);
return getAgent().getComponent(clazz);
}
public <T extends StrolchComponent> T getComponentByName(String name) {
return getAgent().getComponentByName(name);
}
public StrolchSessionHandler getSessionHandler() {

View File

@ -45,6 +45,7 @@ public class StrolchRestfulClasses {
restfulClasses.add(EnumQuery.class);
restfulClasses.add(Languages.class);
restfulClasses.add(OperationsLogResource.class);
restfulClasses.add(AgentResource.class);
// privilege
restfulClasses.add(PrivilegeUsersService.class);

View File

@ -0,0 +1,116 @@
package li.strolch.rest.endpoint;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import li.strolch.agent.api.ComponentState;
import li.strolch.agent.api.StrolchComponent;
import li.strolch.model.Tags;
import li.strolch.privilege.model.Certificate;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.helper.ResponseUtil;
import li.strolch.runtime.configuration.ConfigurationParser;
import li.strolch.runtime.configuration.ConfigurationTags;
import li.strolch.runtime.configuration.RuntimeConfiguration;
import li.strolch.runtime.configuration.StrolchConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.List;
import java.util.Map;
import static li.strolch.rest.StrolchRestfulConstants.DATA;
import static li.strolch.rest.StrolchRestfulConstants.STROLCH_CERTIFICATE;
import static li.strolch.utils.helper.ExceptionHelper.getCallerMethodNoClass;
@Path("strolch/agent")
public class AgentResource {
private static final Logger logger = LoggerFactory.getLogger(AgentResource.class);
private static Certificate validateCertificate(HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
RestfulStrolchComponent rest = RestfulStrolchComponent.getInstance();
rest.validate(cert).validateAction(Tags.AGENT, getCallerMethodNoClass(2));
return cert;
}
@PUT
@Path("configuration/reload")
@Produces(MediaType.APPLICATION_JSON)
public Response reloadConfiguration(@Context HttpServletRequest request) {
validateCertificate(request);
RestfulStrolchComponent rest = RestfulStrolchComponent.getInstance();
rest.getAgent().reloadStrolchConfiguration();
return ResponseUtil.toResponse();
}
@GET
@Path("components")
@Produces(MediaType.APPLICATION_JSON)
public Response getComponents(@Context HttpServletRequest request) {
validateCertificate(request);
List<StrolchComponent> components = RestfulStrolchComponent.getInstance().getAgent()
.getComponentsOrderedByRoot();
JsonArray resultJ = new JsonArray();
for (StrolchComponent component : components) {
JsonObject componentJ = new JsonObject();
componentJ.addProperty(Tags.Json.NAME, component.getName());
componentJ.addProperty(ConfigurationTags.API, component.getConfiguration().getApi());
componentJ.addProperty(ConfigurationTags.IMPL, component.getConfiguration().getImpl());
componentJ.addProperty(Tags.Json.STATE, component.getState().name());
JsonArray propertiesJ = new JsonArray();
Map<String, String> properties = component.getConfiguration().getAsMap();
for (String key : properties.keySet()) {
JsonObject propertyJ = new JsonObject();
propertyJ.addProperty(Tags.Json.KEY, key);
propertyJ.addProperty(Tags.Json.VALUE, properties.get(key));
propertiesJ.add(propertyJ);
}
componentJ.add(Tags.Json.PROPERTIES, propertiesJ);
componentJ.add(Tags.Json.DEPENDENCIES, component.getConfiguration().getDependencies().stream()
.collect(JsonArray::new, JsonArray::add, JsonArray::addAll));
resultJ.add(componentJ);
}
return ResponseUtil.toResponse(DATA, resultJ);
}
@PUT
@Path("components/{name}/state")
@Produces(MediaType.APPLICATION_JSON)
public Response setComponentState(@Context HttpServletRequest request, @PathParam("name") String name,
@QueryParam("state") String newState) {
ComponentState state = ComponentState.valueOf(newState);
validateCertificate(request);
StrolchComponent component = RestfulStrolchComponent.getInstance().getComponentByName(name);
try {
switch (state) {
case INITIALIZED -> {
if (component.getState() == ComponentState.DESTROYED)
component.setup(component.getConfiguration());
component.initialize(component.getConfiguration());
}
case STARTED -> component.start();
case STOPPED -> component.stop();
case DESTROYED -> component.destroy();
}
} catch (Exception e) {
logger.error("Failed to change state of component " + name + " to state " + state, e);
return ResponseUtil.toResponse(e);
}
return ResponseUtil.toResponse();
}
}

View File

@ -26,7 +26,7 @@ import li.strolch.rest.helper.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Path("i18n")
@Path("strolch/i18n")
public class I18nService {
private static final Logger logger = LoggerFactory.getLogger(I18nService.class);

View File

@ -15,30 +15,10 @@
*/
package li.strolch.rest.endpoint;
import static java.util.Collections.emptySet;
import static java.util.Collections.sort;
import static li.strolch.model.StrolchModelConstants.ROLE_STROLCH_ADMIN;
import static li.strolch.rest.StrolchRestfulConstants.MSG;
import static li.strolch.rest.StrolchRestfulConstants.STROLCH_CERTIFICATE;
import static li.strolch.rest.helper.ResponseUtil.toResponse;
import static li.strolch.rest.helper.RestfulHelper.toJson;
import static li.strolch.search.SearchBuilder.orderBy;
import static li.strolch.utils.helper.ExceptionHelper.getCallerMethod;
import static li.strolch.utils.helper.ExceptionHelper.getCallerMethodNoClass;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.google.gson.*;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
@ -50,7 +30,10 @@ import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.OrderMap;
import li.strolch.agent.api.ResourceMap;
import li.strolch.exception.StrolchException;
import li.strolch.model.*;
import li.strolch.model.Locator;
import li.strolch.model.Order;
import li.strolch.model.Resource;
import li.strolch.model.Tags;
import li.strolch.model.Tags.Json;
import li.strolch.model.activity.Activity;
import li.strolch.model.json.*;
@ -74,6 +57,29 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static java.util.Collections.emptySet;
import static java.util.Collections.sort;
import static li.strolch.model.StrolchModelConstants.ROLE_STROLCH_ADMIN;
import static li.strolch.rest.StrolchRestfulConstants.MSG;
import static li.strolch.rest.StrolchRestfulConstants.STROLCH_CERTIFICATE;
import static li.strolch.rest.helper.ResponseUtil.toResponse;
import static li.strolch.rest.helper.RestfulHelper.toJson;
import static li.strolch.search.SearchBuilder.orderBy;
import static li.strolch.utils.helper.ExceptionHelper.getCallerMethod;
import static li.strolch.utils.helper.ExceptionHelper.getCallerMethodNoClass;
/**
* The RESTful inspector for Strolch. It allows to inspect the realms, and their respective elements. Supporting
* querying and retrieving, in multiple formats: XML, JSON and flat JSON
@ -85,22 +91,22 @@ public class Inspector {
private static final Logger logger = LoggerFactory.getLogger(Inspector.class);
private StrolchTransaction openTx(Certificate certificate, String realm) {
private static Certificate getCertificate(HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
RestfulStrolchComponent rest = RestfulStrolchComponent.getInstance();
if (!certificate.hasRole(ROLE_STROLCH_ADMIN))
rest.validate(certificate).validateAction(Inspector.class.getSimpleName(), getCallerMethodNoClass(2));
return rest.openTx(certificate, realm, getCallerMethod(2));
if (!cert.hasRole(ROLE_STROLCH_ADMIN))
rest.validate(cert).validateAction(Inspector.class.getSimpleName(), getCallerMethodNoClass(2));
return cert;
}
private String toString(JsonElement jsonElement) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(jsonElement);
private StrolchTransaction openTx(Certificate certificate, String realm) {
return RestfulStrolchComponent.getInstance().openTx(certificate, realm, getCallerMethod());
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAgentOverview(@Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
JsonObject agentOverview = new JsonObject();
JsonArray realmsArr = new JsonArray();
@ -124,7 +130,7 @@ public class Inspector {
}
}
return Response.ok().entity(toString(agentOverview)).build();
return Response.ok().entity(agentOverview.toString()).build();
}
@GET
@ -132,7 +138,7 @@ public class Inspector {
@Path("{realm}")
public Response getRealmOverview(@Context HttpServletRequest request, @PathParam("realm") String realm) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
JsonObject realmDetailJ = new JsonObject();
JsonArray elementMapsArr = new JsonArray();
@ -177,7 +183,7 @@ public class Inspector {
}
}
return Response.ok().entity(toString(realmDetailJ)).build();
return Response.ok().entity(realmDetailJ.toString()).build();
}
@GET
@ -185,7 +191,7 @@ public class Inspector {
@Path("{realm}/xml")
public Response exportRealmToXml(@Context HttpServletRequest request, @PathParam("realm") String realm) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
StreamingOutput streamingOutput = stream -> {
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -206,8 +212,7 @@ public class Inspector {
String fileName = "strolch_export_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
}
@GET
@ -215,7 +220,7 @@ public class Inspector {
@Path("{realm}/resources")
public Response getResourcesOverview(@Context HttpServletRequest request, @PathParam("realm") String realm) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
JsonObject mapOverview = new JsonObject();
@ -240,7 +245,7 @@ public class Inspector {
});
}
return Response.ok().entity(toString(mapOverview)).build();
return Response.ok().entity(mapOverview.toString()).build();
}
@GET
@ -248,7 +253,7 @@ public class Inspector {
@Path("{realm}/orders")
public Response getOrdersOverview(@Context HttpServletRequest request, @PathParam("realm") String realm) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
JsonObject mapOverview = new JsonObject();
@ -273,7 +278,7 @@ public class Inspector {
});
}
return Response.ok().entity(toString(mapOverview)).build();
return Response.ok().entity(mapOverview.toString()).build();
}
@GET
@ -281,7 +286,7 @@ public class Inspector {
@Path("{realm}/activities")
public Response getActivitiesOverview(@Context HttpServletRequest request, @PathParam("realm") String realm) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
JsonObject mapOverview = new JsonObject();
@ -306,7 +311,7 @@ public class Inspector {
});
}
return Response.ok().entity(toString(mapOverview)).build();
return Response.ok().entity(mapOverview.toString()).build();
}
@GET
@ -314,7 +319,7 @@ public class Inspector {
@Path("{realm}/resources/xml")
public Response exportResourcesToXml(@Context HttpServletRequest request, @PathParam("realm") String realm) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
StreamingOutput streamingOutput = stream -> {
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -333,8 +338,7 @@ public class Inspector {
String fileName = "strolch_export_resources_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
}
@GET
@ -342,7 +346,7 @@ public class Inspector {
@Path("{realm}/orders/xml")
public Response exportOrdersToXml(@Context HttpServletRequest request, @PathParam("realm") String realm) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
StreamingOutput streamingOutput = stream -> {
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -361,8 +365,7 @@ public class Inspector {
String fileName = "strolch_export_orders_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
}
@GET
@ -370,7 +373,7 @@ public class Inspector {
@Path("{realm}/activities/xml")
public Response exportActivitiesToXml(@Context HttpServletRequest request, @PathParam("realm") String realm) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
StreamingOutput streamingOutput = stream -> {
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -389,8 +392,7 @@ public class Inspector {
String fileName = "strolch_export_activities_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
}
@GET
@ -401,7 +403,7 @@ public class Inspector {
@QueryParam("overview") Boolean overview) {
queryData.initializeUnsetFields();
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
// parse the query string
ResourceSearch search = SearchBuilder.buildResourceSearch(queryData.getQuery(), type);
@ -435,7 +437,7 @@ public class Inspector {
JsonObject root = toJson(queryData, dataSetSize, result, visitor);
// marshall result
return Response.ok(toString(root)).build();
return Response.ok(root.toString()).build();
}
@GET
@ -446,7 +448,7 @@ public class Inspector {
@QueryParam("overview") Boolean overview) {
queryData.initializeUnsetFields();
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
// parse the query string
OrderSearch search = SearchBuilder.buildOrderSearch(queryData.getQuery(), type);
@ -482,7 +484,7 @@ public class Inspector {
JsonObject root = toJson(queryData, dataSetSize, result, visitor);
// marshall result
return Response.ok(toString(root)).build();
return Response.ok(root.toString()).build();
}
@GET
@ -493,7 +495,7 @@ public class Inspector {
@QueryParam("overview") Boolean overview) {
queryData.initializeUnsetFields();
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
// parse the query string
ActivitySearch search = SearchBuilder.buildActivitySearch(queryData.getQuery(), type);
@ -529,7 +531,7 @@ public class Inspector {
JsonObject root = toJson(queryData, dataSetSize, result, visitor);
// marshall result
return Response.ok(toString(root)).build();
return Response.ok(root.toString()).build();
}
@GET
@ -538,7 +540,7 @@ public class Inspector {
public Response exportResourcesOfTypeToXml(@BeanParam QueryData queryData, @PathParam("realm") String realm,
@PathParam("type") String type, @Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
queryData.initializeUnsetFields();
@ -562,8 +564,7 @@ public class Inspector {
String fileName = "strolch_export_resources_" + type + "_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
}
@GET
@ -572,7 +573,7 @@ public class Inspector {
public Response exportOrdersOfTypeToXml(@BeanParam QueryData queryData, @PathParam("realm") String realm,
@PathParam("type") String type, @Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
queryData.initializeUnsetFields();
@ -596,8 +597,7 @@ public class Inspector {
String fileName = "strolch_export_orders_" + type + "_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
}
@GET
@ -606,7 +606,7 @@ public class Inspector {
public Response exportActivitiesOfTypeToXml(@BeanParam QueryData queryData, @PathParam("realm") String realm,
@PathParam("type") String type, @Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
queryData.initializeUnsetFields();
@ -630,8 +630,7 @@ public class Inspector {
String fileName = "strolch_export_activities_" + type + "_" + realm + "_" + System.currentTimeMillis() + ".xml";
return Response.ok(streamingOutput, MediaType.APPLICATION_XML)
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
.build();
.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build();
}
@GET
@ -640,7 +639,7 @@ public class Inspector {
public Response getResourceAsJson(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id, @QueryParam("flat") String flat) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Resource resource;
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -654,7 +653,8 @@ public class Inspector {
if (Boolean.parseBoolean(flat))
visitor.flat();
return Response.ok().entity(toString(resource.accept(visitor))).build();
JsonElement jsonElement = resource.accept(visitor);
return Response.ok().entity(jsonElement.toString()).build();
}
@GET
@ -663,7 +663,7 @@ public class Inspector {
public Response getResourceAsXml(@PathParam("realm") String realm, @PathParam("type") String type,
@PathParam("id") String id, @Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Resource resource;
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -683,7 +683,7 @@ public class Inspector {
public Response getOrderAsJson(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id, @QueryParam("flat") String flat) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Order order;
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -696,7 +696,8 @@ public class Inspector {
StrolchElementToJsonVisitor visitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
if (Boolean.parseBoolean(flat))
visitor.flat();
return Response.ok().entity(toString(order.accept(visitor))).build();
JsonElement jsonElement = order.accept(visitor);
return Response.ok().entity(jsonElement.toString()).build();
}
@GET
@ -705,7 +706,7 @@ public class Inspector {
public Response getOrderAsXml(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Order order;
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -725,7 +726,7 @@ public class Inspector {
public Response getActivityAsJson(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id, @QueryParam("flat") String flat) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Activity activity;
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -738,7 +739,8 @@ public class Inspector {
StrolchElementToJsonVisitor visitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
if (Boolean.parseBoolean(flat))
visitor.flat();
return Response.ok().entity(toString(activity.accept(visitor))).build();
JsonElement jsonElement = activity.accept(visitor);
return Response.ok().entity(jsonElement.toString()).build();
}
@GET
@ -747,7 +749,7 @@ public class Inspector {
public Response getActivityAsXml(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Activity activity;
try (StrolchTransaction tx = openTx(cert, realm)) {
@ -768,7 +770,7 @@ public class Inspector {
public Response updateResourceAsXml(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Resource resource = parseResourceFromXml(type, data);
DBC.INTERIM.assertEquals("Posted id must be same as request!", id, resource.getId());
@ -795,7 +797,7 @@ public class Inspector {
public Response updateResourceAsJson(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id, @QueryParam("flat") String flatS, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
boolean flat = Boolean.parseBoolean(flatS);
UpdateResourceService svc = new UpdateResourceService();
@ -832,7 +834,8 @@ public class Inspector {
StrolchElementToJsonVisitor toJsonVisitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
if (flat)
toJsonVisitor.flat();
return Response.ok().entity(toString(resource.accept(toJsonVisitor))).build();
JsonElement jsonElement = resource.accept(toJsonVisitor);
return Response.ok().entity(jsonElement.toString()).build();
}
return toResponse(result);
@ -845,7 +848,7 @@ public class Inspector {
public Response updateOrderAsXml(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Order order = parseOrderFromXml(type, data);
DBC.INTERIM.assertEquals("Posted id must be same as request!", id, order.getId());
@ -872,7 +875,7 @@ public class Inspector {
public Response updateOrderAsJson(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id, @QueryParam("flat") String flatS, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
boolean flat = Boolean.parseBoolean(flatS);
UpdateOrderService svc = new UpdateOrderService();
@ -909,7 +912,8 @@ public class Inspector {
StrolchElementToJsonVisitor toJsonVisitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
if (flat)
toJsonVisitor.flat();
return Response.ok().entity(toString(order.accept(toJsonVisitor))).build();
JsonElement jsonElement = order.accept(toJsonVisitor);
return Response.ok().entity(jsonElement.toString()).build();
}
return toResponse(result);
@ -922,7 +926,7 @@ public class Inspector {
public Response updateActivityAsXml(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Activity activity = parseActivityFromXml(type, data);
DBC.INTERIM.assertEquals("Posted id must be same as request!", id, activity.getId());
@ -949,7 +953,7 @@ public class Inspector {
public Response updateActivityAsJson(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @PathParam("id") String id, @QueryParam("flat") String flatS, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
boolean flat = Boolean.parseBoolean(flatS);
UpdateActivityService svc = new UpdateActivityService();
@ -986,7 +990,8 @@ public class Inspector {
StrolchElementToJsonVisitor toJsonVisitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
if (flat)
toJsonVisitor.flat();
return Response.ok().entity(toString(activity.accept(toJsonVisitor))).build();
JsonElement jsonElement = activity.accept(toJsonVisitor);
return Response.ok().entity(jsonElement.toString()).build();
}
return toResponse(result);
@ -1007,7 +1012,7 @@ public class Inspector {
@QueryParam("updateActivities") boolean updateActivities, //
String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
File tempFile = null;
try {
@ -1061,7 +1066,7 @@ public class Inspector {
public Response addResourceAsXml(@Context HttpServletRequest request, @PathParam("realm") String realm,
String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Resource resource = parseResourceFromXml(null, data);
@ -1086,7 +1091,7 @@ public class Inspector {
public Response addResourceAsJson(@Context HttpServletRequest request, @PathParam("realm") String realm,
String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
// parse from complete JSON
JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject();
@ -1101,7 +1106,8 @@ public class Inspector {
ServiceResult result = getServiceHandler().doService(cert, svc, arg);
if (result.isOk()) {
StrolchElementToJsonVisitor toJsonVisitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
return Response.ok().entity(toString(resource.accept(toJsonVisitor))).build();
JsonElement jsonElement = resource.accept(toJsonVisitor);
return Response.ok().entity(jsonElement.toString()).build();
}
return toResponse(result);
@ -1114,7 +1120,7 @@ public class Inspector {
public Response addResourceAsJsonFlat(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @QueryParam("flat") String flatS, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
boolean flat = Boolean.parseBoolean(flatS);
Resource resource = parseNewResourceFromJson(cert, realm, type, data, flat);
@ -1129,7 +1135,8 @@ public class Inspector {
StrolchElementToJsonVisitor toJsonVisitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
if (flat)
toJsonVisitor.flat();
return Response.ok().entity(toString(resource.accept(toJsonVisitor))).build();
JsonElement jsonElement = resource.accept(toJsonVisitor);
return Response.ok().entity(jsonElement.toString()).build();
}
return toResponse(result);
@ -1141,7 +1148,7 @@ public class Inspector {
@Path("{realm}/orders")
public Response addOrderAsXml(@Context HttpServletRequest request, @PathParam("realm") String realm, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Order order = parseOrderFromXml(null, data);
@ -1165,7 +1172,7 @@ public class Inspector {
@Path("{realm}/orders")
public Response addOrderAsJson(@Context HttpServletRequest request, @PathParam("realm") String realm, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
// parse from complete JSON
JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject();
@ -1180,7 +1187,8 @@ public class Inspector {
ServiceResult result = getServiceHandler().doService(cert, svc, arg);
if (result.isOk()) {
StrolchElementToJsonVisitor toJsonVisitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
return Response.ok().entity(toString(order.accept(toJsonVisitor))).build();
JsonElement jsonElement = order.accept(toJsonVisitor);
return Response.ok().entity(jsonElement.toString()).build();
}
return toResponse(result);
@ -1193,7 +1201,7 @@ public class Inspector {
public Response addOrderAsJsonFlat(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @QueryParam("flat") String flatS, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
boolean flat = Boolean.parseBoolean(flatS);
Order order = parseNewOrderFromJson(cert, realm, type, data, flat);
@ -1208,7 +1216,8 @@ public class Inspector {
StrolchElementToJsonVisitor toJsonVisitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
if (flat)
toJsonVisitor.flat();
return Response.ok().entity(toString(order.accept(toJsonVisitor))).build();
JsonElement jsonElement = order.accept(toJsonVisitor);
return Response.ok().entity(jsonElement.toString()).build();
}
return toResponse(result);
@ -1221,7 +1230,7 @@ public class Inspector {
public Response addActivityAsXml(@Context HttpServletRequest request, @PathParam("realm") String realm,
String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
Activity activity = parseActivityFromXml(null, data);
@ -1246,7 +1255,7 @@ public class Inspector {
public Response addActivityAsJson(@Context HttpServletRequest request, @PathParam("realm") String realm,
String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
// parse from complete JSON
JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject();
@ -1261,7 +1270,8 @@ public class Inspector {
ServiceResult result = getServiceHandler().doService(cert, svc, arg);
if (result.isOk()) {
StrolchElementToJsonVisitor toJsonVisitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
return Response.ok().entity(toString(activity.accept(toJsonVisitor))).build();
JsonElement jsonElement = activity.accept(toJsonVisitor);
return Response.ok().entity(jsonElement.toString()).build();
}
return toResponse(result);
@ -1274,7 +1284,7 @@ public class Inspector {
public Response addActivityAsJsonFlat(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @QueryParam("flat") String flatS, String data) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
boolean flat = Boolean.parseBoolean(flatS);
Activity activity = parseNewActivityFromJson(cert, realm, type, data, flat);
@ -1289,7 +1299,8 @@ public class Inspector {
StrolchElementToJsonVisitor toJsonVisitor = new StrolchElementToJsonVisitor().withLocator().withVersion();
if (flat)
toJsonVisitor.flat();
return Response.ok().entity(toString(activity.accept(toJsonVisitor))).build();
JsonElement jsonElement = activity.accept(toJsonVisitor);
return Response.ok().entity(jsonElement.toString()).build();
}
return toResponse(result);
@ -1300,7 +1311,7 @@ public class Inspector {
public Response removeResourcesByType(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @QueryParam("ids") String ids) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
RemoveResourcesService svc = new RemoveResourcesService();
LocatorListArgument arg = svc.getArgumentInstance();
@ -1321,7 +1332,7 @@ public class Inspector {
public Response removeOrdersByType(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @QueryParam("ids") String ids) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
RemoveOrdersService svc = new RemoveOrdersService();
LocatorListArgument arg = svc.getArgumentInstance();
@ -1342,7 +1353,7 @@ public class Inspector {
public Response removeActivitiesByType(@Context HttpServletRequest request, @PathParam("realm") String realm,
@PathParam("type") String type, @QueryParam("ids") String ids) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
RemoveActivitiesService svc = new RemoveActivitiesService();
LocatorListArgument arg = svc.getArgumentInstance();
@ -1364,7 +1375,7 @@ public class Inspector {
public Response removeResource(@PathParam("realm") String realm, @PathParam("type") String type,
@PathParam("id") String id, @Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
RemoveResourceService svc = new RemoveResourceService();
LocatorArgument arg = svc.getArgumentInstance();
@ -1381,7 +1392,7 @@ public class Inspector {
public Response removeOrder(@PathParam("realm") String realm, @PathParam("type") String type,
@PathParam("id") String id, @Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
RemoveOrderService svc = new RemoveOrderService();
LocatorArgument arg = svc.getArgumentInstance();
@ -1398,7 +1409,7 @@ public class Inspector {
public Response removeActivity(@PathParam("realm") String realm, @PathParam("type") String type,
@PathParam("id") String id, @Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(STROLCH_CERTIFICATE);
Certificate cert = getCertificate(request);
RemoveActivityService svc = new RemoveActivityService();
LocatorArgument arg = svc.getArgumentInstance();
@ -1417,15 +1428,11 @@ public class Inspector {
parser.parse(new InputSource(new StringReader(data)), new XmlModelSaxReader(listener));
if (listener.getResources().size() == 0)
throw new StrolchPersistenceException(
"No Resource parsed from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type :
""));
throw new StrolchPersistenceException("No Resource parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
if (listener.getResources().size() > 1)
throw new StrolchPersistenceException(
"Multiple Resources parsed from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type :
""));
throw new StrolchPersistenceException("Multiple Resources parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
resource = listener.getResources().get(0);
resource.setVersion(null);
@ -1433,10 +1440,8 @@ public class Inspector {
DBC.INTERIM.assertEquals("Posted type must be same as request!", type, resource.getType());
} catch (Exception e) {
throw new StrolchPersistenceException(
"Failed to extract Resource from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type :
""), e);
throw new StrolchPersistenceException("Failed to extract Resource from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""), e);
}
return resource;
}
@ -1452,10 +1457,8 @@ public class Inspector {
throw new StrolchPersistenceException(
"No Order parsed from xml value" + (StringHelper.isNotEmpty(type) ? " for type " + type : ""));
if (listener.getOrders().size() > 1)
throw new StrolchPersistenceException(
"Multiple Orders parsed from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type :
""));
throw new StrolchPersistenceException("Multiple Orders parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
order = listener.getOrders().get(0);
order.setVersion(null);
@ -1463,10 +1466,8 @@ public class Inspector {
DBC.INTERIM.assertEquals("Posted type must be same as request!", type, order.getType());
} catch (Exception e) {
throw new StrolchPersistenceException(
"Failed to extract Order from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type :
""), e);
throw new StrolchPersistenceException("Failed to extract Order from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""), e);
}
return order;
}
@ -1479,15 +1480,11 @@ public class Inspector {
parser.parse(new InputSource(new StringReader(data)), new XmlModelSaxReader(listener));
if (listener.getActivities().size() == 0)
throw new StrolchPersistenceException(
"No Activity parsed from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type :
""));
throw new StrolchPersistenceException("No Activity parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
if (listener.getActivities().size() > 1)
throw new StrolchPersistenceException(
"Multiple Activities parsed from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type :
""));
throw new StrolchPersistenceException("Multiple Activities parsed from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""));
activity = listener.getActivities().get(0);
activity.setVersion(null);
@ -1495,10 +1492,8 @@ public class Inspector {
DBC.INTERIM.assertEquals("Posted type must be same as request!", type, activity.getType());
} catch (Exception e) {
throw new StrolchPersistenceException(
"Failed to extract Activity from xml value" + (StringHelper.isNotEmpty(type) ?
" for type " + type :
""), e);
throw new StrolchPersistenceException("Failed to extract Activity from xml value" +
(StringHelper.isNotEmpty(type) ? " for type " + type : ""), e);
}
return activity;
}