[Major] Removed the need for javax.xml.bind.* imports. Using gson

This commit is contained in:
Robert von Burg 2017-09-29 15:57:21 +02:00
parent 76e7403974
commit 2cb799dfb4
60 changed files with 1071 additions and 2083 deletions

View File

@ -1,4 +1,15 @@
<code_scheme name="strolch">
<option name="IMPORT_LAYOUT_TABLE">
<value>
<package name="" withSubpackages="true" static="true" />
<emptyLine />
<package name="javax" withSubpackages="true" static="false" />
<package name="java" withSubpackages="true" static="false" />
<emptyLine />
<package name="" withSubpackages="true" static="false" />
<emptyLine />
</value>
</option>
<option name="HTML_ATTRIBUTE_WRAP" value="4" />
<option name="HTML_KEEP_LINE_BREAKS" value="false" />
<option name="HTML_KEEP_LINE_BREAKS_IN_TEXT" value="false" />
@ -8,6 +19,12 @@
<JSCodeStyleSettings>
<option name="OBJECT_LITERAL_WRAP" value="2" />
</JSCodeStyleSettings>
<JavaCodeStyleSettings>
<option name="CLASS_NAMES_IN_JAVADOC" value="3" />
</JavaCodeStyleSettings>
<XML>
<option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
</XML>
<codeStyleSettings language="JAVA">
<option name="KEEP_LINE_BREAKS" value="false" />
<option name="KEEP_CONTROL_STATEMENT_IN_ONE_LINE" value="false" />
@ -40,9 +57,12 @@
<codeStyleSettings language="JSON">
<option name="KEEP_LINE_BREAKS" value="false" />
<option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
<indentOptions>
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
<codeStyleSettings language="JavaScript">
<option name="KEEP_LINE_BREAKS" value="false" />
<option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
<option name="ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION" value="true" />
<option name="ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE" value="true" />
<option name="ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE" value="true" />

View File

@ -17,54 +17,44 @@ package li.strolch.agent.api;
import java.util.Properties;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.gson.JsonObject;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "AgentVersion")
public class AgentVersion extends StrolchVersion {
@XmlAttribute(name = "agentName")
public static final String AGENT_NAME = "agentName";
private String agentName;
public AgentVersion() {
// no-arg constructor for JAXB
}
/**
* @param agentName
* @param properties
*/
public AgentVersion(String agentName, Properties properties) {
super(properties);
this.agentName = agentName;
}
/**
* @return the agentName
*/
public String getAgentName() {
return this.agentName;
}
/**
* @param agentName
* the agentName to set
*/
public void setAgentName(String agentName) {
this.agentName = agentName;
}
@SuppressWarnings("nls")
@Override
public JsonObject toJson() {
JsonObject jsonObject = super.toJson();
jsonObject.addProperty(AGENT_NAME, this.agentName);
return jsonObject;
}
@Override
public String toString() {
return "AgentVersion [agentName=" + this.agentName + ", groupId=" + getGroupId() + ", artifactId="
+ getArtifactId() + ", artifactVersion=" + getArtifactVersion() + ", scmRevision=" + getScmRevision()
+ ", scmBranch=" + getScmBranch() + ", buildTimestamp=" + getBuildTimestamp() + "]";
return "AgentVersion{agentName='" + this.agentName + "' , groupId='" + getGroupId() + "' , artifactId='"
+ getArtifactId() + "' , artifactVersion='" + getArtifactVersion() + "' , scmRevision='"
+ getScmRevision() + "' , scmBranch='" + getScmBranch() + "' , buildTimestamp='" + getBuildTimestamp()
+ "' }";
}
}

View File

@ -17,54 +17,44 @@ package li.strolch.agent.api;
import java.util.Properties;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.gson.JsonObject;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "ComponentVersion")
public class ComponentVersion extends StrolchVersion {
@XmlAttribute(name = "componentName")
private static final String COMPONENT_VERSION = "componentName";
private String componentName;
public ComponentVersion() {
// no-arg constructor for JAXB
}
/**
* @param componentName
* @param properties
*/
public ComponentVersion(String componentName, Properties properties) {
super(properties);
this.componentName = componentName;
}
/**
* @return the componentName
*/
public String getComponentName() {
return this.componentName;
}
/**
* @param componentName
* the componentName to set
*/
public void setComponentName(String componentName) {
this.componentName = componentName;
}
@SuppressWarnings("nls")
@Override
public JsonObject toJson() {
JsonObject jsonObject = super.toJson();
jsonObject.addProperty(COMPONENT_VERSION, this.componentName);
return jsonObject;
}
@Override
public String toString() {
return "ComponentVersion [componentName=" + this.componentName + ", groupId=" + getGroupId() + ", artifactId="
+ getArtifactId() + ", artifactVersion=" + getArtifactVersion() + ", scmRevision=" + getScmRevision()
+ ", scmBranch=" + getScmBranch() + ", buildTimestamp=" + getBuildTimestamp() + "]";
return "ComponentVersion{componentName='" + this.componentName + "' , groupId='" + getGroupId()
+ "' , artifactId='" + getArtifactId() + "' , artifactVersion='" + getArtifactVersion()
+ "' , scmRevision='" + getScmRevision() + "' , scmBranch='" + getScmBranch() + "' , buildTimestamp='"
+ getBuildTimestamp() + "' }";
}
}

View File

@ -17,14 +17,11 @@ package li.strolch.agent.api;
import java.util.Properties;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import com.google.gson.JsonObject;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlAccessorType(XmlAccessType.NONE)
public class StrolchVersion {
public static final String BUILD_TIMESTAMP = "buildTimestamp";
@ -34,122 +31,87 @@ public class StrolchVersion {
public static final String ARTIFACT_ID = "artifactId";
public static final String GROUP_ID = "groupId";
@XmlAttribute(name = GROUP_ID)
private String groupId;
@XmlAttribute(name = ARTIFACT_ID)
private String artifactId;
@XmlAttribute(name = ARTIFACT_VERSION)
private String artifactVersion;
@XmlAttribute(name = SCM_REVISION)
private String scmRevision;
@XmlAttribute(name = SCM_BRANCH)
private String scmBranch;
@XmlAttribute(name = BUILD_TIMESTAMP)
private String buildTimestamp;
public StrolchVersion() {
// no-arg constructor for JAXB
}
/**
* @param properties
*/
public StrolchVersion(Properties properties) {
this.groupId = properties.getProperty(GROUP_ID); //$NON-NLS-1$
this.artifactId = properties.getProperty(ARTIFACT_ID); //$NON-NLS-1$
this.artifactVersion = properties.getProperty(ARTIFACT_VERSION); //$NON-NLS-1$
this.scmRevision = properties.getProperty(SCM_REVISION); //$NON-NLS-1$
this.scmBranch = properties.getProperty(SCM_BRANCH); //$NON-NLS-1$
this.buildTimestamp = properties.getProperty(BUILD_TIMESTAMP); //$NON-NLS-1$
this.groupId = properties.getProperty(GROUP_ID);
this.artifactId = properties.getProperty(ARTIFACT_ID);
this.artifactVersion = properties.getProperty(ARTIFACT_VERSION);
this.scmRevision = properties.getProperty(SCM_REVISION);
this.scmBranch = properties.getProperty(SCM_BRANCH);
this.buildTimestamp = properties.getProperty(BUILD_TIMESTAMP);
}
/**
* @return the groupId
*/
public String getGroupId() {
return this.groupId;
}
/**
* @param groupId
* the groupId to set
*/
public void setGroupId(String groupId) {
this.groupId = groupId;
}
/**
* @return the artifactId
*/
public String getArtifactId() {
return this.artifactId;
}
/**
* @param artifactId
* the artifactId to set
*/
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
/**
* @return the artifactVersion
*/
public String getArtifactVersion() {
return this.artifactVersion;
}
/**
* @param artifactVersion
* the artifactVersion to set
*/
public void setArtifactVersion(String artifactVersion) {
this.artifactVersion = artifactVersion;
}
/**
* @return the scmRevision
*/
public String getScmRevision() {
return this.scmRevision;
}
/**
* @param scmRevision
* the scmRevision to set
*/
public void setScmRevision(String scmRevision) {
this.scmRevision = scmRevision;
}
/**
* @return the scmBranch
*/
public String getScmBranch() {
return this.scmBranch;
}
/**
* @param scmBranch
* the scmBranch to set
*/
public void setScmBranch(String scmBranch) {
this.scmBranch = scmBranch;
}
/**
* @return the buildTimestamp
*/
public String getBuildTimestamp() {
return this.buildTimestamp;
}
/**
* @param buildTimestamp
* the buildTimestamp to set
*/
public void setBuildTimestamp(String buildTimestamp) {
this.buildTimestamp = buildTimestamp;
}
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(GROUP_ID, this.groupId);
jsonObject.addProperty(ARTIFACT_ID, this.artifactId);
jsonObject.addProperty(ARTIFACT_VERSION, this.artifactVersion);
jsonObject.addProperty(SCM_REVISION, this.scmRevision);
jsonObject.addProperty(SCM_BRANCH, this.scmBranch);
jsonObject.addProperty(BUILD_TIMESTAMP, this.buildTimestamp);
return jsonObject;
}
@Override
public String toString() {
return "StrolchVersion{groupId='" + groupId + "' , artifactId='" + artifactId + "', artifactVersion='"
+ artifactVersion + "' , scmRevision='" + scmRevision + "' , scmBranch='" + scmBranch
+ "' , buildTimestamp='" + buildTimestamp + "' }";
}
}

View File

@ -18,57 +18,31 @@ package li.strolch.agent.api;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "VersionQueryResult")
public class VersionQueryResult {
@XmlElement(name = "appVersion", type = StrolchVersion.class)
private StrolchVersion appVersion;
@XmlElement(name = "agentVersion", type = AgentVersion.class)
private AgentVersion agentVersion;
@XmlElement(name = "componentVersions", type = ComponentVersion.class)
private List<ComponentVersion> componentVersions;
@XmlElement(name = "errors", type = String.class)
private List<String> errors;
public VersionQueryResult() {
// no-arg constructor for JAXB
}
/**
* @return the appVersion
*/
public StrolchVersion getAppVersion() {
return this.appVersion;
}
/**
* @param appVersion
* the appVersion to set
*/
public void setAppVersion(StrolchVersion appVersion) {
this.appVersion = appVersion;
}
/**
* @return the agentVersion
*/
public AgentVersion getAgentVersion() {
return this.agentVersion;
}
/**
* @param agentVersion
* the agentVersion to set
*/
public void setAgentVersion(AgentVersion agentVersion) {
this.agentVersion = agentVersion;
}
@ -87,40 +61,42 @@ public class VersionQueryResult {
this.errors.add(error);
}
/**
* @return the componentVersions
*/
public List<ComponentVersion> getComponentVersions() {
return this.componentVersions;
}
/**
* @param componentVersions
* the componentVersions to set
*/
public void setComponentVersions(List<ComponentVersion> componentVersions) {
this.componentVersions = componentVersions;
}
/**
* @return the errors
*/
public List<String> getErrors() {
return this.errors;
}
/**
* @param errors
* the errors to set
*/
public void setErrors(List<String> errors) {
this.errors = errors;
}
/**
* @return
*/
public boolean hasErrors() {
return this.errors != null && !this.errors.isEmpty();
}
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
jsonObject.add("appVersion", this.appVersion.toJson());
jsonObject.add("agentVersion", this.agentVersion.toJson());
JsonArray componentVersionsJ = new JsonArray();
this.componentVersions.forEach(c -> componentVersionsJ.add(c.toJson()));
jsonObject.add("componentVersions", componentVersionsJ);
if (this.errors != null) {
JsonArray errorsJ = new JsonArray();
this.errors.forEach(errorsJ::add);
jsonObject.add("errors", errorsJ);
}
return jsonObject;
}
}

View File

@ -46,10 +46,6 @@ public class DefaultEnumHandler extends StrolchComponent implements EnumHandler
private String realm;
private Map<String, Locator> enumLocators;
/**
* @param container
* @param componentName
*/
public DefaultEnumHandler(ComponentContainer container, String componentName) {
super(container, componentName);
}
@ -83,28 +79,24 @@ public class DefaultEnumHandler extends StrolchComponent implements EnumHandler
Locator enumLocator = this.enumLocators.get(name);
if (enumLocator == null)
throw new StrolchException(MessageFormat.format("No enumeration is configured for the name {0}", name)); //$NON-NLS-1$
throw new StrolchException(
MessageFormat.format("No enumeration is configured for the name {0}", name)); //$NON-NLS-1$
try (StrolchTransaction tx = getContainer().getRealm(this.realm).openTx(certificate, EnumHandler.class)) {
Resource enumeration = tx.findElement(enumLocator);
ParameterBag enumValuesByLanguage = findParameterBagByLanguage(enumeration, locale);
Set<String> parameterKeySet = enumValuesByLanguage.getParameterKeySet();
Map<String, EnumValue> values = new HashMap<>(parameterKeySet.size());
Map<String, String> values = new HashMap<>(parameterKeySet.size());
for (String paramKey : parameterKeySet) {
StringParameter enumParam = enumValuesByLanguage.getParameter(paramKey);
values.put(paramKey, new EnumValue(paramKey, enumParam.getValue()));
values.put(paramKey, enumParam.getValue());
}
return new StrolchEnum(name, locale, values);
}
}
/**
* @param enumeration
* @param locale
* @return
*/
private ParameterBag findParameterBagByLanguage(Resource enumeration, Locale locale) {
String localeS = locale.getLanguage() + UNDERLINE + locale.getCountry() + UNDERLINE + locale.getVariant();

View File

@ -15,63 +15,43 @@
*/
package li.strolch.runtime.query.enums;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.gson.JsonObject;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "EnumValue")
public class EnumValue {
@XmlAttribute(name = "id")
private String id;
@XmlAttribute(name = "value")
private String value;
public EnumValue() {
// no-arg constructor for JAXB
}
/**
* @param id
* @param value
*/
public EnumValue(String id, String value) {
this.id = id;
this.value = value;
}
/**
* @return the key
*/
public String getId() {
return this.id;
}
/**
* @param id
* the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the value
*/
public String getValue() {
return this.value;
}
/**
* @param value
* the value to set
*/
public void setValue(String value) {
this.value = value;
}
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", this.id);
jsonObject.addProperty("value", this.value);
return jsonObject;
}
}

View File

@ -15,157 +15,74 @@
*/
package li.strolch.runtime.query.enums;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import com.google.gson.JsonObject;
import li.strolch.utils.helper.StringHelper;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "StrolchEnum")
@XmlType(propOrder = { "name", "locale", "values" })
public class StrolchEnum {
@XmlAttribute(name = "name")
private String name;
@XmlAttribute(name = "locale")
private String locale;
private Map<String, String> values;
private Map<String, EnumValue> values;
@XmlTransient
private Locale localeL;
public StrolchEnum() {
// no-arg constructor for JAXB
}
/**
* @param name
* @param locale
* @param values
*/
public StrolchEnum(String name, Locale locale, Map<String, EnumValue> values) {
public StrolchEnum(String name, Locale locale, Map<String, String> values) {
this.name = name;
this.locale = locale.toString();
this.localeL = locale;
this.values = values;
}
/**
* @return the name
*/
public String getName() {
return this.name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the locale as string
*/
public String getLocale() {
return this.locale;
}
/**
* @param locale
* the locale to set
*/
public void setLocale(String locale) {
this.localeL = new Locale(locale);
this.locale = locale;
}
/**
* @return the locale
*/
public Locale getLocaleL() {
return this.localeL;
}
/**
* @param localeL
* the localeL to set
*/
public void setLocaleL(Locale localeL) {
this.locale = localeL.getLanguage() + StringHelper.UNDERLINE + localeL.getCountry();
this.localeL = localeL;
}
/**
* @return the values
*/
@XmlElement(name = "values")
public Collection<EnumValue> getValues() {
if (this.values == null)
return null;
return this.values.values();
}
/**
* @param values
* the values to set
*/
public void setValues(Collection<EnumValue> values) {
this.values = new HashMap<>(values.size());
for (EnumValue enumValue : values) {
this.values.put(enumValue.getId(), enumValue);
}
}
/**
* @return the list of {@link EnumValue#getId()}
*/
public List<String> getEnumValueIds() {
return new ArrayList<>(this.values.keySet());
}
/**
* @return the list of {@link EnumValue#getValue()}
*/
public List<String> getEnumValues() {
List<String> values = new ArrayList<>(this.values.size());
for (EnumValue enumValue : this.values.values()) {
values.add(enumValue.getValue());
}
return values;
}
/**
* Returns the actual value for the given id
*
* @param id
* the id of the value to return
*
* @return the actual value for the given id, or null if it does not exist
*/
public String getValue(String id) {
EnumValue enumValue = this.values.get(id);
if (enumValue == null)
return null;
return enumValue.getValue();
return this.values.get(id);
}
public int size() {
return this.values.size();
}
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", this.name);
jsonObject.addProperty("locale", this.locale);
JsonObject valuesJ = new JsonObject();
this.values.forEach(valuesJ::addProperty);
jsonObject.add("values", valuesJ);
return jsonObject;
}
}

View File

@ -15,15 +15,10 @@
*/
package li.strolch.runtime.query.inmemory;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import li.strolch.model.audit.AccessType;
import li.strolch.model.audit.ActionSelection;
import li.strolch.model.audit.Audit;
import li.strolch.model.audit.ElementSelection;
import li.strolch.model.audit.IdentitySelection;
import li.strolch.model.audit.*;
import li.strolch.model.query.StringSelection;
/**
@ -111,8 +106,8 @@ public abstract class AuditSelector {
private StringSelection actionSelection;
public ActionSelector(ActionSelection selection) {
if (selection.getAccessTypes() != null && selection.getAccessTypes().length != 0)
this.accessTypes = new HashSet<>(Arrays.asList(selection.getAccessTypes()));
if (selection.getAccessTypes() != null && !selection.getAccessTypes().isEmpty())
this.accessTypes = new HashSet<>(selection.getAccessTypes());
this.actionSelection = selection.getActionSelection();
}

View File

@ -17,16 +17,13 @@ package li.strolch.runtime.query.enums;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import org.junit.Test;
import li.strolch.RuntimeMock;
import li.strolch.agent.ComponentContainerTest;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.privilege.model.Certificate;
import org.junit.Test;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -49,26 +46,20 @@ public class EnumHandlerTest {
StrolchEnum sexEnum = enumHandler.getEnum(certificate, "sex", Locale.ENGLISH);
assertEquals("sex", sexEnum.getName());
assertEquals("en", sexEnum.getLocale());
assertEquals(3, sexEnum.getValues().size());
List<String> values = sexEnum.getEnumValues();
Collections.sort(values);
assertEquals("both", values.get(0));
assertEquals(3, sexEnum.size());
assertEquals("both", sexEnum.getValue("both"));
StrolchEnum salutationsEnum = enumHandler.getEnum(certificate, "salutations", Locale.UK);
assertEquals("salutations", salutationsEnum.getName());
assertEquals("en_GB", salutationsEnum.getLocale());
assertEquals(3, salutationsEnum.getValues().size());
values = salutationsEnum.getEnumValues();
Collections.sort(values);
assertEquals("Mr", values.get(0));
assertEquals(3, salutationsEnum.size());
assertEquals("Mr", salutationsEnum.getValue("mr"));
StrolchEnum religionsEnum = enumHandler.getEnum(certificate, "religions", Locale.CANADA);
assertEquals("religions", religionsEnum.getName());
assertEquals("en_CA", religionsEnum.getLocale());
assertEquals(9, religionsEnum.getValues().size());
values = religionsEnum.getEnumValues();
Collections.sort(values);
assertEquals("Atheist", values.get(0));
assertEquals(9, religionsEnum.size());
assertEquals("Atheist", religionsEnum.getValue("Atheist"));
});
}
}

View File

@ -19,37 +19,18 @@ import static li.strolch.utils.helper.StringHelper.NULL;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import li.strolch.model.xml.Iso8601DateAdapter;
import li.strolch.utils.helper.StringHelper;
import li.strolch.utils.iso8601.ISO8601FormatFactory;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "ModelStatistics")
@XmlAccessorType(XmlAccessType.NONE)
public class ModelStatistics {
@XmlAttribute(name = "startTime")
@XmlJavaTypeAdapter(value = Iso8601DateAdapter.class)
public Date startTime;
@XmlAttribute(name = "duractionNanos")
public long durationNanos;
@XmlAttribute(name = "nrOfResources")
public long nrOfResources;
@XmlAttribute(name = "nrOfOrders")
public long nrOfOrders;
@XmlAttribute(name = "nrOfActivities")
public long nrOfActivities;
/**
@ -82,8 +63,8 @@ public class ModelStatistics {
/**
* Adds the statistics of the other statistics to this statistics instance
*
* @param statistics
*
* @param statistics further statistics to add to this {@link ModelStatistics}
*/
public void add(ModelStatistics statistics) {
this.nrOfOrders += statistics.nrOfOrders;
@ -94,7 +75,8 @@ public class ModelStatistics {
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(getClass().getSimpleName() + " [startTime=");
builder.append(getClass().getSimpleName());
builder.append(" [startTime=");
builder.append(this.startTime == null ? NULL : ISO8601FormatFactory.getInstance().formatDate(this.startTime));
builder.append(", durationNanos=");
builder.append(StringHelper.formatNanoDuration(this.durationNanos));

View File

@ -15,6 +15,9 @@
*/
package li.strolch.model.audit;
import java.util.Arrays;
import java.util.List;
import li.strolch.model.query.StringSelection;
import li.strolch.utils.StringMatchMode;
@ -24,7 +27,7 @@ import li.strolch.utils.StringMatchMode;
public class ActionSelection extends AuditSelection {
private StringSelection actionSelection;
private AccessType[] accessTypes;
private List<AccessType> accessTypes;
public ActionSelection(AuditQuery<?> query) {
super(query);
@ -35,12 +38,17 @@ public class ActionSelection extends AuditSelection {
return this;
}
public ActionSelection accessTypes(AccessType... accessTypes) {
public ActionSelection accessTypes(List<AccessType> accessTypes) {
this.accessTypes = accessTypes;
return this;
}
public AccessType[] getAccessTypes() {
public ActionSelection accessTypes(AccessType... accessTypes) {
this.accessTypes = Arrays.asList(accessTypes);
return this;
}
public List<AccessType> getAccessTypes() {
return this.accessTypes;
}
@ -49,7 +57,7 @@ public class ActionSelection extends AuditSelection {
}
public boolean isWildcardActionType() {
return this.accessTypes == null || this.accessTypes.length == 0;
return this.accessTypes == null || this.accessTypes.isEmpty();
}
public boolean isWildcardAction() {

View File

@ -18,60 +18,27 @@ package li.strolch.model.audit;
import java.io.Serializable;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import li.strolch.model.StrolchRootElement;
import li.strolch.model.xml.Iso8601DateAdapter;
/**
* Used to log/audit access to {@link StrolchRootElement}
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "Audit")
@XmlAccessorType(XmlAccessType.NONE)
public class Audit implements Comparable<Audit>, Serializable {
private static final long serialVersionUID = 1L;
@XmlAttribute(name = "id")
private Long id;
@XmlAttribute(name = "username")
private String username;
@XmlAttribute(name = "firstname")
private String firstname;
@XmlAttribute(name = "lastname")
private String lastname;
@XmlElement(name = "date")
@XmlJavaTypeAdapter(Iso8601DateAdapter.class)
private Date date;
@XmlAttribute(name = "elementType")
private String elementType;
@XmlAttribute(name = "elementSubType")
private String elementSubType;
@XmlAttribute(name = "elementAccessed")
private String elementAccessed;
@XmlElement(name = "newVersion")
@XmlJavaTypeAdapter(Iso8601DateAdapter.class)
private Date newVersion;
@XmlAttribute(name = "action")
private String action;
@XmlAttribute(name = "accessType")
private AccessType accessType;
public Long getId() {

View File

@ -0,0 +1,28 @@
package li.strolch.model.json;
import com.google.gson.JsonObject;
import li.strolch.model.audit.Audit;
import li.strolch.model.audit.AuditVisitor;
import li.strolch.utils.iso8601.ISO8601FormatFactory;
public class AuditToJsonVisitor implements AuditVisitor<JsonObject> {
@Override
public JsonObject visitAudit(Audit audit) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", audit.getId());
jsonObject.addProperty("username", audit.getUsername());
jsonObject.addProperty("firstname", audit.getFirstname());
jsonObject.addProperty("lastname", audit.getLastname());
jsonObject.addProperty("date", ISO8601FormatFactory.getInstance().formatDate(audit.getDate()));
jsonObject.addProperty("elementType", audit.getElementType());
jsonObject.addProperty("elementSubType", audit.getElementSubType());
jsonObject.addProperty("elementAccessed", audit.getElementAccessed());
jsonObject.addProperty("newVersion", ISO8601FormatFactory.getInstance().formatDate(audit.getNewVersion()));
jsonObject.addProperty("action", audit.getAction());
jsonObject.addProperty("accessType", audit.getAccessType().name());
return jsonObject;
}
}

View File

@ -0,0 +1,57 @@
package li.strolch.model.json;
import java.util.*;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import li.strolch.privilege.model.UserRep;
import li.strolch.privilege.model.UserState;
public class PrivilegeElementFromJsonVisitor {
public UserRep userRepFromJson(String string) {
return userRepFromJson(new JsonParser().parse(string).getAsJsonObject());
}
public UserRep userRepFromJson(JsonObject jsonObject) {
JsonElement userIdE = jsonObject.get("userId");
JsonElement userNameE = jsonObject.get("username");
JsonElement firstNameE = jsonObject.get("firstname");
JsonElement lastNameE = jsonObject.get("lastname");
JsonElement userStateE = jsonObject.get("userState");
JsonElement localeE = jsonObject.get("locale");
JsonElement rolesE = jsonObject.get("roles");
JsonElement propertiesE = jsonObject.get("properties");
String userId = userIdE == null ? null : userIdE.getAsString();
String username = userNameE == null ? null : userNameE.getAsString();
String firstname = firstNameE == null ? null : firstNameE.getAsString();
String lastname = lastNameE == null ? null : lastNameE.getAsString();
UserState userState = userStateE == null ? null : UserState.valueOf(userStateE.getAsString());
Locale locale = localeE == null ? null : new Locale(localeE.getAsString());
Set<String> roles = null;
if (rolesE != null) {
roles = new HashSet<>();
JsonArray rolesArr = rolesE.getAsJsonArray();
for (JsonElement role : rolesArr) {
roles.add(role.getAsString());
}
}
Map<String, String> properties = null;
if (propertiesE != null) {
properties = new HashMap<>();
JsonArray propertiesArr = propertiesE.getAsJsonArray();
for (JsonElement propertyE : propertiesArr) {
JsonObject property = propertyE.getAsJsonObject();
properties.put(property.get("key").getAsString(), property.get("value").getAsString());
}
}
return new UserRep(userId, username, firstname, lastname, userState, roles, locale, properties);
}
}

View File

@ -0,0 +1,73 @@
package li.strolch.model.json;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import li.strolch.privilege.model.PrivilegeElementVisitor;
import li.strolch.privilege.model.PrivilegeRep;
import li.strolch.privilege.model.RoleRep;
import li.strolch.privilege.model.UserRep;
public class PrivilegeElementToJsonVisitor implements PrivilegeElementVisitor<JsonObject> {
@Override
public JsonObject visitUserRep(UserRep userRep) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("userId", userRep.getUserId());
jsonObject.addProperty("username", userRep.getUsername());
jsonObject.addProperty("firstname", userRep.getFirstname());
jsonObject.addProperty("lastname", userRep.getLastname());
jsonObject.addProperty("userState", userRep.getUserState().name());
jsonObject.addProperty("locale", userRep.getLocale().toString());
JsonArray rolesArr = new JsonArray();
jsonObject.add("roles", rolesArr);
for (String role : userRep.getRoles()) {
rolesArr.add(new JsonPrimitive(role));
}
JsonArray propsArr = new JsonArray();
jsonObject.add("properties", propsArr);
for (String propKey : userRep.getPropertyKeySet()) {
JsonObject propObj = new JsonObject();
propObj.addProperty("key", propKey);
propObj.addProperty("value", userRep.getProperty(propKey));
propsArr.add(propObj);
}
return jsonObject;
}
@Override
public JsonObject visitRoleRep(RoleRep roleRep) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", roleRep.getName());
JsonArray privilegesJ = new JsonArray();
roleRep.getPrivileges().forEach(p -> privilegesJ.add(p.accept(this)));
jsonObject.add("privileges", privilegesJ);
return jsonObject;
}
@Override
public JsonObject visitPrivilegeRep(PrivilegeRep privilegeRep) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", privilegeRep.getName());
jsonObject.addProperty("policy", privilegeRep.getName());
jsonObject.addProperty("allAllowed", privilegeRep.getName());
JsonArray denyListJ = new JsonArray();
privilegeRep.getDenyList().forEach(denyListJ::add);
jsonObject.add("denyList", denyListJ);
JsonArray allowListJ = new JsonArray();
privilegeRep.getAllowList().forEach(allowListJ::add);
jsonObject.add("allowList", allowListJ);
return jsonObject;
}
}

View File

@ -1,61 +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.model.xml;
import java.util.Calendar;
import java.util.Date;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import li.strolch.utils.helper.StringHelper;
public class Iso8601DateAdapter extends XmlAdapter<String, Date> {
private static final Logger logger = LoggerFactory.getLogger(Iso8601DateAdapter.class);
@Override
public Date unmarshal(String value) throws Exception {
if (StringHelper.isEmpty(value))
return null;
try {
return DatatypeConverter.parseDateTime(value).getTime();
} catch (Exception e) {
IllegalArgumentException ex = new IllegalArgumentException("Failed to parse value: " + value, e);
logger.info(ex.getMessage(), ex);
throw ex;
}
}
@Override
public String marshal(Date value) throws Exception {
if (value == null)
return null;
try {
Calendar cal = Calendar.getInstance();
cal.setTime(value);
String valueS = DatatypeConverter.printDateTime(cal);
return valueS;
} catch (Exception e) {
IllegalArgumentException ex = new IllegalArgumentException("Failed to format date: " + value, e);
logger.info(ex.getMessage(), ex);
throw ex;
}
}
}

View File

@ -20,12 +20,7 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import li.strolch.model.audit.AccessType;
import li.strolch.model.audit.ActionSelection;
import li.strolch.model.audit.AuditQuery;
import li.strolch.model.audit.AuditQueryVisitor;
import li.strolch.model.audit.ElementSelection;
import li.strolch.model.audit.IdentitySelection;
import li.strolch.model.audit.*;
import li.strolch.model.query.StringSelection;
import li.strolch.utils.StringMatchMode;
@ -131,21 +126,21 @@ public class PostgreSqlAuditQueryVisitor implements AuditQueryVisitor {
if (!selection.isWildcardActionType()) {
AccessType[] accessTypes = selection.getAccessTypes();
List<AccessType> accessTypes = selection.getAccessTypes();
ensureAnd();
this.sb.append(this.indent);
if (accessTypes.length == 1) {
if (accessTypes.size() == 1) {
this.sb.append(PostgreSqlAuditDao.ACCESS_TYPE + " = ?");
this.sb.append(PostgreSqlAuditDao.ACCESS_TYPE_TYPE);
this.sb.append("\n");
this.values.add(accessTypes[0].name());
this.values.add(accessTypes.get(0).name());
} else {
this.sb.append(PostgreSqlAuditDao.ACCESS_TYPE + " in (");
for (int i = 0; i < accessTypes.length; i++) {
for (int i = 0; i < accessTypes.size(); i++) {
this.sb.append("?");
this.sb.append(PostgreSqlAuditDao.ACCESS_TYPE_TYPE);
this.values.add(accessTypes[i].name());
if (i < accessTypes.length - 1)
this.values.add(accessTypes.get(i).name());
if (i < accessTypes.size() - 1)
this.sb.append(", ");
}
this.sb.append(" )\n");

View File

@ -15,6 +15,7 @@
*/
package li.strolch.privilege.handler;
import javax.crypto.SecretKey;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
@ -22,41 +23,13 @@ import java.nio.file.Files;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.*;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.crypto.SecretKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import li.strolch.privilege.base.AccessDeniedException;
import li.strolch.privilege.base.InvalidCredentialsException;
import li.strolch.privilege.base.NotAuthenticatedException;
import li.strolch.privilege.base.PrivilegeConflictResolution;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.IPrivilege;
import li.strolch.privilege.model.PrivilegeContext;
import li.strolch.privilege.model.PrivilegeRep;
import li.strolch.privilege.model.Restrictable;
import li.strolch.privilege.model.RoleRep;
import li.strolch.privilege.model.SimpleRestrictable;
import li.strolch.privilege.model.Usage;
import li.strolch.privilege.model.UserRep;
import li.strolch.privilege.model.UserState;
import li.strolch.privilege.base.*;
import li.strolch.privilege.model.*;
import li.strolch.privilege.model.internal.PrivilegeImpl;
import li.strolch.privilege.model.internal.Role;
import li.strolch.privilege.model.internal.User;
@ -68,23 +41,24 @@ import li.strolch.privilege.xml.CertificateStubsSaxReader.CertificateStub;
import li.strolch.utils.collections.Tuple;
import li.strolch.utils.helper.AesCryptoHelper;
import li.strolch.utils.helper.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* This is default implementation of the {@link PrivilegeHandler}
* </p>
*
* <p>
* The following list describes implementation details:
* <ul>
* <li>any methods which change the model are first validated by checking if the certificate is for an admin user by
* calling {@link #assertIsPrivilegeAdmin(Certificate)}</li>
* <li>any methods which change the model are first validated by checking if the certificate has the appropriate privilege</li>
* <li>all model requests are delegated to the configured {@link PrivilegeHandler}, except for the session id to
* {@link Certificate} map, no model data is kept in this implementation. This also means that to return the
* representation objects, for every new model query, a new representation object is created</li>
* <li>when creating new users, or editing users then a null password is understood as no password set</li>
* <li>Password requirements are simple: Non null and non empty/length 0</li>
* </ul>
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class DefaultPrivilegeHandler implements PrivilegeHandler {
@ -201,7 +175,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
PrivilegeContext prvCtx = getPrivilegeContext(certificate);
prvCtx.validateAction(new SimpleRestrictable(PRIVILEGE_ACTION, PRIVILEGE_ACTION_GET_CERTIFICATES));
return this.privilegeContextMap.values().stream().map(p -> p.getCertificate()).collect(Collectors.toList());
return this.privilegeContextMap.values().stream().map(PrivilegeContext::getCertificate)
.collect(Collectors.toList());
}
@Override
@ -224,7 +199,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
}
});
List<RoleRep> roles = rolesStream.map(r -> r.asRoleRep()).collect(Collectors.toList());
List<RoleRep> roles = rolesStream.map(Role::asRoleRep).collect(Collectors.toList());
return roles;
}
@ -248,7 +223,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
}
});
List<UserRep> users = usersStream.map(u -> u.asUserRep()).collect(Collectors.toList());
List<UserRep> users = usersStream.map(User::asUserRep).collect(Collectors.toList());
return users;
}
@ -266,7 +241,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
UserState selUserState = selectorRep.getUserState();
Locale selLocale = selectorRep.getLocale();
Set<String> selRoles = selectorRep.getRoles();
Map<String, String> selPropertyMap = selectorRep.getPropertyMap();
Map<String, String> selPropertyMap = selectorRep.getProperties();
List<UserRep> result = new ArrayList<>();
List<User> allUsers = this.persistenceHandler.getAllUsers();
@ -343,8 +318,9 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// properties
propertySelected = isSelectedByProperty(selPropertyMap, user.getProperties());
boolean selected = userIdSelected && usernameSelected && firstnameSelected && lastnameSelected
&& userStateSelected && localeSelected && roleSelected && propertySelected;
boolean selected =
userIdSelected && usernameSelected && firstnameSelected && lastnameSelected && userStateSelected
&& localeSelected && roleSelected && propertySelected;
if (selected)
result.add(user.asUserRep());
@ -357,14 +333,11 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
* Checks if the given properties contains values which are contained in the selectionMap. If the selectionMap is
* null or empty, then true is returned. If a key/value pair from the selectionMap is not in the properties, then
* false is returned
*
* @param selectionMap
* the map defining the expected properties
* @param properties
* the properties which must be a sub set of selectionMap to have this method return true
*
*
* @param selectionMap the map defining the expected properties
* @param properties the properties which must be a sub set of selectionMap to have this method return true
* @return If the selectionMap is null or empty, then true is returned. If a key/value pair from the selectionMap is
* not in the properties, then false is returned
* not in the properties, then false is returned
*/
private boolean isSelectedByProperty(Map<String, String> selectionMap, Map<String, String> properties) {
@ -387,14 +360,11 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
/**
* Checks if the given roles contains the given selectionRoles, if this is the case, or selectionRoles is null or
* empty, then true is returned, otherwise false
*
* @param selectionRoles
* the required roles
* @param roles
* the roles to check if they contain the selectionRoles
*
*
* @param selectionRoles the required roles
* @param roles the roles to check if they contain the selectionRoles
* @return Checks if the given roles contains the given selectionRoles, if this is the case, or selectionRoles is
* null or empty, then true is returned, otherwise false
* null or empty, then true is returned, otherwise false
*/
private boolean isSelectedByRole(Set<String> selectionRoles, Set<String> roles) {
@ -544,7 +514,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
private User createUser(UserRep userRep, byte[] passwordHash, byte[] salt) {
User user = new User(userRep.getUserId(), userRep.getUsername(), passwordHash, salt, userRep.getFirstname(),
userRep.getLastname(), userRep.getUserState(), userRep.getRoles(), userRep.getLocale(),
userRep.getPropertyMap());
userRep.getProperties());
return user;
}
@ -559,15 +529,17 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get existing user
User existingUser = this.persistenceHandler.getUser(userRep.getUsername());
if (existingUser == null) {
throw new PrivilegeException(MessageFormat.format("User {0} does not exist!", userRep.getUsername())); //$NON-NLS-1$
throw new PrivilegeException(
MessageFormat.format("User {0} does not exist!", userRep.getUsername())); //$NON-NLS-1$
}
// if nothing to do, then stop
if (StringHelper.isEmpty(userRep.getFirstname()) && StringHelper.isEmpty(userRep.getLastname())
&& userRep.getLocale() == null
&& (userRep.getProperties() == null || userRep.getProperties().isEmpty())) {
throw new PrivilegeException(MessageFormat.format("All updateable fields are empty for update of user {0}", //$NON-NLS-1$
userRep.getUsername()));
&& userRep.getLocale() == null && (userRep.getProperties() == null || userRep.getProperties()
.isEmpty())) {
throw new PrivilegeException(
MessageFormat.format("All updateable fields are empty for update of user {0}", //$NON-NLS-1$
userRep.getUsername()));
}
String userId = existingUser.getUserId();
@ -589,7 +561,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
if (userRep.getLocale() != null)
locale = userRep.getLocale();
if (userRep.getProperties() != null && !userRep.getProperties().isEmpty())
propertyMap = userRep.getPropertyMap();
propertyMap = userRep.getProperties();
// create new user
User newUser = new User(userId, username, password, salt, firstname, lastname, userState, roles, locale,
@ -702,7 +674,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// ignore if user does not have role
Set<String> currentRoles = existingUser.getRoles();
if (!currentRoles.contains(roleName)) {
String msg = MessageFormat.format("User {0} does not have role {1}", existingUser.getUsername(), roleName); //$NON-NLS-1$
String msg = MessageFormat
.format("User {0} does not have role {1}", existingUser.getUsername(), roleName); //$NON-NLS-1$
throw new PrivilegeException(msg);
}
@ -922,7 +895,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
prvCtx.assertHasPrivilege(PRIVILEGE_REMOVE_ROLE);
// validate no user is using this role
Set<String> roles = new HashSet<>(Arrays.asList(roleName));
Set<String> roles = new HashSet<>(Collections.singletonList(roleName));
UserRep selector = new UserRep(null, null, null, null, null, roles, null, null);
List<UserRep> usersWithRole = queryUsers(certificate, selector);
if (!usersWithRole.isEmpty()) {
@ -1021,7 +994,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// ignore if role does not have privilege
if (!existingRole.hasPrivilege(privilegeName)) {
String msg = MessageFormat.format("Role {0} does not have Privilege {1}", roleName, privilegeName); //$NON-NLS-1$
String msg = MessageFormat
.format("Role {0} does not have Privilege {1}", roleName, privilegeName); //$NON-NLS-1$
throw new PrivilegeException(msg);
}
@ -1097,7 +1071,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
try {
// username must be at least 2 characters in length
if (username == null || username.length() < 2) {
String msg = MessageFormat.format("The given username ''{0}'' is shorter than 2 characters", username); //$NON-NLS-1$
String msg = MessageFormat
.format("The given username ''{0}'' is shorter than 2 characters", username); //$NON-NLS-1$
throw new PrivilegeException(msg);
}
@ -1154,7 +1129,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
return false;
List<Certificate> sessions = new ArrayList<>(this.privilegeContextMap.values()).stream()
.map(p -> p.getCertificate()).filter(c -> !c.getUserState().isSystem()).collect(Collectors.toList());
.map(PrivilegeContext::getCertificate).filter(c -> !c.getUserState().isSystem())
.collect(Collectors.toList());
try (OutputStream fout = Files.newOutputStream(this.persistSessionsPath.toPath());
OutputStream outputStream = AesCryptoHelper.wrapEncrypt(this.secretKey, fout)) {
@ -1234,18 +1210,12 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
/**
* Checks the credentials and validates that the user may log in.
*
* @param username
* the username of the {@link User} to check against
* @param password
* the password of this user
*
*
* @param username the username of the {@link User} to check against
* @param password the password of this user
* @return the {@link User} if the credentials are valid and the user may login
*
* @throws AccessDeniedException
* if anything is wrong with the credentials or the user state
* @throws InvalidCredentialsException
* if the given credentials are invalid, the user does not exist, or has no password set
* @throws AccessDeniedException if anything is wrong with the credentials or the user state
* @throws InvalidCredentialsException if the given credentials are invalid, the user does not exist, or has no password set
*/
private User checkCredentialsAndUserState(String username, char[] password)
throws InvalidCredentialsException, AccessDeniedException {
@ -1282,25 +1252,26 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
MessageFormat.format("User {0} has no password and may not login!", username)); //$NON-NLS-1$
byte[] salt = user.getSalt();
if (salt == null)
throw new AccessDeniedException(MessageFormat.format("User {0} has no salt and may not login!", salt)); //$NON-NLS-1$
throw new AccessDeniedException(
MessageFormat.format("User {0} has no salt and may not login!", salt)); //$NON-NLS-1$
// we only work with hashed passwords
byte[] passwordHash = this.encryptionHandler.hashPassword(password, salt);
// validate password
if (!Arrays.equals(passwordHash, pwHash))
throw new InvalidCredentialsException(MessageFormat.format("Password is incorrect for {0}", username)); //$NON-NLS-1$
throw new InvalidCredentialsException(
MessageFormat.format("Password is incorrect for {0}", username)); //$NON-NLS-1$
return user;
}
/**
* Builds a {@link PrivilegeContext} for the given {@link User} and its {@link Certificate}
*
* @param certificate
* @param user
*
* @return
*
* @param certificate the certificate for which to build the {@link PrivilegeContext}
* @param user the user for which to build the {@link PrivilegeContext}
* @return the {@link PrivilegeContext}
*/
private PrivilegeContext buildPrivilegeContext(Certificate certificate, User user) {
@ -1413,8 +1384,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// validate that challenge certificate is not expired (1 hour only)
if (sessionCertificate.getUsage() != Usage.ANY) {
LocalDateTime dateTime = LocalDateTime.ofInstant(sessionCertificate.getLoginTime().toInstant(),
ZoneId.systemDefault());
LocalDateTime dateTime = LocalDateTime
.ofInstant(sessionCertificate.getLoginTime().toInstant(), ZoneId.systemDefault());
if (dateTime.plusHours(1).isBefore(LocalDateTime.now())) {
invalidateSession(sessionCertificate);
throw new NotAuthenticatedException("Certificate has already expired!"); //$NON-NLS-1$
@ -1447,7 +1418,7 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
/**
* This simple implementation validates that the password is not null, and that the password string is not empty
*
*
* @see li.strolch.privilege.handler.PrivilegeHandler#validatePassword(char[])
*/
@Override
@ -1496,20 +1467,13 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
* Initializes the concrete {@link EncryptionHandler}. The passed parameter map contains any configuration this
* {@link PrivilegeHandler} might need. This method may only be called once and this must be enforced by the
* concrete implementation
*
* @param parameterMap
* a map containing configuration properties
* @param encryptionHandler
* the {@link EncryptionHandler} instance for this {@link PrivilegeHandler}
* @param persistenceHandler
* the {@link PersistenceHandler} instance for this {@link PrivilegeHandler}
* @param userChallengeHandler
* the handler to challenge a user's actions e.g. password change or authentication
* @param policyMap
* map of {@link PrivilegePolicy} classes
*
* @throws PrivilegeException
* if the this method is called multiple times or an initialization exception occurs
*
* @param parameterMap a map containing configuration properties
* @param encryptionHandler the {@link EncryptionHandler} instance for this {@link PrivilegeHandler}
* @param persistenceHandler the {@link PersistenceHandler} instance for this {@link PrivilegeHandler}
* @param userChallengeHandler the handler to challenge a user's actions e.g. password change or authentication
* @param policyMap map of {@link PrivilegePolicy} classes
* @throws PrivilegeException if the this method is called multiple times or an initialization exception occurs
*/
public synchronized void initialize(Map<String, String> parameterMap, EncryptionHandler encryptionHandler,
PersistenceHandler persistenceHandler, UserChallengeHandler userChallengeHandler,
@ -1713,9 +1677,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
/**
* Validates that the policies which are not null on the privileges of the role exist
*
* @param role
* the role for which the policies are to be checked
*
* @param role the role for which the policies are to be checked
*/
private void validatePolicies(Role role) {
for (String privilegeName : role.getPrivilegeNames()) {
@ -1732,9 +1695,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
/**
* Passwords should not be kept as strings, as string are immutable, this method thus clears the char array so that
* the password is not in memory anymore
*
* @param password
* the char array containing the passwort which is to be set to zeroes
*
* @param password the char array containing the passwort which is to be set to zeroes
*/
private void clearPassword(char[] password) {
if (password != null) {
@ -1781,11 +1743,13 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// get the system user
User systemUser = this.persistenceHandler.getUser(username);
if (systemUser == null)
throw new PrivilegeException(MessageFormat.format("System user {0} does not exist!", username)); //$NON-NLS-1$
throw new PrivilegeException(
MessageFormat.format("System user {0} does not exist!", username)); //$NON-NLS-1$
// validate this is a system user
if (systemUser.getUserState() != UserState.SYSTEM)
throw new PrivilegeException(MessageFormat.format("User {0} is not a System user!", username)); //$NON-NLS-1$
throw new PrivilegeException(
MessageFormat.format("User {0} is not a System user!", username)); //$NON-NLS-1$
// get privilegeContext for this system user
PrivilegeContext systemUserPrivilegeContext = getSystemUserPrivilegeContext(username);
@ -1802,10 +1766,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
/**
* Returns the {@link Certificate} for the given system username. If it does not yet exist, then it is created by
* authenticating the system user
*
* @param systemUsername
* the name of the system user
*
*
* @param systemUsername the name of the system user
* @return the {@link Certificate} for this system user
*/
private PrivilegeContext getSystemUserPrivilegeContext(String systemUsername) {
@ -1814,14 +1776,16 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
User user = this.persistenceHandler.getUser(systemUsername);
// no user means no authentication
if (user == null) {
String msg = MessageFormat.format("The system user with username {0} does not exist!", systemUsername); //$NON-NLS-1$
String msg = MessageFormat
.format("The system user with username {0} does not exist!", systemUsername); //$NON-NLS-1$
throw new AccessDeniedException(msg);
}
// validate password
byte[] pwHash = user.getPassword();
if (pwHash != null) {
String msg = MessageFormat.format("System users must not have a password: {0}", systemUsername); //$NON-NLS-1$
String msg = MessageFormat
.format("System users must not have a password: {0}", systemUsername); //$NON-NLS-1$
throw new AccessDeniedException(msg);
}
@ -1834,7 +1798,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// validate user has at least one role
if (user.getRoles().isEmpty()) {
String msg = MessageFormat.format("The system user {0} does not have any roles defined!", systemUsername); //$NON-NLS-1$
String msg = MessageFormat
.format("The system user {0} does not have any roles defined!", systemUsername); //$NON-NLS-1$
throw new PrivilegeException(msg);
}
@ -1865,14 +1830,10 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
* is not stored in a database. The privilege name is a class name and is then used to instantiate a new
* {@link PrivilegePolicy} object
* </p>
*
* @param policyName
* the class name of the {@link PrivilegePolicy} object to return
*
*
* @param policyName the class name of the {@link PrivilegePolicy} object to return
* @return the {@link PrivilegePolicy} object
*
* @throws PrivilegeException
* if the {@link PrivilegePolicy} object for the given policy name could not be instantiated
* @throws PrivilegeException if the {@link PrivilegePolicy} object for the given policy name could not be instantiated
*/
private PrivilegePolicy getPolicy(String policyName) {

View File

@ -29,11 +29,11 @@ import li.strolch.privilege.policy.PrivilegePolicy;
/**
* This context gives access to a logged in user's privilege data e.g. the {@link UserRep}, {@link Certificate} and the
* user's list of {@link PrivilegeRep}
*
* <p>
* <p>
* Note: This is an internal object which is not to be serialized to clients
* </p>
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class PrivilegeContext {
@ -71,7 +71,7 @@ public class PrivilegeContext {
return this.privileges.keySet();
}
public void assertHasPrivilege(String privilegeName) {
public void assertHasPrivilege(String privilegeName) throws AccessDeniedException {
if (!this.privileges.containsKey(privilegeName)) {
String msg = MessageFormat.format(PrivilegeMessages.getString("Privilege.noprivilege.user"), //$NON-NLS-1$
userRep.getUsername(), privilegeName);
@ -79,12 +79,12 @@ public class PrivilegeContext {
}
}
public IPrivilege getPrivilege(String privilegeName) {
public IPrivilege getPrivilege(String privilegeName) throws AccessDeniedException {
assertHasPrivilege(privilegeName);
return this.privileges.get(privilegeName);
}
public PrivilegePolicy getPolicy(String policyName) {
public PrivilegePolicy getPolicy(String policyName) throws PrivilegeException {
PrivilegePolicy policy = this.policies.get(policyName);
if (policy == null) {
String msg = "The PrivilegePolicy {0} does not exist on the PrivilegeContext!"; //$NON-NLS-1$
@ -101,23 +101,20 @@ public class PrivilegeContext {
* Validates if the user for this context has the privilege to access to the given {@link Restrictable}. If the user
* has the privilege, then this method returns with no exception and void, if the user does not have the privilege,
* then a {@link AccessDeniedException} is thrown.
*
* @param restrictable
* the {@link Restrictable} which the user wants to access
*
* @throws AccessDeniedException
* if the user does not have access
* @throws PrivilegeException
* if there is an internal error due to wrongly configured privileges or programming errors
*
* @param restrictable the {@link Restrictable} which the user wants to access
* @throws AccessDeniedException if the user does not have access
* @throws PrivilegeException if there is an internal error due to wrongly configured privileges or programming errors
*/
public void validateAction(Restrictable restrictable) throws AccessDeniedException, PrivilegeException {
public void validateAction(Restrictable restrictable) throws PrivilegeException, AccessDeniedException {
// the privilege for the restrictable
String privilegeName = restrictable.getPrivilegeName();
IPrivilege privilege = this.privileges.get(privilegeName);
if (privilege == null) {
String msg = MessageFormat.format(PrivilegeMessages.getString("Privilege.accessdenied.noprivilege"), //$NON-NLS-1$
getUsername(), privilegeName, restrictable.getClass().getName());
String msg = MessageFormat
.format(PrivilegeMessages.getString("Privilege.accessdenied.noprivilege"), //$NON-NLS-1$
getUsername(), privilegeName, restrictable.getClass().getName());
throw new AccessDeniedException(msg);
}

View File

@ -0,0 +1,10 @@
package li.strolch.privilege.model;
public interface PrivilegeElementVisitor<T> {
T visitUserRep(UserRep userRep);
T visitRoleRep(RoleRep roleRep);
T visitPrivilegeRep(PrivilegeRep privilegeRep);
}

View File

@ -19,12 +19,6 @@ import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.handler.PrivilegeHandler;
import li.strolch.privilege.model.internal.Role;
@ -35,44 +29,28 @@ import li.strolch.utils.helper.StringHelper;
* To keep certain details of the {@link IPrivilege} itself hidden from remote clients and make sure instances are only
* edited by users with the correct privilege, this representational version is allowed to be viewed by remote clients
* and simply wraps all public data from the {@link IPrivilege}
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "Privilege")
@XmlAccessorType(XmlAccessType.NONE)
public class PrivilegeRep implements Serializable {
private static final long serialVersionUID = 1L;
@XmlAttribute(name = "name")
private String name;
@XmlAttribute(name = "policy")
private String policy;
@XmlAttribute(name = "allAllowed")
private boolean allAllowed;
@XmlElement(name = "denyList")
private Set<String> denyList;
@XmlElement(name = "allowList")
private Set<String> allowList;
/**
* Default constructor
*
* @param name
* the name of this privilege, which is unique to all privileges known in the {@link PrivilegeHandler}
* @param policy
* the {@link PrivilegePolicy} configured to evaluate if the privilege is granted
* @param allAllowed
* a boolean defining if a {@link Role} with this {@link IPrivilege} has unrestricted access to a
* {@link Restrictable}
* @param denyList
* a list of deny rules for this {@link IPrivilege}
* @param allowList
* a list of allow rules for this {@link IPrivilege}
*
* @param name the name of this privilege, which is unique to all privileges known in the {@link PrivilegeHandler}
* @param policy the {@link PrivilegePolicy} configured to evaluate if the privilege is granted
* @param allAllowed a boolean defining if a {@link Role} with this {@link IPrivilege} has unrestricted access to a
* {@link Restrictable}
* @param denyList a list of deny rules for this {@link IPrivilege}
* @param allowList a list of allow rules for this {@link IPrivilege}
*/
public PrivilegeRep(String name, String policy, boolean allAllowed, Set<String> denyList, Set<String> allowList) {
this.name = name;
@ -82,14 +60,6 @@ public class PrivilegeRep implements Serializable {
this.allowList = allowList;
}
/**
*
*/
@SuppressWarnings("unused")
private PrivilegeRep() {
// no-arg constructor for JAXB
}
/**
* Validates that all required fields are set
*/
@ -119,8 +89,7 @@ public class PrivilegeRep implements Serializable {
}
/**
* @param name
* the name to set
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
@ -134,8 +103,7 @@ public class PrivilegeRep implements Serializable {
}
/**
* @param policy
* the policy to set
* @param policy the policy to set
*/
public void setPolicy(String policy) {
this.policy = policy;
@ -149,8 +117,7 @@ public class PrivilegeRep implements Serializable {
}
/**
* @param allAllowed
* the allAllowed to set
* @param allAllowed the allAllowed to set
*/
public void setAllAllowed(boolean allAllowed) {
this.allAllowed = allAllowed;
@ -164,8 +131,7 @@ public class PrivilegeRep implements Serializable {
}
/**
* @param denyList
* the denyList to set
* @param denyList the denyList to set
*/
public void setDenyList(Set<String> denyList) {
this.denyList = denyList;
@ -179,8 +145,7 @@ public class PrivilegeRep implements Serializable {
}
/**
* @param allowList
* the allowList to set
* @param allowList the allowList to set
*/
public void setAllowList(Set<String> allowList) {
this.allowList = allowList;
@ -188,7 +153,7 @@ public class PrivilegeRep implements Serializable {
/**
* Returns a string representation of this object displaying its concrete type and its values
*
*
* @see java.lang.Object#toString()
*/
@SuppressWarnings("nls")
@ -233,4 +198,8 @@ public class PrivilegeRep implements Serializable {
return false;
return true;
}
public <T> T accept(PrivilegeElementVisitor<T> visitor) {
return visitor.visitPrivilegeRep(this);
}
}

View File

@ -20,12 +20,6 @@ import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.model.internal.Role;
import li.strolch.utils.helper.StringHelper;
@ -34,42 +28,27 @@ import li.strolch.utils.helper.StringHelper;
* To keep certain details of the {@link Role} itself hidden from remote clients and make sure instances are only edited
* by users with the correct privilege, this representational version is allowed to be viewed by remote clients and
* simply wraps all public data from the {@link Role}
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "Role")
@XmlAccessorType(XmlAccessType.NONE)
public class RoleRep implements Serializable {
private static final long serialVersionUID = 1L;
@XmlAttribute(name = "name")
private String name;
@XmlElement(name = "privileges")
private List<PrivilegeRep> privileges;
/**
* Default constructor
*
* @param name
* the name of this role
* @param privileges
* the list of privileges granted to this role
*
* @param name the name of this role
* @param privileges the list of privileges granted to this role
*/
public RoleRep(String name, List<PrivilegeRep> privileges) {
this.name = name;
this.privileges = privileges;
}
/**
*
*/
@SuppressWarnings("unused")
private RoleRep() {
// no-arg constructor for JAXB
}
/**
* validates that all required fields are set
*/
@ -98,8 +77,7 @@ public class RoleRep implements Serializable {
}
/**
* @param name
* the name to set
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
@ -107,7 +85,7 @@ public class RoleRep implements Serializable {
/**
* Returns the privileges assigned to this Role as a list
*
*
* @return the privileges assigned to this Role as a list
*/
public List<PrivilegeRep> getPrivileges() {
@ -116,9 +94,8 @@ public class RoleRep implements Serializable {
/**
* Sets the privileges on this from a list
*
* @param privileges
* the list of privileges to assign to this role
*
* @param privileges the list of privileges to assign to this role
*/
public void setPrivileges(List<PrivilegeRep> privileges) {
this.privileges = privileges;
@ -126,7 +103,7 @@ public class RoleRep implements Serializable {
/**
* Returns a string representation of this object displaying its concrete type and its values
*
*
* @see java.lang.Object#toString()
*/
@SuppressWarnings("nls")
@ -165,4 +142,8 @@ public class RoleRep implements Serializable {
return false;
return true;
}
public <T> T accept(PrivilegeElementVisitor<T> visitor) {
return visitor.visitRoleRep(this);
}
}

View File

@ -16,25 +16,18 @@
package li.strolch.privilege.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.*;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.privilege.model.internal.Role;
import li.strolch.privilege.model.internal.User;
import li.strolch.utils.helper.StringHelper;
import li.strolch.utils.xml.XmlKeyValue;
/**
* To keep certain details of the {@link User} itself hidden from remote clients and make sure instances are only edited
* by users with the correct privilege, this representational version is allowed to be viewed by remote clients and
* simply wraps all public data from the {@link User}
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class UserRep implements Serializable {
@ -55,27 +48,19 @@ public class UserRep implements Serializable {
private Set<String> roles;
private List<XmlKeyValue> properties;
private Map<String, String> properties;
/**
* Default constructor
*
* @param userId
* the user's id
* @param username
* the user's login name
* @param firstname
* the user's first name
* @param lastname
* the user's last name
* @param userState
* the user's {@link UserState}
* @param roles
* the set of {@link Role}s assigned to this user
* @param locale
* the user's {@link Locale}
* @param propertyMap
* a {@link Map} containing string value pairs of properties for this user
*
* @param userId the user's id
* @param username the user's login name
* @param firstname the user's first name
* @param lastname the user's last name
* @param userState the user's {@link UserState}
* @param roles the set of {@link Role}s assigned to this user
* @param locale the user's {@link Locale}
* @param propertyMap a {@link Map} containing string value pairs of properties for this user
*/
public UserRep(String userId, String username, String firstname, String lastname, UserState userState,
Set<String> roles, Locale locale, Map<String, String> propertyMap) {
@ -86,11 +71,11 @@ public class UserRep implements Serializable {
this.userState = userState;
this.roles = roles;
this.locale = locale;
this.properties = propertyMap == null ? new ArrayList<>() : XmlKeyValue.valueOf(propertyMap);
this.properties = propertyMap == null ? null : new HashMap<>(propertyMap);
}
/**
*
*
*/
@SuppressWarnings("unused")
private UserRep() {
@ -130,9 +115,8 @@ public class UserRep implements Serializable {
/**
* Set the userId
*
* @param userId
* to set
*
* @param userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
@ -146,8 +130,7 @@ public class UserRep implements Serializable {
}
/**
* @param username
* the username to set
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
@ -161,8 +144,7 @@ public class UserRep implements Serializable {
}
/**
* @param firstname
* the firstname to set
* @param firstname the firstname to set
*/
public void setFirstname(String firstname) {
this.firstname = firstname;
@ -176,8 +158,7 @@ public class UserRep implements Serializable {
}
/**
* @param lastname
* the lastname to set
* @param lastname the lastname to set
*/
public void setLastname(String lastname) {
this.lastname = lastname;
@ -191,8 +172,7 @@ public class UserRep implements Serializable {
}
/**
* @param userState
* the userState to set
* @param userState the userState to set
*/
public void setUserState(UserState userState) {
this.userState = userState;
@ -206,8 +186,7 @@ public class UserRep implements Serializable {
}
/**
* @param roles
* the roles to set
* @param roles the roles to set
*/
public void setRoles(Set<String> roles) {
this.roles = roles;
@ -215,10 +194,8 @@ public class UserRep implements Serializable {
/**
* Returns true if this user has the given role
*
* @param role
* the role to check for
*
*
* @param role the role to check for
* @return returns true if this user has the given role
*/
public boolean hasRole(String role) {
@ -233,8 +210,7 @@ public class UserRep implements Serializable {
}
/**
* @param locale
* the locale to set
* @param locale the locale to set
*/
public void setLocale(Locale locale) {
this.locale = locale;
@ -242,96 +218,53 @@ public class UserRep implements Serializable {
/**
* Returns the property with the given key
*
* @param key
* the key for which the property is to be returned
*
*
* @param key the key for which the property is to be returned
* @return the property with the given key, or null if the property is not defined
*/
public String getProperty(String key) {
if (this.properties == null)
return null;
for (XmlKeyValue keyValue : this.properties) {
if (keyValue.getKey().equals(key))
return keyValue.getValue();
}
return null;
return this.properties.get(key);
}
/**
* Set the property with the key to the value
*
* @param key
* the key of the property to set
* @param value
* the value of the property to set
*
* @param key the key of the property to set
* @param value the value of the property to set
*/
public void setProperty(String key, String value) {
if (this.properties == null)
this.properties = new ArrayList<>();
boolean updated = false;
for (XmlKeyValue keyValue : this.properties) {
if (keyValue.getKey().equals(key)) {
keyValue.setValue(value);
updated = true;
}
}
if (!updated) {
this.properties.add(new XmlKeyValue(key, value));
}
this.properties = new HashMap<>(1);
this.properties.put(key, value);
}
/**
* Returns the {@link Set} of keys of all properties
*
*
* @return the {@link Set} of keys of all properties
*/
public Set<String> getPropertyKeySet() {
if (this.properties == null)
return new HashSet<>();
Set<String> keySet = new HashSet<>(this.properties.size());
for (XmlKeyValue keyValue : this.properties) {
keySet.add(keyValue.getKey());
}
return keySet;
return new HashSet<>(this.properties.keySet());
}
/**
* Returns the map of properties
*
*
* @return the map of properties
*/
public Map<String, String> getPropertyMap() {
public Map<String, String> getProperties() {
if (this.properties == null)
return new HashMap<>();
return XmlKeyValue.toMap(this.properties);
}
/**
* Returns the string map properties of this user as a list of {@link XmlKeyValue} elements
*
* @return the string map properties of this user as a list of {@link XmlKeyValue} elements
*/
public List<XmlKeyValue> getProperties() {
return this.properties == null ? new ArrayList<>() : this.properties;
}
/**
* Sets the string map properties of this user from the given list of {@link XmlKeyValue}
*
* @param values
* the list of {@link XmlKeyValue} from which to set the properties
*/
public void setProperties(List<XmlKeyValue> values) {
this.properties = values;
return new HashMap<>(this.properties);
}
/**
* Returns a string representation of this object displaying its concrete type and its values
*
*
* @see java.lang.Object#toString()
*/
@SuppressWarnings("nls")
@ -385,12 +318,15 @@ public class UserRep implements Serializable {
public UserRep clone() {
Set<String> roles = new HashSet<>(this.roles);
Map<String, String> propertyMap = new HashMap<>();
this.properties.forEach(e -> propertyMap.put(e.getKey(), e.getValue()));
Map<String, String> propertyMap = this.properties == null ? null : new HashMap<>(this.properties);
UserRep clone = new UserRep(this.userId, this.username, this.firstname, this.lastname, this.userState, roles,
this.locale, propertyMap);
return clone;
}
public <T> T accept(PrivilegeElementVisitor<T> visitor) {
return visitor.visitUserRep(this);
}
}

View File

@ -63,10 +63,6 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>com.github.petitparser.java-petitparser</groupId>

View File

@ -17,8 +17,6 @@ package li.strolch.rest;
import java.text.MessageFormat;
import org.glassfish.jersey.server.ServerProperties;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.StrolchAgent;
import li.strolch.agent.api.StrolchComponent;
@ -51,7 +49,7 @@ public class RestfulStrolchComponent extends StrolchComponent {
* <li>{@code ALL} - tracing support is enabled for every request.</li>
* </ul>
*
* @see ServerProperties#TRACING
* @see org.glassfish.jersey.server.ServerProperties#TRACING
*/
private static final String PARAM_REST_TRACING = "restTracing"; //$NON-NLS-1$
@ -63,7 +61,7 @@ public class RestfulStrolchComponent extends StrolchComponent {
* <li>{@code VERBOSE}</li>
* </ul>
*
* @see ServerProperties#TRACING_THRESHOLD
* @see org.glassfish.jersey.server.ServerProperties#TRACING_THRESHOLD
*/
private static final String PARAM_REST_TRACING_THRESHOLD = "restTracingThreshold"; //$NON-NLS-1$

View File

@ -15,21 +15,19 @@
*/
package li.strolch.rest;
import java.text.MessageFormat;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.MessageFormat;
import li.strolch.exception.StrolchAccessDeniedException;
import li.strolch.privilege.model.Restrictable;
import li.strolch.rest.model.Result;
import li.strolch.rest.helper.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
public class StrolchRestfulExceptionMapper implements ExceptionMapper<Exception> {
@ -42,7 +40,7 @@ public class StrolchRestfulExceptionMapper implements ExceptionMapper<Exception>
logger.error(MessageFormat.format("Handling exception {0}", ex.getClass()), ex); //$NON-NLS-1$
if (ex instanceof NotFoundException)
return Response.status(Status.NOT_FOUND).entity(new Result(ex)).type(MediaType.APPLICATION_JSON).build();
return ResponseUtil.toResponse(Status.NOT_FOUND, ex);
if (ex instanceof StrolchAccessDeniedException) {
StrolchAccessDeniedException e = (StrolchAccessDeniedException) ex;
@ -64,6 +62,6 @@ public class StrolchRestfulExceptionMapper implements ExceptionMapper<Exception>
return Response.status(Status.UNAUTHORIZED).entity(sb.toString()).type(MediaType.TEXT_PLAIN).build();
}
return Response.serverError().entity(new Result(ex)).type(MediaType.APPLICATION_JSON).build();
return ResponseUtil.toResponse(ex);
}
}

View File

@ -15,29 +15,21 @@
*/
package li.strolch.rest.endpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.JsonArray;
import li.strolch.agent.api.StrolchRealm;
import li.strolch.model.audit.Audit;
import li.strolch.model.json.AuditToJsonVisitor;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.privilege.model.Certificate;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.model.AuditQuery;
import li.strolch.rest.model.AuditQueryResult;
import li.strolch.rest.model.StringListResult;
import li.strolch.rest.model.AuditQueryData;
import li.strolch.rest.model.visitor.ToAuditQueryVisitor;
@Path("strolch/audits")
@ -52,25 +44,26 @@ public class AuditsService {
StrolchRealm realm = RestfulStrolchComponent.getInstance().getContainer().getRealm(cert);
try (StrolchTransaction tx = realm.openTx(cert, AuditsService.class)) {
Set<String> data = tx.getAuditTrail().getTypes(tx);
return Response.ok(new StringListResult(new ArrayList<>(data)), MediaType.APPLICATION_JSON).build();
JsonArray dataJ = new JsonArray();
tx.getAuditTrail().getTypes(tx).forEach(dataJ::add);
return Response.ok(dataJ.toString(), MediaType.APPLICATION_JSON).build();
}
}
@POST
@GET
@Path("query")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response queryAudits(AuditQuery query, @Context HttpServletRequest request) {
public Response queryAudits(@BeanParam AuditQueryData query, @Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(StrolchRestfulConstants.STROLCH_CERTIFICATE);
StrolchRealm realm = RestfulStrolchComponent.getInstance().getContainer().getRealm(cert);
try (StrolchTransaction tx = realm.openTx(cert, AuditsService.class)) {
li.strolch.model.audit.AuditQuery<Audit> auditQuery = new ToAuditQueryVisitor().create(query);
List<Audit> audits = tx.getAuditTrail().doQuery(tx, auditQuery);
return Response.ok(new AuditQueryResult(audits), MediaType.APPLICATION_JSON).build();
JsonArray dataJ = new JsonArray();
tx.getAuditTrail().doQuery(tx, auditQuery).forEach(a -> a.accept(new AuditToJsonVisitor()));
return Response.ok(dataJ.toString(), MediaType.APPLICATION_JSON).build();
}
}
}

View File

@ -15,37 +15,16 @@
*/
package li.strolch.rest.endpoint;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.core.Response.Status;
import java.text.MessageFormat;
import java.util.Base64;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.*;
import li.strolch.exception.StrolchException;
import li.strolch.privilege.base.AccessDeniedException;
import li.strolch.privilege.base.InvalidCredentialsException;
@ -57,9 +36,11 @@ import li.strolch.privilege.model.Usage;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.StrolchSessionHandler;
import li.strolch.rest.model.Result;
import li.strolch.rest.helper.ResponseUtil;
import li.strolch.runtime.privilege.PrivilegeHandler;
import li.strolch.utils.helper.ExceptionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -92,8 +73,9 @@ public class AuthenticationService {
sb.append("Password was not given!"); //$NON-NLS-1$
}
char[] password = passwordE == null ? new char[] {}
: new String(Base64.getDecoder().decode(passwordE.getAsString())).toCharArray();
char[] password = passwordE == null ?
new char[] {} :
new String(Base64.getDecoder().decode(passwordE.getAsString())).toCharArray();
if (password.length < 3) {
if (sb.length() > 0)
sb.append("\n");
@ -101,7 +83,8 @@ public class AuthenticationService {
}
if (sb.length() != 0) {
loginResult.addProperty("msg", MessageFormat.format("Could not log in due to: {0}", sb.toString())); //$NON-NLS-1$
loginResult.addProperty("msg",
MessageFormat.format("Could not log in due to: {0}", sb.toString())); //$NON-NLS-1$
return Response.status(Status.BAD_REQUEST).entity(loginResult).build();
}
@ -175,11 +158,13 @@ public class AuthenticationService {
return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
} catch (AccessDeniedException e) {
logger.error("Authentication failed due to: " + e.getMessage());
loginResult.addProperty("msg", MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-1$
loginResult.addProperty("msg",
MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-1$
return Response.status(Status.UNAUTHORIZED).entity(loginResult.toString()).build();
} catch (StrolchException | PrivilegeException e) {
logger.error(e.getMessage(), e);
loginResult.addProperty("msg", MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-1$
loginResult.addProperty("msg",
MessageFormat.format("Could not log in due to: {0}", e.getMessage())); //$NON-NLS-1$
return Response.status(Status.FORBIDDEN).entity(loginResult.toString()).build();
} catch (Exception e) {
logger.error(e.getMessage(), e);
@ -211,12 +196,14 @@ public class AuthenticationService {
} catch (StrolchException | PrivilegeException e) {
logger.error("Failed to invalidate session due to: " + e.getMessage());
logoutResult.addProperty("msg", MessageFormat.format("Could not logout due to: {0}", e.getMessage())); //$NON-NLS-1$
logoutResult.addProperty("msg",
MessageFormat.format("Could not logout due to: {0}", e.getMessage())); //$NON-NLS-1$
return Response.status(Status.UNAUTHORIZED).entity(logoutResult.toString()).build();
} catch (Exception e) {
logger.error(e.getMessage(), e);
String msg = e.getMessage();
logoutResult.addProperty("msg", MessageFormat.format("{0}: {1}", e.getClass().getName(), msg)); //$NON-NLS-1$
logoutResult
.addProperty("msg", MessageFormat.format("{0}: {1}", e.getClass().getName(), msg)); //$NON-NLS-1$
return Response.serverError().entity(logoutResult.toString()).build();
}
}
@ -263,7 +250,7 @@ public class AuthenticationService {
StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
sessionHandler.initiateChallengeFor(Usage.byValue(usage), username);
return Response.ok(new Result(), MediaType.APPLICATION_JSON).build();
return ResponseUtil.toResponse();
} catch (PrivilegeException e) {
logger.error("Challenge initialization failed: " + e.getMessage());

View File

@ -15,18 +15,16 @@
*/
package li.strolch.rest.endpoint;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Locale;
import li.strolch.privilege.model.Certificate;
import li.strolch.rest.RestfulStrolchComponent;
@ -34,7 +32,6 @@ import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.helper.RestfulHelper;
import li.strolch.runtime.query.enums.EnumHandler;
import li.strolch.runtime.query.enums.StrolchEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -60,11 +57,7 @@ public class EnumQuery {
Certificate cert = (Certificate) request.getAttribute(StrolchRestfulConstants.STROLCH_CERTIFICATE);
Locale locale = RestfulHelper.getLocale(headers);
StrolchEnum strolchEnum = enumHandler.getEnum(cert, name, locale);
GenericEntity<StrolchEnum> entity = new GenericEntity<StrolchEnum>(strolchEnum, StrolchEnum.class) {
//
};
return Response.ok().entity(entity).build();
return Response.ok().entity(strolchEnum.toJson().toString()).build();
} catch (Exception e) {
logger.error(e.getMessage(), e);

View File

@ -17,6 +17,13 @@ package li.strolch.rest.endpoint;
import static li.strolch.rest.StrolchRestfulConstants.MSG;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.StringReader;
@ -26,34 +33,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.*;
import li.strolch.agent.api.ActivityMap;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.OrderMap;
@ -64,11 +44,7 @@ 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.ActivityFromJsonVisitor;
import li.strolch.model.json.FromFlatJsonVisitor;
import li.strolch.model.json.OrderFromJsonVisitor;
import li.strolch.model.json.ResourceFromJsonVisitor;
import li.strolch.model.json.StrolchElementToJsonVisitor;
import li.strolch.model.json.*;
import li.strolch.model.query.ActivityQuery;
import li.strolch.model.query.OrderQuery;
import li.strolch.model.query.ResourceQuery;
@ -84,28 +60,19 @@ import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.helper.ResponseUtil;
import li.strolch.rest.helper.RestfulHelper;
import li.strolch.rest.model.Result;
import li.strolch.service.AddActivityService;
import li.strolch.rest.model.QueryData;
import li.strolch.service.*;
import li.strolch.service.AddActivityService.AddActivityArg;
import li.strolch.service.AddOrderService;
import li.strolch.service.AddOrderService.AddOrderArg;
import li.strolch.service.AddResourceService;
import li.strolch.service.AddResourceService.AddResourceArg;
import li.strolch.service.LocatorArgument;
import li.strolch.service.RemoveActivityService;
import li.strolch.service.RemoveOrderService;
import li.strolch.service.RemoveResourceService;
import li.strolch.service.UpdateActivityService;
import li.strolch.service.UpdateActivityService.UpdateActivityArg;
import li.strolch.service.UpdateOrderService;
import li.strolch.service.UpdateOrderService.UpdateOrderArg;
import li.strolch.service.UpdateResourceService;
import li.strolch.service.UpdateResourceService.UpdateResourceArg;
import li.strolch.service.XmlImportModelArgument;
import li.strolch.service.XmlImportModelResult;
import li.strolch.service.XmlImportModelService;
import li.strolch.service.api.ServiceResult;
import li.strolch.utils.helper.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -116,8 +83,8 @@ public class Inspector {
private static final Logger logger = LoggerFactory.getLogger(Inspector.class);
private StrolchTransaction openTx(Certificate certificate, String realm) {
return RestfulStrolchComponent.getInstance().getContainer().getRealm(realm).openTx(certificate,
Inspector.class);
return RestfulStrolchComponent.getInstance().getContainer().getRealm(realm)
.openTx(certificate, Inspector.class);
}
private String toString(JsonObject jsonObject) {
@ -129,11 +96,11 @@ public class Inspector {
* <p>
* Root path of the inspector
* </p>
*
* <p>
* <p>
* Returns the root element, which is an overview of the configured realms
* </p>
*
*
* @return the root element, which is an overview of the configured realms
*/
@GET
@ -176,14 +143,12 @@ public class Inspector {
* <p>
* Realm inspector
* </p>
*
* <p>
* <p>
* Returns the overview of a specific relam
* </p>
*
* @param realm
* the realm for which the overview is to be returned
*
*
* @param realm the realm for which the overview is to be returned
* @return the overview of a specific relam
*/
@GET
@ -246,10 +211,8 @@ public class Inspector {
* <p>
* Returns an overview of the {@link Resource Resources}. This is a list of all the types and the size each type has
* </p>
*
* @param realm
* the realm for which the resource overview is to be returned
*
*
* @param realm the realm for which the resource overview is to be returned
* @return an overview of the {@link Resource Resources}. This is a list of all the types and the size each type has
*/
@GET
@ -292,10 +255,8 @@ public class Inspector {
* <p>
* Returns an overview of the {@link Order Orders}. This is a list of all the types and the size each type has
* </p>
*
* @param realm
* the realm for which the order overview is to be returned
*
*
* @param realm the realm for which the order overview is to be returned
* @return an overview of the {@link Order Orders}. This is a list of all the types and the size each type has
*/
@GET
@ -339,12 +300,10 @@ public class Inspector {
* Returns an overview of the {@link Activity Activities}. This is a list of all the types and the size each type
* has
* </p>
*
* @param realm
* the realm for which the activity overview is to be returned
*
*
* @param realm the realm for which the activity overview is to be returned
* @return an overview of the {@link Activity Activities}. This is a list of all the types and the size each type
* has
* has
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@ -389,13 +348,11 @@ public class Inspector {
* Returns an overview of the {@link Resource Resources} with the given type. This is a list of overviews of the
* resources
* </p>
*
* @param realm
* the realm for which the resource type overview is to be returned
* @param type
* marshall
*
* @param realm the realm for which the resource type overview is to be returned
* @param type marshall
* @return an overview of the {@link Resource Resources} with the given type. This is a list of overviews of the
* resources
* resources
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@ -440,11 +397,9 @@ public class Inspector {
* <p>
* Returns an overview of the {@link Order Orders} with the given type. This is a list of overviews of the orders
* </p>
*
* @param realm
* the realm for which the order type overview is to be returned
*
* @param realm the realm for which the order type overview is to be returned
* @param type
*
* @return an overview of the {@link Order Orders} with the given type. This is a list of overviews of the orders
*/
@GET
@ -603,18 +558,14 @@ public class Inspector {
* <p>
* Activity inspector
* </p>
*
* <p>
* <p>
* Returns the activity with the given id
* </p>
*
* @param realm
* the realm for which the activity is to be returned
* @param type
* the type of the activity
* @param id
* the id of the activity
*
*
* @param realm the realm for which the activity is to be returned
* @param type the type of the activity
* @param id the id of the activity
* @return the activity with the given id
*/
@GET
@ -681,7 +632,7 @@ public class Inspector {
return Response.ok().type(MediaType.APPLICATION_XML).entity(asXml).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@PUT
@ -731,7 +682,7 @@ public class Inspector {
return Response.ok().entity(toString(resource.accept(toJsonVisitor))).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@PUT
@ -756,7 +707,7 @@ public class Inspector {
return Response.ok().type(MediaType.APPLICATION_XML).entity(asXml).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@PUT
@ -806,7 +757,7 @@ public class Inspector {
return Response.ok().entity(toString(order.accept(toJsonVisitor))).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@PUT
@ -831,7 +782,7 @@ public class Inspector {
return Response.ok().type(MediaType.APPLICATION_XML).entity(asXml).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@PUT
@ -881,7 +832,7 @@ public class Inspector {
return Response.ok().entity(toString(activity.accept(toJsonVisitor))).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@POST
@ -913,8 +864,8 @@ public class Inspector {
arg.resourceTypes = Collections.emptySet();
arg.realm = realm;
XmlImportModelResult svcResult = RestfulStrolchComponent.getInstance().getServiceHandler().doService(cert,
svc, arg);
XmlImportModelResult svcResult = RestfulStrolchComponent.getInstance().getServiceHandler()
.doService(cert, svc, arg);
if (svcResult.isOk())
return ResponseUtil.toResponse(MSG, svcResult.getStatistics().toString());
return ResponseUtil.toResponse(svcResult);
@ -951,7 +902,7 @@ public class Inspector {
return Response.ok().type(MediaType.APPLICATION_XML).entity(asXml).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@POST
@ -979,7 +930,7 @@ public class Inspector {
return Response.ok().entity(toString(resource.accept(toJsonVisitor))).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@POST
@ -1007,7 +958,7 @@ public class Inspector {
return Response.ok().entity(toString(resource.accept(toJsonVisitor))).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@POST
@ -1031,7 +982,7 @@ public class Inspector {
return Response.ok().type(MediaType.APPLICATION_XML).entity(asXml).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@POST
@ -1058,7 +1009,7 @@ public class Inspector {
return Response.ok().entity(toString(order.accept(toJsonVisitor))).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@POST
@ -1086,7 +1037,7 @@ public class Inspector {
return Response.ok().entity(toString(order.accept(toJsonVisitor))).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@POST
@ -1111,7 +1062,7 @@ public class Inspector {
return Response.ok().type(MediaType.APPLICATION_XML).entity(asXml).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@POST
@ -1139,7 +1090,7 @@ public class Inspector {
return Response.ok().entity(toString(activity.accept(toJsonVisitor))).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@POST
@ -1167,7 +1118,7 @@ public class Inspector {
return Response.ok().entity(toString(activity.accept(toJsonVisitor))).build();
}
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@DELETE
@ -1184,7 +1135,7 @@ public class Inspector {
arg.realm = realm;
ServiceResult result = RestfulStrolchComponent.getInstance().getServiceHandler().doService(cert, svc, arg);
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@DELETE
@ -1201,7 +1152,7 @@ public class Inspector {
arg.realm = realm;
ServiceResult result = RestfulStrolchComponent.getInstance().getServiceHandler().doService(cert, svc, arg);
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
@DELETE
@ -1218,7 +1169,7 @@ public class Inspector {
arg.realm = realm;
ServiceResult result = RestfulStrolchComponent.getInstance().getServiceHandler().doService(cert, svc, arg);
return Result.toResponse(result);
return ResponseUtil.toResponse(result);
}
private Resource parseResourceFromXml(String type, String data) {
@ -1229,17 +1180,23 @@ 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);
} 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;
}
@ -1255,14 +1212,18 @@ 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);
} 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;
}
@ -1275,17 +1236,23 @@ 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);
} 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;
}

View File

@ -1,9 +1,5 @@
package li.strolch.rest.endpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.BeanParam;
import javax.ws.rs.GET;
@ -12,11 +8,13 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import li.strolch.agent.api.ActivityMap;
import li.strolch.agent.api.OrderMap;
import li.strolch.agent.api.ResourceMap;
@ -34,6 +32,7 @@ import li.strolch.privilege.model.Certificate;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.helper.RestfulHelper;
import li.strolch.rest.model.QueryData;
@Path("strolch/model")
public class ModelQuery {

View File

@ -15,24 +15,21 @@
*/
package li.strolch.rest.endpoint;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;
import com.google.gson.JsonObject;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.privilege.handler.PrivilegeHandler;
import li.strolch.privilege.model.Certificate;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.utils.xml.XmlKeyValue;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -54,9 +51,11 @@ public class PrivilegePoliciesService {
PrivilegeHandler privilegeHandler = getPrivilegeHandler();
Map<String, String> policyDefs = privilegeHandler.getPolicyDefs(cert);
List<XmlKeyValue> values = XmlKeyValue.valueOf(policyDefs);
GenericEntity<List<XmlKeyValue>> entity = new GenericEntity<List<XmlKeyValue>>(values) {
};
return Response.ok(entity, MediaType.APPLICATION_JSON).build();
JsonObject policiesJ = new JsonObject();
for (String key : policyDefs.keySet()) {
policiesJ.addProperty(key, policyDefs.get(key));
}
return Response.ok(policiesJ.toString(), MediaType.APPLICATION_JSON).build();
}
}

View File

@ -15,44 +15,25 @@
*/
package li.strolch.rest.endpoint;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.util.List;
import com.google.gson.JsonArray;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.privilege.base.AccessDeniedException;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.model.json.PrivilegeElementToJsonVisitor;
import li.strolch.privilege.handler.PrivilegeHandler;
import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.PrivilegeRep;
import li.strolch.privilege.model.RoleRep;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.model.Result;
import li.strolch.rest.helper.ResponseUtil;
import li.strolch.service.api.ServiceHandler;
import li.strolch.service.privilege.roles.PrivilegeAddOrReplacePrivilegeOnRoleArgument;
import li.strolch.service.privilege.roles.PrivilegeAddOrReplacePrivilegeOnRoleService;
import li.strolch.service.privilege.roles.PrivilegeAddRoleService;
import li.strolch.service.privilege.roles.PrivilegeRemovePrivilegeFromRoleArgument;
import li.strolch.service.privilege.roles.PrivilegeRemovePrivilegeFromRoleService;
import li.strolch.service.privilege.roles.PrivilegeRemoveRoleService;
import li.strolch.service.privilege.roles.PrivilegeRoleArgument;
import li.strolch.service.privilege.roles.PrivilegeRoleNameArgument;
import li.strolch.service.privilege.roles.PrivilegeRoleResult;
import li.strolch.service.privilege.roles.PrivilegeUpdateRoleService;
import li.strolch.service.privilege.roles.*;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -72,9 +53,8 @@ public class PrivilegeRolesService {
PrivilegeHandler privilegeHandler = getPrivilegeHandler();
List<RoleRep> roles = privilegeHandler.getRoles(cert);
GenericEntity<List<RoleRep>> entity = new GenericEntity<List<RoleRep>>(roles) {
};
return Response.ok(entity, MediaType.APPLICATION_JSON).build();
JsonArray rolesJ = toJson(roles);
return Response.ok(rolesJ.toString(), MediaType.APPLICATION_JSON).build();
}
@GET
@ -85,7 +65,7 @@ public class PrivilegeRolesService {
PrivilegeHandler privilegeHandler = getPrivilegeHandler();
RoleRep role = privilegeHandler.getRole(cert, rolename);
return Response.ok(role, MediaType.APPLICATION_JSON).build();
return Response.ok(role.accept(new PrivilegeElementToJsonVisitor()), MediaType.APPLICATION_JSON).build();
}
@POST
@ -111,9 +91,10 @@ public class PrivilegeRolesService {
@Context HttpServletRequest request) {
Certificate cert = (Certificate) request.getAttribute(StrolchRestfulConstants.STROLCH_CERTIFICATE);
if (!rolename.equals(updatedRole.getName()))
return Response.serverError().entity(new Result("Path rolename and data do not have same role name!"))
.type(MediaType.APPLICATION_JSON).build();
if (!rolename.equals(updatedRole.getName())) {
String msg = "Path rolename and data do not have same role name!";
return ResponseUtil.toResponse(msg);
}
ServiceHandler svcHandler = RestfulStrolchComponent.getInstance().getComponent(ServiceHandler.class);
PrivilegeUpdateRoleService svc = new PrivilegeUpdateRoleService();
@ -178,17 +159,17 @@ public class PrivilegeRolesService {
private Response handleServiceResult(PrivilegeRoleResult svcResult) {
if (svcResult.isOk()) {
return Response.ok(svcResult.getRole(), MediaType.APPLICATION_JSON).build();
} else if (svcResult.getThrowable() != null) {
Throwable t = svcResult.getThrowable();
if (t instanceof AccessDeniedException) {
return Response.status(Status.FORBIDDEN).entity(new Result(t.getMessage()))
.type(MediaType.APPLICATION_JSON).build();
} else if (t instanceof PrivilegeException) {
return Response.status(Status.UNAUTHORIZED).entity(new Result(t.getMessage())).build();
}
RoleRep roleRep = svcResult.getRole();
return Response.ok(roleRep.accept(new PrivilegeElementToJsonVisitor()), MediaType.APPLICATION_JSON).build();
}
return ResponseUtil.toResponse(svcResult);
}
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new Result(svcResult.getMessage())).build();
private JsonArray toJson(List<RoleRep> roles) {
JsonArray rolesArr = new JsonArray();
for (RoleRep roleRep : roles) {
rolesArr.add(roleRep.accept(new PrivilegeElementToJsonVisitor()));
}
return rolesArr;
}
}

View File

@ -15,38 +15,21 @@
*/
package li.strolch.rest.endpoint;
import java.text.MessageFormat;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.text.MessageFormat;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.privilege.base.AccessDeniedException;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.model.json.PrivilegeElementFromJsonVisitor;
import li.strolch.model.json.PrivilegeElementToJsonVisitor;
import li.strolch.privilege.handler.PrivilegeHandler;
import li.strolch.privilege.model.Certificate;
import li.strolch.privilege.model.UserRep;
@ -54,24 +37,10 @@ import li.strolch.privilege.model.UserState;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.StrolchSessionHandler;
import li.strolch.rest.model.Result;
import li.strolch.rest.helper.ResponseUtil;
import li.strolch.service.api.ServiceHandler;
import li.strolch.service.api.ServiceResult;
import li.strolch.service.privilege.users.PrivilegeAddRoleToUserService;
import li.strolch.service.privilege.users.PrivilegeAddUserService;
import li.strolch.service.privilege.users.PrivilegeRemoveRoleFromUserService;
import li.strolch.service.privilege.users.PrivilegeRemoveUserService;
import li.strolch.service.privilege.users.PrivilegeRoleUserNamesArgument;
import li.strolch.service.privilege.users.PrivilegeSetUserLocaleArgument;
import li.strolch.service.privilege.users.PrivilegeSetUserLocaleService;
import li.strolch.service.privilege.users.PrivilegeSetUserPasswordArgument;
import li.strolch.service.privilege.users.PrivilegeSetUserPasswordService;
import li.strolch.service.privilege.users.PrivilegeSetUserStateArgument;
import li.strolch.service.privilege.users.PrivilegeSetUserStateService;
import li.strolch.service.privilege.users.PrivilegeUpdateUserService;
import li.strolch.service.privilege.users.PrivilegeUserArgument;
import li.strolch.service.privilege.users.PrivilegeUserNameArgument;
import li.strolch.service.privilege.users.PrivilegeUserResult;
import li.strolch.service.privilege.users.*;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -84,83 +53,6 @@ public class PrivilegeUsersService {
return container.getPrivilegeHandler().getPrivilegeHandler();
}
private JsonArray toJson(List<UserRep> users) {
JsonArray usersArr = new JsonArray();
for (UserRep userRep : users) {
usersArr.add(toJson(userRep));
}
return usersArr;
}
private JsonObject toJson(UserRep userRep) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("userId", userRep.getUserId());
jsonObject.addProperty("username", userRep.getUsername());
jsonObject.addProperty("firstname", userRep.getFirstname());
jsonObject.addProperty("lastname", userRep.getLastname());
jsonObject.addProperty("userState", userRep.getUserState().name());
jsonObject.addProperty("locale", userRep.getLocale().toString());
JsonArray rolesArr = new JsonArray();
jsonObject.add("roles", rolesArr);
for (String role : userRep.getRoles()) {
rolesArr.add(new JsonPrimitive(role));
}
JsonArray propsArr = new JsonArray();
jsonObject.add("properties", propsArr);
for (String propKey : userRep.getPropertyKeySet()) {
JsonObject propObj = new JsonObject();
propObj.addProperty("key", propKey);
propObj.addProperty("value", userRep.getProperty(propKey));
propsArr.add(propObj);
}
return jsonObject;
}
private UserRep fromJson(JsonObject jsonObject) {
JsonElement userIdE = jsonObject.get("userId");
JsonElement usernameE = jsonObject.get("username");
JsonElement firstnameE = jsonObject.get("firstname");
JsonElement lastnameE = jsonObject.get("lastname");
JsonElement userStateE = jsonObject.get("userState");
JsonElement localeE = jsonObject.get("locale");
JsonElement rolesE = jsonObject.get("roles");
JsonElement propertiesE = jsonObject.get("properties");
String userId = userIdE == null ? null : userIdE.getAsString();
String username = usernameE == null ? null : usernameE.getAsString();
String firstname = firstnameE == null ? null : firstnameE.getAsString();
String lastname = lastnameE == null ? null : lastnameE.getAsString();
UserState userState = userStateE == null ? null : UserState.valueOf(userStateE.getAsString());
Locale locale = localeE == null ? null : new Locale(localeE.getAsString());
Set<String> roles = null;
if (rolesE != null) {
roles = new HashSet<>();
JsonArray rolesArr = rolesE.getAsJsonArray();
for (JsonElement role : rolesArr) {
roles.add(role.getAsString());
}
}
Map<String, String> properties = null;
if (propertiesE != null) {
properties = new HashMap<>();
JsonArray propertiesArr = propertiesE.getAsJsonArray();
for (JsonElement propertyE : propertiesArr) {
JsonObject property = propertyE.getAsJsonObject();
properties.put(property.get("key").getAsString(), property.get("value").getAsString());
}
}
UserRep userRep = new UserRep(userId, username, firstname, lastname, userState, roles, locale, properties);
return userRep;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers(@Context HttpServletRequest request) {
@ -180,7 +72,8 @@ public class PrivilegeUsersService {
PrivilegeHandler privilegeHandler = getPrivilegeHandler();
UserRep user = privilegeHandler.getUser(cert, username);
return Response.ok(toJson(user).toString(), MediaType.APPLICATION_JSON).build();
return Response.ok(user.accept(new PrivilegeElementToJsonVisitor()).toString(), MediaType.APPLICATION_JSON)
.build();
}
@POST
@ -191,7 +84,7 @@ public class PrivilegeUsersService {
Certificate cert = (Certificate) request.getAttribute(StrolchRestfulConstants.STROLCH_CERTIFICATE);
PrivilegeHandler privilegeHandler = getPrivilegeHandler();
UserRep queryRep = fromJson(new JsonParser().parse(query).getAsJsonObject());
UserRep queryRep = new PrivilegeElementFromJsonVisitor().userRepFromJson(query);
List<UserRep> users = privilegeHandler.queryUsers(cert, queryRep);
JsonArray usersArr = toJson(users);
return Response.ok(usersArr.toString(), MediaType.APPLICATION_JSON).build();
@ -206,7 +99,7 @@ public class PrivilegeUsersService {
ServiceHandler svcHandler = RestfulStrolchComponent.getInstance().getComponent(ServiceHandler.class);
PrivilegeAddUserService svc = new PrivilegeAddUserService();
PrivilegeUserArgument arg = new PrivilegeUserArgument();
arg.user = fromJson(new JsonParser().parse(newUser).getAsJsonObject());
arg.user = new PrivilegeElementFromJsonVisitor().userRepFromJson(newUser);
PrivilegeUserResult svcResult = svcHandler.doService(cert, svc, arg);
return handleServiceResult(svcResult);
@ -239,7 +132,7 @@ public class PrivilegeUsersService {
ServiceHandler svcHandler = RestfulStrolchComponent.getInstance().getComponent(ServiceHandler.class);
PrivilegeUpdateUserService svc = new PrivilegeUpdateUserService();
PrivilegeUserArgument arg = new PrivilegeUserArgument();
arg.user = fromJson(new JsonParser().parse(updatedFields).getAsJsonObject());
arg.user = new PrivilegeElementFromJsonVisitor().userRepFromJson(updatedFields);
PrivilegeUserResult svcResult = svcHandler.doService(cert, svc, arg);
return handleServiceResult(svcResult);
@ -293,7 +186,7 @@ public class PrivilegeUsersService {
userState = UserState.valueOf(state);
} catch (Exception e) {
String msg = MessageFormat.format("UserState {0} is not valid!", state);
return Response.serverError().entity(new Result(msg)).type(MediaType.APPLICATION_JSON).build();
return ResponseUtil.toResponse(msg);
}
ServiceHandler svcHandler = RestfulStrolchComponent.getInstance().getComponent(ServiceHandler.class);
@ -306,22 +199,6 @@ public class PrivilegeUsersService {
return handleServiceResult(svcResult);
}
private Response handleServiceResult(PrivilegeUserResult svcResult) {
if (svcResult.isOk()) {
return Response.ok(toJson(svcResult.getUser()), MediaType.APPLICATION_JSON).build();
} else if (svcResult.getThrowable() != null) {
Throwable t = svcResult.getThrowable();
if (t instanceof AccessDeniedException) {
return Response.status(Status.FORBIDDEN).entity(new Result(t.getMessage()))
.type(MediaType.APPLICATION_JSON).build();
} else if (t instanceof PrivilegeException) {
return Response.status(Status.UNAUTHORIZED).entity(new Result(t.getMessage())).build();
}
}
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new Result(svcResult.getMessage())).build();
}
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("{username}/locale/{locale}")
@ -334,7 +211,7 @@ public class PrivilegeUsersService {
locale = new Locale(localeS);
} catch (Exception e) {
String msg = MessageFormat.format("Locale {0} is not valid!", localeS);
return Response.serverError().entity(new Result(msg)).type(MediaType.APPLICATION_JSON).build();
return ResponseUtil.toResponse(msg);
}
ServiceHandler svcHandler = RestfulStrolchComponent.getInstance().getComponent(ServiceHandler.class);
@ -355,36 +232,41 @@ public class PrivilegeUsersService {
Certificate cert = (Certificate) request.getAttribute(StrolchRestfulConstants.STROLCH_CERTIFICATE);
String password = new JsonParser().parse(data).getAsJsonObject().get("password").getAsString();
char[] passwordChars = new String(Base64.getDecoder().decode(password)).toCharArray();
ServiceHandler svcHandler = RestfulStrolchComponent.getInstance().getComponent(ServiceHandler.class);
PrivilegeSetUserPasswordService svc = new PrivilegeSetUserPasswordService();
PrivilegeSetUserPasswordArgument arg = new PrivilegeSetUserPasswordArgument();
arg.username = username;
arg.password = new String(Base64.getDecoder().decode(password)).toCharArray();
arg.password = passwordChars;
ServiceResult svcResult = svcHandler.doService(cert, svc, arg);
if (svcResult.isOk()) {
if (svcResult.isNok())
return ResponseUtil.toResponse(svcResult);
// if user changes their own password, then invalidate the session
if (cert.getUsername().equals(username)) {
StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
sessionHandler.invalidate(cert);
}
// TODO invalidate any other sessions for this user
return Response.ok(new Result(), MediaType.APPLICATION_JSON).build();
} else if (svcResult.getThrowable() != null) {
Throwable t = svcResult.getThrowable();
if (t instanceof AccessDeniedException) {
return Response.status(Status.UNAUTHORIZED).entity(new Result(t.getMessage()))
.type(MediaType.APPLICATION_JSON).build();
} else if (t instanceof PrivilegeException) {
return Response.status(Status.FORBIDDEN).entity(new Result(t.getMessage())).build();
}
// if user changes their own password, then invalidate the session
if (cert.getUsername().equals(username)) {
StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
sessionHandler.invalidate(cert);
}
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new Result(svcResult.getMessage())).build();
return ResponseUtil.toResponse();
}
private Response handleServiceResult(PrivilegeUserResult svcResult) {
if (svcResult.isOk()) {
UserRep userRep = svcResult.getUser();
return Response.ok(userRep.accept(new PrivilegeElementToJsonVisitor()), MediaType.APPLICATION_JSON).build();
}
return ResponseUtil.toResponse(svcResult);
}
private JsonArray toJson(List<UserRep> users) {
JsonArray usersArr = new JsonArray();
for (UserRep userRep : users) {
usersArr.add(userRep.accept(new PrivilegeElementToJsonVisitor()));
}
return usersArr;
}
}

View File

@ -15,29 +15,21 @@
*/
package li.strolch.rest.endpoint;
import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.MessageFormat;
import java.util.Locale;
import com.google.gson.JsonArray;
import li.strolch.privilege.model.Certificate;
import li.strolch.rest.RestfulStrolchComponent;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.StrolchSessionHandler;
import li.strolch.rest.model.Result;
import li.strolch.rest.helper.ResponseUtil;
import li.strolch.rest.model.UserSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -52,10 +44,10 @@ public class UserSessionsService {
Certificate cert = (Certificate) request.getAttribute(StrolchRestfulConstants.STROLCH_CERTIFICATE);
logger.info("[" + cert.getUsername() + "] Returning all sessions...");
StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
List<UserSession> sessions = sessionHandler.getSessions(cert);
GenericEntity<List<UserSession>> entity = new GenericEntity<List<UserSession>>(sessions) {
};
return Response.ok(entity, MediaType.APPLICATION_JSON).build();
JsonArray sessionsJ = new JsonArray();
sessionHandler.getSessions(cert).stream().map(UserSession::toJson).forEach(sessionsJ::add);
return Response.ok(sessionsJ.toString(), MediaType.APPLICATION_JSON).build();
}
@GET
@ -66,7 +58,7 @@ public class UserSessionsService {
logger.info("[" + cert.getUsername() + "] Returning session " + sessionId);
StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
UserSession session = sessionHandler.getSession(cert, sessionId);
return Response.ok(session, MediaType.APPLICATION_JSON).build();
return Response.ok(session.toJson().toString(), MediaType.APPLICATION_JSON).build();
}
@DELETE
@ -77,7 +69,7 @@ public class UserSessionsService {
logger.info("[" + cert.getUsername() + "] Invalidating session " + sessionId);
StrolchSessionHandler sessionHandler = RestfulStrolchComponent.getInstance().getSessionHandler();
sessionHandler.invalidateSession(cert, sessionId);
return Response.ok(new Result(), MediaType.APPLICATION_JSON).build();
return ResponseUtil.toResponse();
}
@PUT
@ -93,10 +85,10 @@ public class UserSessionsService {
locale = new Locale(localeS);
} catch (Exception e) {
String msg = MessageFormat.format("Locale {0} is not valid!", localeS);
return Response.serverError().entity(new Result(msg)).type(MediaType.APPLICATION_JSON).build();
return Response.serverError().entity(ResponseUtil.toResponse(msg)).type(MediaType.APPLICATION_JSON).build();
}
sessionHandler.setSessionLocale(cert, sessionId, locale);
return Response.ok(new Result(), MediaType.APPLICATION_JSON).build();
return ResponseUtil.toResponse();
}
}

View File

@ -20,7 +20,6 @@ import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@ -44,10 +43,6 @@ public class VersionQuery {
instance.getSessionHandler().validate(cert);
VersionQueryResult versionQueryResult = instance.getContainer().getAgent().getVersion();
GenericEntity<VersionQueryResult> entity = new GenericEntity<VersionQueryResult>(versionQueryResult,
VersionQueryResult.class) {
//
};
return Response.ok().entity(entity).build();
return Response.ok(versionQueryResult.toJson().toString(), MediaType.APPLICATION_JSON).build();
}
}

View File

@ -1,27 +1,19 @@
package li.strolch.rest.helper;
import static li.strolch.rest.StrolchRestfulConstants.DATA;
import static li.strolch.rest.StrolchRestfulConstants.EXCEPTION_MSG;
import static li.strolch.rest.StrolchRestfulConstants.LAST_OFFSET;
import static li.strolch.rest.StrolchRestfulConstants.LIMIT;
import static li.strolch.rest.StrolchRestfulConstants.MSG;
import static li.strolch.rest.StrolchRestfulConstants.NEXT_OFFSET;
import static li.strolch.rest.StrolchRestfulConstants.OFFSET;
import static li.strolch.rest.StrolchRestfulConstants.PREVIOUS_OFFSET;
import static li.strolch.rest.StrolchRestfulConstants.SIZE;
import java.util.List;
import java.util.function.Function;
import static li.strolch.rest.StrolchRestfulConstants.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.util.List;
import java.util.function.Function;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import li.strolch.privilege.base.AccessDeniedException;
import li.strolch.privilege.base.PrivilegeException;
import li.strolch.service.api.ServiceResult;
import li.strolch.utils.collections.Paging;
import li.strolch.utils.helper.ExceptionHelper;
@ -41,6 +33,15 @@ public class ResponseUtil {
return Response.ok(json, MediaType.APPLICATION_JSON).build();
}
public static Response toResponse(String errorMsg) {
JsonObject response = new JsonObject();
response.addProperty(MSG, errorMsg);
String json = new Gson().toJson(response);
return Response.serverError().entity(json).type(MediaType.APPLICATION_JSON).build();
}
public static Response toResponse(String prop, String value) {
JsonObject response = new JsonObject();
response.addProperty(MSG, StringHelper.DASH);
@ -92,9 +93,9 @@ public class ResponseUtil {
String msg = StringHelper.DASH;
String exceptionMsg = StringHelper.DASH;
Throwable t = svcResult.getThrowable();
if (svcResult.isNok()) {
msg = svcResult.getMessage();
Throwable t = svcResult.getThrowable();
if (t != null)
exceptionMsg = StringHelper.formatExceptionMessage(t);
}
@ -109,11 +110,26 @@ public class ResponseUtil {
if (svcResult.isOk())
return Response.ok().entity(json).type(MediaType.APPLICATION_JSON).build();
return Response.serverError().entity(json).type(MediaType.APPLICATION_JSON).build();
Status status;
if (t instanceof AccessDeniedException) {
status = Status.FORBIDDEN;
} else if (t instanceof PrivilegeException) {
status = Status.UNAUTHORIZED;
} else {
status = Status.INTERNAL_SERVER_ERROR;
}
return Response.status(status).entity(json).type(MediaType.APPLICATION_JSON).build();
}
public static Response toResponse(Throwable t) {
return toResponse(Status.INTERNAL_SERVER_ERROR, t);
if (t instanceof AccessDeniedException) {
return ResponseUtil.toResponse(Status.FORBIDDEN, t);
} else if (t instanceof PrivilegeException) {
return ResponseUtil.toResponse(Status.UNAUTHORIZED, t);
} else {
return toResponse(Status.INTERNAL_SERVER_ERROR, t);
}
}
public static Response toResponse(Status status, String msg) {

View File

@ -32,7 +32,7 @@ import li.strolch.model.Tags;
import li.strolch.model.visitor.StrolchElementVisitor;
import li.strolch.privilege.model.Certificate;
import li.strolch.rest.StrolchRestfulConstants;
import li.strolch.rest.endpoint.QueryData;
import li.strolch.rest.model.QueryData;
import li.strolch.utils.collections.Paging;
import li.strolch.utils.dbc.DBC;
import li.strolch.utils.helper.StringHelper;

View File

@ -1,56 +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.rest.model;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import li.strolch.model.audit.AccessType;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "ActionSelection")
@XmlAccessorType(XmlAccessType.NONE)
public class ActionSelection {
@XmlAttribute(name = "action")
private String action;
@XmlElement(name = "accessTypes")
private List<AccessType> accessTypes;
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public List<AccessType> getAccessTypes() {
return accessTypes;
}
public void setAccessTypes(List<AccessType> accessTypes) {
this.accessTypes = accessTypes;
}
}

View File

@ -15,38 +15,44 @@
*/
package li.strolch.rest.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.ws.rs.QueryParam;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "AuditQuery")
@XmlAccessorType(XmlAccessType.NONE)
public class AuditQuery {
public class AuditQueryData {
@XmlAttribute(name = "elementType")
@QueryParam("elementType")
private String elementType;
@XmlAttribute(name = "elementSubType")
@QueryParam("elementSubType")
private String elementSubType;
@XmlAttribute(name = "elementId")
@QueryParam("elementId")
private String elementId;
@XmlElement(name = "identity")
private IdentitySelection identity;
@QueryParam("username")
private String username;
@XmlElement(name = "action")
private ActionSelection action;
@QueryParam("firstname")
private String firstname;
@XmlElement(name = "dateRange")
private DateRange dateRange;
@QueryParam("lastname")
private String lastname;
@XmlElement(name = "limit")
@QueryParam("action")
private String action;
@QueryParam("accessTypes")
private String accessTypes;
@QueryParam("fromDate")
private String fromDate;
@QueryParam("toDate")
private String toDate;
@QueryParam("limit")
private long limit;
public String getElementType() {
@ -73,28 +79,60 @@ public class AuditQuery {
this.elementId = elementId;
}
public IdentitySelection getIdentity() {
return identity;
public String getUsername() {
return username;
}
public void setIdentity(IdentitySelection identity) {
this.identity = identity;
public void setUsername(String username) {
this.username = username;
}
public ActionSelection getAction() {
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getAction() {
return action;
}
public void setAction(ActionSelection action) {
public void setAction(String action) {
this.action = action;
}
public DateRange getDateRange() {
return dateRange;
public String getAccessTypes() {
return accessTypes;
}
public void setDateRange(DateRange dateRange) {
this.dateRange = dateRange;
public void setAccessTypes(String accessTypes) {
this.accessTypes = accessTypes;
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public long getLimit() {

View File

@ -1,63 +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.rest.model;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import li.strolch.model.audit.Audit;
import li.strolch.utils.helper.StringHelper;
@XmlRootElement(name = "AuditQueryResult")
@XmlAccessorType(XmlAccessType.NONE)
public class AuditQueryResult {
@XmlAttribute(name = "msg")
private String msg;
@XmlElement(name = "audits")
private List<Audit> audits;
public AuditQueryResult() {
this.msg = StringHelper.DASH;
}
public AuditQueryResult(List<Audit> audits) {
this.msg = StringHelper.DASH;
this.audits = audits;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<Audit> getAudits() {
return audits;
}
public void setAudits(List<Audit> audits) {
this.audits = audits;
}
}

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.rest.model;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import li.strolch.model.xml.Iso8601DateAdapter;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "DateRange")
@XmlAccessorType(XmlAccessType.NONE)
public class DateRange {
@XmlAttribute(name = "fromInclusive")
private boolean fromInclusive;
@XmlAttribute(name = "toInclusive")
private boolean toInclusive;
@XmlElement(name = "fromDate")
@XmlJavaTypeAdapter(Iso8601DateAdapter.class)
private Date fromDate;
@XmlElement(name = "toDate")
@XmlJavaTypeAdapter(Iso8601DateAdapter.class)
private Date toDate;
public boolean isFromInclusive() {
return fromInclusive;
}
public void setFromInclusive(boolean fromInclusive) {
this.fromInclusive = fromInclusive;
}
public boolean isToInclusive() {
return toInclusive;
}
public void setToInclusive(boolean toInclusive) {
this.toInclusive = toInclusive;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
}

View File

@ -1,62 +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.rest.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "IdentitySelection")
@XmlAccessorType(XmlAccessType.NONE)
public class IdentitySelection {
@XmlAttribute(name = "username")
private String username;
@XmlAttribute(name = "firstname")
private String firstname;
@XmlAttribute(name = "lastname")
private String lastname;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}

View File

@ -1,40 +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.rest.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "PasswordField")
@XmlAccessorType(XmlAccessType.NONE)
public class PasswordField {
@XmlAttribute(name = "password")
private byte[] password;
public byte[] getPassword() {
return password;
}
public void setPassword(byte[] password) {
this.password = password;
}
}

View File

@ -1,4 +1,4 @@
package li.strolch.rest.endpoint;
package li.strolch.rest.model;
import javax.ws.rs.QueryParam;

View File

@ -1,93 +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.rest.model;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import li.strolch.service.api.ServiceResult;
import li.strolch.utils.helper.StringHelper;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "Result")
@XmlAccessorType(XmlAccessType.NONE)
public class Result {
@XmlAttribute(name = "msg")
private String msg;
@XmlAttribute(name = "exceptionMsg")
private String exceptionMsg;
public Result(String msg) {
this.msg = msg;
}
public Result(Exception e) {
this.msg = StringHelper.isEmpty(e.getMessage()) ? e.getClass().getName() : e.getMessage();
this.exceptionMsg = StringHelper.formatExceptionMessage(e);
}
public Result(ServiceResult svcResult) {
if (svcResult.isOk()) {
this.msg = StringHelper.DASH;
} else {
this.msg = svcResult.getMessage();
Throwable t = svcResult.getThrowable();
if (t != null)
this.exceptionMsg = StringHelper.formatExceptionMessage(t);
}
}
public Result() {
this.msg = StringHelper.DASH;
}
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getExceptionMsg() {
return exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
public static Response toResponse(String msg) {
Result result = new Result(msg);
return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON).entity(result).build();
}
public static Response toResponse(ServiceResult svcResult) {
Result result = new Result(svcResult);
if (svcResult.isOk())
return Response.ok(result, MediaType.APPLICATION_JSON).build();
return Response.serverError().type(MediaType.APPLICATION_JSON).entity(result).build();
}
}

View File

@ -1,62 +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.rest.model;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import li.strolch.utils.helper.StringHelper;
@XmlRootElement(name = "StringListResult")
@XmlAccessorType(XmlAccessType.NONE)
public class StringListResult {
@XmlAttribute(name = "msg")
private String msg;
@XmlElement(name = "data")
private List<String> data;
public StringListResult() {
this.msg = StringHelper.DASH;
}
public StringListResult(List<String> data) {
this.msg = StringHelper.DASH;
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<String> getData() {
return data;
}
public void setData(List<String> data) {
this.data = data;
}
}

View File

@ -19,39 +19,22 @@ import java.util.Date;
import java.util.Locale;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import li.strolch.privilege.model.Certificate;
import li.strolch.utils.iso8601.ISO8601FormatFactory;
@XmlRootElement(name = "UserSession")
@XmlAccessorType(XmlAccessType.NONE)
public class UserSession {
@XmlAttribute(name = "sessionId")
private String sessionId;
@XmlAttribute(name = "loginTime")
private Date loginTime;
@XmlAttribute(name = "username")
private String username;
@XmlAttribute(name = "firstname")
private String firstname;
@XmlAttribute(name = "lastname")
private String lastname;
@XmlElement(name = "roles")
private Set<String> userRoles;
@XmlAttribute(name = "locale")
private Locale locale;
@XmlAttribute(name = "lastAccess")
private Date lastAccess;
public UserSession() {
// no-arg constructor for JAXB
}
public UserSession(Certificate certificate) {
this.sessionId = certificate.getSessionId();
this.loginTime = certificate.getLoginTime();
@ -94,4 +77,25 @@ public class UserSession {
public Set<String> getUserRoles() {
return userRoles;
}
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("sessionId", this.sessionId);
jsonObject.addProperty("loginTime", ISO8601FormatFactory.getInstance().formatDate(this.loginTime));
jsonObject.addProperty("username", this.username);
jsonObject.addProperty("firstname", this.firstname);
jsonObject.addProperty("lastname", this.lastname);
jsonObject.addProperty("locale", this.locale.toString());
jsonObject.addProperty("lastAccess", ISO8601FormatFactory.getInstance().formatDate(this.lastAccess));
JsonArray rolesJ = new JsonArray();
for (String role : this.userRoles) {
rolesJ.add(role);
}
jsonObject.add("roles", rolesJ);
return jsonObject;
}
}

View File

@ -15,38 +15,41 @@
*/
package li.strolch.rest.model.visitor;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import li.strolch.model.audit.AccessType;
import li.strolch.model.audit.ActionSelection;
import li.strolch.model.audit.Audit;
import li.strolch.rest.model.ActionSelection;
import li.strolch.rest.model.AuditQuery;
import li.strolch.rest.model.DateRange;
import li.strolch.rest.model.IdentitySelection;
import li.strolch.model.audit.AuditQuery;
import li.strolch.rest.model.AuditQueryData;
import li.strolch.utils.StringMatchMode;
import li.strolch.utils.collections.DateRange;
import li.strolch.utils.helper.StringHelper;
import li.strolch.utils.iso8601.ISO8601FormatFactory;
public class ToAuditQueryVisitor {
public li.strolch.model.audit.AuditQuery<Audit> create(AuditQuery query) {
public li.strolch.model.audit.AuditQuery<Audit> create(AuditQueryData query) {
// validate element type
String elementType = query.getElementType();
if (StringHelper.isEmpty(elementType)) {
throw new IllegalArgumentException("elementType on AuditQuery is empty!");
throw new IllegalArgumentException("elementType on AuditQueryData is empty!");
}
// validate date range
DateRange dateRange = query.getDateRange();
if (dateRange == null || dateRange.getFromDate() == null || dateRange.getToDate() == null) {
throw new IllegalArgumentException("DateRange on AuditQuery is not valid or is missing!");
if (query.getFromDate() == null || query.getToDate() == null) {
throw new IllegalArgumentException("fromDate or toDate must be set!");
}
li.strolch.utils.collections.DateRange dr = new li.strolch.utils.collections.DateRange().from(
dateRange.getFromDate(), dateRange.isFromInclusive()).to(dateRange.getToDate(),
dateRange.isToInclusive());
Date fromDate = ISO8601FormatFactory.getInstance().parseDate(query.getFromDate());
Date toDate = ISO8601FormatFactory.getInstance().parseDate(query.getToDate());
DateRange dr = new DateRange().from(fromDate, true).to(toDate, false);
// create query
li.strolch.model.audit.AuditQuery<Audit> auditQuery = li.strolch.model.audit.AuditQuery.query(elementType, dr);
AuditQuery<Audit> auditQuery = AuditQuery.query(elementType, dr);
// limit
auditQuery.limit(query.getLimit());
@ -62,31 +65,26 @@ public class ToAuditQueryVisitor {
}
// action
ActionSelection action = query.getAction();
if (action != null) {
String actionS = action.getAction();
li.strolch.model.audit.ActionSelection actionSelection = auditQuery.action();
if (StringHelper.isNotEmpty(actionS))
actionSelection.actions(StringMatchMode.ci(), actionS);
List<AccessType> accessTypes = action.getAccessTypes();
if (accessTypes != null && !accessTypes.isEmpty()) {
AccessType[] accessTypesArr = new AccessType[accessTypes.size()];
accessTypes.toArray(accessTypesArr);
actionSelection.accessTypes(accessTypesArr);
}
String actionS = query.getAction();
ActionSelection actionSelection = auditQuery.action();
if (StringHelper.isNotEmpty(actionS))
actionSelection.actions(StringMatchMode.ci(), actionS);
String accessTypesS = query.getAccessTypes();
if (StringHelper.isNotEmpty(accessTypesS)) {
String[] accessTypes = accessTypesS.split("\\|");
List<AccessType> accessTypeList = Arrays.stream(accessTypes).map(AccessType::valueOf)
.collect(Collectors.toList());
actionSelection.accessTypes(accessTypeList);
}
// identity
IdentitySelection identity = query.getIdentity();
if (identity != null) {
li.strolch.model.audit.IdentitySelection identitySelection = auditQuery.identity();
if (StringHelper.isNotEmpty(identity.getFirstname()))
identitySelection.firstnames(StringMatchMode.ci(), identity.getFirstname());
if (StringHelper.isNotEmpty(identity.getLastname()))
identitySelection.lastnames(StringMatchMode.ci(), identity.getLastname());
if (StringHelper.isNotEmpty(identity.getUsername()))
identitySelection.usernames(StringMatchMode.ci(), identity.getUsername());
}
li.strolch.model.audit.IdentitySelection identitySelection = auditQuery.identity();
if (StringHelper.isNotEmpty(query.getFirstname()))
identitySelection.firstnames(StringMatchMode.ci(), query.getFirstname());
if (StringHelper.isNotEmpty(query.getLastname()))
identitySelection.lastnames(StringMatchMode.ci(), query.getLastname());
if (StringHelper.isNotEmpty(query.getUsername()))
identitySelection.usernames(StringMatchMode.ci(), query.getUsername());
return auditQuery;
}

View File

@ -15,15 +15,27 @@
*/
package li.strolch.rest.inspector.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Base64;
import java.util.Collections;
import java.util.logging.Level;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Application;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import li.strolch.rest.StrolchRestfulClasses;
import li.strolch.rest.endpoint.Inspector;
import li.strolch.rest.filters.AuthenticationRequestFilter;
import li.strolch.testbase.runtime.RuntimeMock;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.grizzly2.servlet.GrizzlyWebContainerFactory;
@ -43,16 +55,14 @@ import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import li.strolch.rest.StrolchRestfulClasses;
import li.strolch.rest.endpoint.Inspector;
import li.strolch.testbase.runtime.RuntimeMock;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@SuppressWarnings("nls")
public abstract class AbstractRestfulTest extends JerseyTest {
public static final String AUTHENTICATION_PATH = "strolch/authentication";
protected static final Logger logger = LoggerFactory.getLogger(AbstractRestfulTest.class);
private static final String RUNTIME_PATH = "target/withPrivilegeRuntime/"; //$NON-NLS-1$
private static final String CONFIG_SRC = "src/test/resources/withPrivilegeRuntime"; //$NON-NLS-1$
@ -80,6 +90,48 @@ public abstract class AbstractRestfulTest extends JerseyTest {
return createApp();
}
protected String authenticate() {
return authenticate("jill", "jill");
}
protected void logout(String authToken) {
logout("jill", authToken);
}
protected String authenticate(String username, String password) {
// login
JsonObject login = new JsonObject();
login.addProperty("username", username);
login.addProperty("password", Base64.getEncoder().encodeToString(username.getBytes()));
Entity<String> entity = Entity.entity(login.toString(), MediaType.APPLICATION_JSON);
Response result = target() //
.path(AUTHENTICATION_PATH) //
.request(MediaType.APPLICATION_JSON) //
.post(entity);
assertEquals(Response.Status.OK.getStatusCode(), result.getStatus());
JsonObject loginResult = new JsonParser().parse(result.readEntity(String.class)).getAsJsonObject();
assertEquals("jill", loginResult.get("username").getAsString());
assertEquals(64, loginResult.get("authToken").getAsString().length());
assertNull(loginResult.get("msg"));
return loginResult.get("authToken").getAsString();
}
protected void logout(String username, String authToken) {
Response result = target() //
.path(AUTHENTICATION_PATH + "/" + authToken) //
.request(MediaType.APPLICATION_JSON) //
.delete();
assertEquals(Response.Status.OK.getStatusCode(), result.getStatus());
JsonObject logoutResult = new JsonParser().parse(result.readEntity(String.class)).getAsJsonObject();
assertEquals("jill has been logged out.", logoutResult.get("msg").getAsString());
}
public static ResourceConfig createApp() {
ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.setApplicationName("RestTest");
@ -122,8 +174,10 @@ public abstract class AbstractRestfulTest extends JerseyTest {
@Override
public void start() {
try {
this.server = GrizzlyWebContainerFactory.create(baseUri, Collections.singletonMap(
"jersey.config.server.provider.packages", Inspector.class.getPackage().getName()));
this.server = GrizzlyWebContainerFactory.create(baseUri, Collections
.singletonMap("jersey.config.server.provider.packages",
Inspector.class.getPackage().getName() + ";"
+ AuthenticationRequestFilter.class.getPackage().getName()));
} catch (ProcessingException e) {
throw new TestContainerException(e);
} catch (IOException e) {

View File

@ -16,20 +16,15 @@
package li.strolch.rest.inspector.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Base64;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.junit.Test;
import java.util.Base64;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.Test;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
@ -37,33 +32,10 @@ import com.google.gson.JsonParser;
@SuppressWarnings("nls")
public class AuthenticationTest extends AbstractRestfulTest {
private static final String ROOT_PATH = "strolch/authentication";
@Test
public void shouldAuthenticate() {
// login
JsonObject login = new JsonObject();
login.addProperty("username", "jill");
login.addProperty("password", Base64.getEncoder().encodeToString("jill".getBytes()));
Entity<String> entity = Entity.entity(login.toString(), MediaType.APPLICATION_JSON);
Response result = target().path(ROOT_PATH).request(MediaType.APPLICATION_JSON).post(entity);
assertEquals(Status.OK.getStatusCode(), result.getStatus());
JsonObject loginResult = new JsonParser().parse(result.readEntity(String.class)).getAsJsonObject();
assertNotNull(loginResult);
assertEquals("jill", loginResult.get("username").getAsString());
assertEquals(64, loginResult.get("authToken").getAsString().length());
assertNull(loginResult.get("msg"));
// logout
result = target().path(ROOT_PATH + "/" + loginResult.get("authToken").getAsString())
.request(MediaType.APPLICATION_JSON).delete();
assertEquals(Status.OK.getStatusCode(), result.getStatus());
assertNotNull(loginResult);
JsonObject logoutResult = new JsonParser().parse(result.readEntity(String.class)).getAsJsonObject();
assertNotNull(logoutResult);
assertEquals("jill has been logged out.", logoutResult.get("msg").getAsString());
String authToken = authenticate("jill", "jill");
logout("jill", authToken);
}
@Test
@ -75,29 +47,15 @@ public class AuthenticationTest extends AbstractRestfulTest {
login.addProperty("password", Base64.getEncoder().encodeToString("blabla".getBytes()));
Entity<String> entity = Entity.entity(login.toString(), MediaType.APPLICATION_JSON);
Response result = target().path(ROOT_PATH).request(MediaType.APPLICATION_JSON).post(entity);
Response result = target().path(AUTHENTICATION_PATH).request(MediaType.APPLICATION_JSON).post(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), result.getStatus());
}
@Test
public void shouldFailLogoutIllegalSession() {
// login
JsonObject login = new JsonObject();
login.addProperty("username", "jill");
login.addProperty("password", Base64.getEncoder().encodeToString("jill".getBytes()));
Entity<String> entity = Entity.entity(login.toString(), MediaType.APPLICATION_JSON);
Response result = target().path(ROOT_PATH).request(MediaType.APPLICATION_JSON).post(entity);
assertEquals(Status.OK.getStatusCode(), result.getStatus());
JsonObject loginResult = new JsonParser().parse(result.readEntity(String.class)).getAsJsonObject();
assertNotNull(loginResult);
assertEquals("jill", loginResult.get("username").getAsString());
assertEquals(64, loginResult.get("authToken").getAsString().length());
assertNull(loginResult.get("msg"));
// logout
result = target().path(ROOT_PATH + "/blabla").request(MediaType.APPLICATION_JSON).delete();
Response result = target().path(AUTHENTICATION_PATH + "/blabla").request(MediaType.APPLICATION_JSON).delete();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), result.getStatus());
}
}

View File

@ -18,64 +18,90 @@ package li.strolch.rest.inspector.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.Locale;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import java.util.Locale;
import li.strolch.runtime.query.enums.StrolchEnum;
import org.junit.Ignore;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@Ignore
@SuppressWarnings("nls")
public class EnumTest extends AbstractRestfulTest {
private static final String ROOT_PATH = "strolch/enums";
private String authToken;
@Before
public void before() {
this.authToken = authenticate();
}
@After
public void after() {
if (this.authToken != null)
logout(this.authToken);
}
@Test
public void shouldQuerySex() {
// query
Response result = target().path(ROOT_PATH + "/sex").request(MediaType.APPLICATION_JSON)
.acceptLanguage(Locale.ENGLISH).get();
Response result = target() //
.path(ROOT_PATH + "/sex") //
.request(MediaType.APPLICATION_JSON) //
.header(HttpHeaders.AUTHORIZATION, this.authToken) //
.acceptLanguage(Locale.ENGLISH) //
.get();
assertEquals(Status.OK.getStatusCode(), result.getStatus());
StrolchEnum strolchEnum = result.readEntity(StrolchEnum.class);
assertNotNull(strolchEnum);
assertEquals("sex", strolchEnum.getName());
assertEquals(4, strolchEnum.getValues().size());
String strolchEnumS = result.readEntity(String.class);
assertNotNull(strolchEnumS);
JsonObject strolchEnumJ = new JsonParser().parse(strolchEnumS).getAsJsonObject();
assertEquals("sex", strolchEnumJ.get("name").getAsString());
assertEquals(4, strolchEnumJ.get("values").getAsJsonObject().size());
}
@Test
public void shouldQuerySalutation() {
// query
Response result = target().path(ROOT_PATH + "/salutation").request(MediaType.APPLICATION_JSON)
.acceptLanguage(Locale.ENGLISH).get();
Response result = target() //
.path(ROOT_PATH + "/salutation") //
.request(MediaType.APPLICATION_JSON) //
.header(HttpHeaders.AUTHORIZATION, this.authToken) //
.acceptLanguage(Locale.ENGLISH) //
.get();
assertEquals(Status.OK.getStatusCode(), result.getStatus());
StrolchEnum strolchEnum = result.readEntity(StrolchEnum.class);
assertNotNull(strolchEnum);
assertEquals("salutation", strolchEnum.getName());
assertEquals(3, strolchEnum.getValues().size());
assertEquals("Mrs", strolchEnum.getValue("mrs"));
String strolchEnumS = result.readEntity(String.class);
assertNotNull(strolchEnumS);
JsonObject strolchEnumJ = new JsonParser().parse(strolchEnumS).getAsJsonObject();
assertEquals("salutation", strolchEnumJ.get("name").getAsString());
assertEquals(3, strolchEnumJ.get("values").getAsJsonObject().size());
assertEquals("Mrs", strolchEnumJ.get("values").getAsJsonObject().get("mrs").getAsString());
}
@Test
public void shouldQueryGermanSalutation() {
// query
Response result = target().path(ROOT_PATH + "/salutation").request(MediaType.APPLICATION_JSON)
.acceptLanguage(Locale.GERMAN).get();
Response result = target() //
.path(ROOT_PATH + "/salutation") //
.request(MediaType.APPLICATION_JSON) //
.header(HttpHeaders.AUTHORIZATION, this.authToken) //
.acceptLanguage(Locale.GERMAN) //
.get();
assertEquals(Status.OK.getStatusCode(), result.getStatus());
StrolchEnum strolchEnum = result.readEntity(StrolchEnum.class);
assertNotNull(strolchEnum);
assertEquals("salutation", strolchEnum.getName());
assertEquals(3, strolchEnum.getValues().size());
assertEquals("Frau", strolchEnum.getValue("mrs"));
String strolchEnumS = result.readEntity(String.class);
assertNotNull(strolchEnumS);
JsonObject strolchEnumJ = new JsonParser().parse(strolchEnumS).getAsJsonObject();
assertEquals("salutation", strolchEnumJ.get("name").getAsString());
assertEquals(3, strolchEnumJ.get("values").getAsJsonObject().size());
assertEquals("Frau", strolchEnumJ.get("values").getAsJsonObject().get("mrs").getAsString());
}
}

View File

@ -17,52 +17,70 @@ package li.strolch.rest.inspector.test;
import static org.junit.Assert.assertEquals;
import java.util.List;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import li.strolch.agent.api.AgentVersion;
import li.strolch.agent.api.ComponentVersion;
import li.strolch.agent.api.VersionQueryResult;
import org.junit.Ignore;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@Ignore
@SuppressWarnings("nls")
public class VersionQueryTest extends AbstractRestfulTest {
private static final String ROOT_PATH = "strolch/version";
private String authToken;
@Before
public void before() {
this.authToken = authenticate();
}
@After
public void after() {
if (this.authToken != null)
logout(this.authToken);
}
@Test
public void shouldQueryVersion() {
// query
Response result = target().path(ROOT_PATH).request(MediaType.APPLICATION_JSON).get();
Response result = target() //
.path(ROOT_PATH) //
.request(MediaType.APPLICATION_JSON) //
.header(HttpHeaders.AUTHORIZATION, this.authToken) //
.get();
assertEquals(Status.OK.getStatusCode(), result.getStatus());
VersionQueryResult versionQueryResult = result.readEntity(VersionQueryResult.class);
if (versionQueryResult.hasErrors()) {
for (String error : versionQueryResult.getErrors()) {
logger.error(error);
String versionQueryResultS = result.readEntity(String.class);
JsonObject versionQueryResultJ = new JsonParser().parse(versionQueryResultS).getAsJsonObject();
if (versionQueryResultJ.has("errors")) {
JsonArray errorsJ = versionQueryResultJ.get("errors").getAsJsonArray();
for (JsonElement errorJ : errorsJ) {
logger.error(errorJ.getAsString());
}
}
AgentVersion agentVersion = versionQueryResult.getAgentVersion();
logger.info(agentVersion.toString());
List<ComponentVersion> componentVersions = versionQueryResult.getComponentVersions();
assertEquals(6, componentVersions.size());
for (ComponentVersion version : componentVersions) {
logger.info(version.toString());
assertEquals("li.strolch", agentVersion.getGroupId());
}
JsonObject agentVersionJ = versionQueryResultJ.get("agentVersion").getAsJsonObject();
assertEquals("StrolchPersistenceTest", agentVersionJ.get("agentName").getAsString());
assertEquals("li.strolch", agentVersionJ.get("groupId").getAsString());
assertEquals("li.strolch.agent", agentVersionJ.get("artifactId").getAsString());
assertEquals("StrolchPersistenceTest", agentVersion.getAgentName());
assertEquals("li.strolch", agentVersion.getGroupId());
assertEquals("li.strolch.agent", agentVersion.getArtifactId());
JsonArray componentVersionsJ = versionQueryResultJ.get("componentVersions").getAsJsonArray();
assertEquals(6, componentVersionsJ.size());
for (JsonElement element : componentVersionsJ) {
JsonObject componentVersionJ = element.getAsJsonObject();
assertEquals("li.strolch", componentVersionJ.get("groupId").getAsString());
}
}
}

View File

@ -1,4 +1,4 @@
package li.strolch.rest.util;
package li.strolch.service;
import com.google.gson.JsonElement;

View File

@ -1,4 +1,4 @@
package li.strolch.rest.util;
package li.strolch.service;
import com.google.gson.JsonElement;

View File

@ -18,8 +18,6 @@ package li.strolch.service.executor;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import li.strolch.agent.api.ComponentContainer;
import li.strolch.agent.api.StrolchComponent;
@ -30,20 +28,15 @@ import li.strolch.service.api.Service;
import li.strolch.service.api.ServiceArgument;
import li.strolch.service.api.ServiceHandler;
import li.strolch.service.api.ServiceResult;
import li.strolch.utils.helper.ExceptionHelper;
/**
* The {@link ServiceExecutionHandler} is used to perform long running services so that no singletons etc. are required.
*
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class ServiceExecutionHandler extends StrolchComponent {
private Map<String, ServiceExecutionStatus> serviceContextMap;
private BlockingQueue<ServiceContext<? extends ServiceArgument, ? extends ServiceResult>> queue;
private Thread thread;
private volatile boolean interrupted;
public ServiceExecutionHandler(ComponentContainer container, String componentName) {
super(container, componentName);
@ -53,29 +46,10 @@ public class ServiceExecutionHandler extends StrolchComponent {
public void initialize(ComponentConfiguration configuration) throws Exception {
this.serviceContextMap = Collections.synchronizedMap(new HashMap<>());
this.queue = new LinkedBlockingQueue<>();
this.thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (!interrupted) {
doService(queue.take());
}
} catch (InterruptedException ex) {
logger.error(ExceptionHelper.formatExceptionMessage(ex));
}
}
}, "ServiceExecutor");
this.thread.setDaemon(true);
super.initialize(configuration);
}
private <T extends ServiceArgument, U extends ServiceResult> void doService(ServiceContext<T, U> svcCtx) {
if (this.interrupted)
return;
String serviceName = svcCtx.service.getClass().getName();
ServiceExecutionStatus status = this.serviceContextMap.get(serviceName);
status.started();
@ -84,33 +58,6 @@ public class ServiceExecutionHandler extends StrolchComponent {
status.setResult(svcResult);
}
@Override
public void start() throws Exception {
this.thread.start();
super.start();
}
@Override
public void stop() throws Exception {
if (this.thread != null) {
this.thread.interrupt();
try {
this.thread.join(2000l);
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
}
super.stop();
}
@Override
public void destroy() throws Exception {
this.thread = null;
super.destroy();
}
public ServiceExecutionStatus getStatus(Class<?> clazz) {
ServiceExecutionStatus status = this.serviceContextMap.get(clazz.getName());
if (status == null)
@ -134,8 +81,10 @@ public class ServiceExecutionHandler extends StrolchComponent {
try {
ServiceExecutionStatus status = new ServiceExecutionStatus(serviceName);
this.serviceContextMap.put(serviceName, status);
this.queue.put(svcCtx);
Thread.sleep(20l);
getExecutorService().execute(() -> doService(svcCtx));
Thread.sleep(20L);
return status;
} catch (InterruptedException e) {
this.serviceContextMap.remove(serviceName);

View File

@ -15,19 +15,12 @@
*/
package li.strolch.service.executor;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import li.strolch.service.api.ServiceResult;
import li.strolch.utils.helper.StringHelper;
/**
* @author Robert von Burg <eitch@eitchnet.ch>
*/
@XmlRootElement(name = "ServiceExecutionStatus")
@XmlAccessorType(XmlAccessType.NONE)
public class ServiceExecutionStatus {
private String serviceName;
@ -42,7 +35,6 @@ public class ServiceExecutionStatus {
this.serviceName = serviceName;
}
@XmlAttribute(name = "serviceName")
public String getServiceName() {
return serviceName;
}
@ -55,7 +47,6 @@ public class ServiceExecutionStatus {
this.result = svcResult;
}
@XmlAttribute(name = "msg")
public String getMsg() {
if (this.result == null)
return StringHelper.DASH;
@ -64,19 +55,16 @@ public class ServiceExecutionStatus {
return this.result.getMessage();
}
@XmlAttribute(name = "state")
public String getState() {
if (this.result == null)
return StringHelper.DASH;
return this.result.getState().name();
}
@XmlAttribute(name = "done")
public boolean isDone() {
return this.result != null;
}
@XmlAttribute(name = "started")
public synchronized boolean isStarted() {
return started;
}

View File

@ -21,37 +21,17 @@
*/
package li.strolch.communication;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author Robert von Burg &lt;eitch@eitchnet.ch&gt;
*/
@XmlRootElement(name = "ConnectionInfo")
@XmlAccessorType(XmlAccessType.FIELD)
public class ConnectionInfo {
@XmlAttribute(name = "id")
private String id;
@XmlAttribute(name = "localUri")
private String localUri;
@XmlAttribute(name = "remoteUri")
private String remoteUri;
@XmlAttribute(name = "mode")
private ConnectionMode mode;
@XmlAttribute(name = "queueSize")
private int queueSize;
@XmlAttribute(name = "state")
private ConnectionState state;
@XmlAttribute(name = "stateMsg")
private String stateMsg;
/**
@ -62,8 +42,7 @@ public class ConnectionInfo {
}
/**
* @param id
* the id to set
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
@ -77,8 +56,7 @@ public class ConnectionInfo {
}
/**
* @param localUri
* the localUri to set
* @param localUri the localUri to set
*/
public void setLocalUri(String localUri) {
this.localUri = localUri;
@ -92,8 +70,7 @@ public class ConnectionInfo {
}
/**
* @param remoteUri
* the remoteUri to set
* @param remoteUri the remoteUri to set
*/
public void setRemoteUri(String remoteUri) {
this.remoteUri = remoteUri;
@ -107,8 +84,7 @@ public class ConnectionInfo {
}
/**
* @param mode
* the mode to set
* @param mode the mode to set
*/
public void setMode(ConnectionMode mode) {
this.mode = mode;
@ -122,8 +98,7 @@ public class ConnectionInfo {
}
/**
* @param state
* the state to set
* @param state the state to set
*/
public void setState(ConnectionState state) {
this.state = state;
@ -137,8 +112,7 @@ public class ConnectionInfo {
}
/**
* @param stateMsg
* the stateMsg to set
* @param stateMsg the stateMsg to set
*/
public void setStateMsg(String stateMsg) {
this.stateMsg = stateMsg;
@ -152,8 +126,7 @@ public class ConnectionInfo {
}
/**
* @param queueSize
* the queueSize to set
* @param queueSize the queueSize to set
*/
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;

View File

@ -1,73 +0,0 @@
package li.strolch.utils.xml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.XmlAttribute;
public class XmlKeyValue {
@XmlAttribute(name = "key")
private String key;
@XmlAttribute(name = "value")
private String value;
public XmlKeyValue(String key, String value) {
this.key = key;
this.value = value;
}
public XmlKeyValue() {
// no-arg constructor for JAXB
}
/**
* @return the key
*/
public String getKey() {
return this.key;
}
/**
* @param key
* the key to set
*/
public void setKey(String key) {
this.key = key;
}
/**
* @return the value
*/
public String getValue() {
return this.value;
}
/**
* @param value
* the value to set
*/
public void setValue(String value) {
this.value = value;
}
public static List<XmlKeyValue> valueOf(Map<String, String> map) {
List<XmlKeyValue> keyValues = new ArrayList<>(map.size());
for (Entry<String, String> entry : map.entrySet()) {
keyValues.add(new XmlKeyValue(entry.getKey(), entry.getValue()));
}
return keyValues;
}
public static Map<String, String> toMap(List<XmlKeyValue> values) {
Map<String, String> propertyMap = new HashMap<>(values.size());
for (XmlKeyValue xmlKeyValue : values) {
propertyMap.put(xmlKeyValue.getKey(), xmlKeyValue.getValue());
}
return propertyMap;
}
}