Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Improved JS API rendering, implemented some of tenant detail page

Christian Bauer9f11ee7a295d
diff --git a/container/build.gradle b/container/build.gradle
index d7f35eeb5..2451c1522 100644
--- a/container/build.gradle
+++ b/container/build.gradle
@@ -19,7 +19,6 @@ dependencies {
compile "org.jboss.resteasy:resteasy-multipart-provider:$resteasyVersion"
compile "org.jboss.resteasy:resteasy-cache-core:$resteasyVersion"
compile "org.jboss.resteasy:async-http-servlet-3.0:$resteasyVersion"
- compile "org.jboss.resteasy:resteasy-jsapi:$resteasyVersion"
compile "org.keycloak:keycloak-client-registration-api:$keycloakVersion"
compile "org.keycloak:keycloak-undertow-adapter:$keycloakVersion"
diff --git a/container/src/main/java/org/openremote/container/security/KeycloakResource.java b/container/src/main/java/org/openremote/container/security/KeycloakResource.java
index b6aa0fad7..58ccf8da7 100644
--- a/container/src/main/java/org/openremote/container/security/KeycloakResource.java
+++ b/container/src/main/java/org/openremote/container/security/KeycloakResource.java
@@ -19,7 +19,6 @@
*/
package org.openremote.container.security;
-import org.jboss.resteasy.annotations.Form;
import org.keycloak.representations.AccessTokenResponse;
import javax.ws.rs.*;
@@ -40,7 +39,7 @@ public interface KeycloakResource {
@Path("realms/{realm}/protocol/openid-connect/token")
@Consumes(APPLICATION_FORM_URLENCODED)
@Produces(APPLICATION_JSON)
- AccessTokenResponse getAccessToken(@PathParam("realm") String realm, @Form AuthForm authForm);
+ AccessTokenResponse getAccessToken(@PathParam("realm") String realm, @BeanParam AuthForm authForm);
@GET
@Path("realms/{realm}/clients-registrations/install/{clientId}")
diff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.java
index 91dcff713..ab1c89bbf 100644
--- a/container/src/main/java/org/openremote/container/web/WebService.java
+++ b/container/src/main/java/org/openremote/container/web/WebService.java
@@ -30,7 +30,6 @@ import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.*;
import io.undertow.util.HttpString;
import io.undertow.util.MimeMappings;
-import org.jboss.resteasy.jsapi.JSAPIServlet;
import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher;
import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
import org.jboss.resteasy.spi.ResteasyDeployment;
@@ -42,6 +41,7 @@ import org.openremote.container.json.ElementalMessageBodyConverter;
import org.openremote.container.json.JacksonConfig;
import org.openremote.container.security.AuthOverloadHandler;
import org.openremote.container.security.SimpleKeycloakServletExtension;
+import org.openremote.container.web.jsapi.JSAPIServlet;
import java.net.URI;
import java.nio.file.Files;
diff --git a/container/src/main/java/org/openremote/container/web/jsapi/JSAPIServlet.java b/container/src/main/java/org/openremote/container/web/jsapi/JSAPIServlet.java
new file mode 100644
index 000000000..3ca220791
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/jsapi/JSAPIServlet.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright 2016 Red Hat, Inc. and/or its affiliates
+ * and other contributors as indicated by the @author tags.
+ *
+ * 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 org.openremote.container.web.jsapi;
+
+import org.jboss.resteasy.core.ResourceMethodRegistry;
+import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters;
+import org.jboss.resteasy.spi.ResteasyDeployment;
+import org.jboss.resteasy.spi.ResteasyProviderFactory;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+/**
+ * @author Stéphane Épardaud <[email protected]>
+ */
+public class JSAPIServlet extends HttpServlet {
+
+ private static final Logger LOG = Logger.getLogger(JSAPIServlet.class.getName());
+
+ //corresponding to RFC 4329 this is the right MEDIA_TYPE
+ private static final String JS_MEDIA_TYPE = "application/javascript";
+
+ private static final long serialVersionUID = -1985015444704126795L;
+
+ private Map<String, ServiceRegistry> services;
+
+ private JSAPIWriter apiWriter = new JSAPIWriter();
+
+ @Override
+ public void init(ServletConfig config) throws ServletException {
+ super.init(config);
+ LOG.fine("Loading JS API servlet");
+ try {
+ scanResources();
+ } catch (Exception e) {
+ throw new ServletException(e);
+ }
+
+ LOG.fine("JS API servlet loaded");
+
+ // make it possible to get to us for rescanning
+ ServletContext servletContext = config.getServletContext();
+ servletContext.setAttribute(getClass().getName(), this);
+ }
+
+ @Override
+ protected void service(HttpServletRequest req, HttpServletResponse resp)
+ throws ServletException, IOException {
+ String pathInfo = req.getPathInfo();
+ String uri = req.getRequestURL().toString();
+ uri = uri.substring(0, uri.length() - req.getServletPath().length());
+ if (LOG.isLoggable(Level.FINE)) {
+ LOG.fine("Serving JS API on: " + pathInfo);
+ }
+ if (this.services == null) try {
+ scanResources();
+ } catch (Exception e) {
+ resp.sendError(503, "No Resteasy deployments found"); // FIXME should return internal error
+ }
+
+ if (this.services == null) {
+ resp.sendError(503, "No Resteasy deployments found");
+ }
+ resp.setContentType(JS_MEDIA_TYPE);
+ this.apiWriter.writeJavaScript(uri, req, resp, services);
+
+ }
+
+ public void scanResources() throws Exception {
+
+ ServletConfig config = getServletConfig();
+ ServletContext servletContext = config.getServletContext();
+ Map<String, ResteasyDeployment> deployments = (Map<String, ResteasyDeployment>) servletContext.getAttribute(ResteasyContextParameters.RESTEASY_DEPLOYMENTS);
+
+ if (deployments == null) return;
+ synchronized (this) {
+ services = new HashMap<String, ServiceRegistry>();
+ for (Map.Entry<String, ResteasyDeployment> entry : deployments.entrySet()) {
+ ResourceMethodRegistry registry = (ResourceMethodRegistry) entry.getValue().getRegistry();
+ ResteasyProviderFactory providerFactory =
+ (ResteasyProviderFactory) entry.getValue().getProviderFactory();
+ ServiceRegistry service = new ServiceRegistry(null, registry, providerFactory, null);
+ services.put(entry.getKey(), service);
+ }
+ }
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/jsapi/JSAPIWriter.java b/container/src/main/java/org/openremote/container/web/jsapi/JSAPIWriter.java
new file mode 100644
index 000000000..473a88e42
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/jsapi/JSAPIWriter.java
@@ -0,0 +1,304 @@
+/*
+ * Copyright 2016 Red Hat, Inc. and/or its affiliates
+ * and other contributors as indicated by the @author tags.
+ *
+ * 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 org.openremote.container.web.jsapi;
+
+import org.jboss.resteasy.util.PathHelper;
+
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.zip.GZIPOutputStream;
+
+/**
+ * @author Stéphane Épardaud <[email protected]>
+ */
+public class JSAPIWriter {
+
+ private static final Logger LOG = Logger.getLogger(JSAPIWriter.class.getName());
+
+ private static final long serialVersionUID = -1985015444704126795L;
+
+ public void writeJavaScript(String base, HttpServletRequest req, HttpServletResponse resp,
+ Map<String, ServiceRegistry> serviceRegistries) throws IOException {
+ if (LOG.isLoggable(Level.FINE)) {
+ LOG.fine("Starting JS API client");
+ }
+
+ // RESTEASY-776
+ // before writing generated javascript, we generate Etag and compare it with client request.
+ // If nothing changed, we send back 304 Not Modified for client browser to use cached js.
+ String ifNoneMatch = req.getHeader("If-None-Match");
+ String etag = generateEtag(serviceRegistries);
+ resp.setHeader("Etag", etag);
+
+ if (ifNoneMatch != null && ifNoneMatch.equals(etag)) {
+ resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
+ return;
+ }
+
+ for (Map.Entry<String, ServiceRegistry> entry : serviceRegistries.entrySet()) {
+ String uri = base;
+ if (entry.getKey() != null) uri += entry.getKey();
+
+ StringWriter stringWriter = new StringWriter();
+ PrintWriter writer = new PrintWriter(new BufferedWriter(stringWriter));
+ writeJavaScript(uri, writer, entry.getValue());
+ writer.flush();
+ writer.close();
+
+ if (clientIsGzipSupported(req)) {
+ ByteArrayOutputStream compressedContent = new ByteArrayOutputStream();
+ GZIPOutputStream gzipstream = new GZIPOutputStream(compressedContent);
+ gzipstream.write(stringWriter.toString().getBytes());
+ gzipstream.finish();
+
+ // get the compressed content
+ byte[] compressedBytes = compressedContent.toByteArray();
+
+ // set appropriate HTTP headers
+ resp.setContentLength(compressedBytes.length);
+ resp.addHeader("Content-Encoding", "gzip");
+
+ ServletOutputStream output = resp.getOutputStream();
+ output.write(compressedBytes);
+ output.flush();
+ output.close();
+
+ } else {
+ ServletOutputStream output = resp.getOutputStream();
+ byte[] bytes = stringWriter.toString().getBytes();
+ resp.setContentLength(bytes.length);
+ output.write(bytes);
+ output.flush();
+ output.close();
+ }
+ }
+
+ }
+
+ private boolean clientIsGzipSupported(HttpServletRequest req) {
+ String encoding = req.getHeader("Accept-Encoding");
+ return encoding != null && encoding.contains("gzip");
+ }
+
+ public void writeJavaScript(String uri, PrintWriter writer,
+ ServiceRegistry serviceRegistry) throws IOException {
+ copyResource("client.js", writer);
+ writer.println("REST.apiURL = '" + uri + "';");
+ Set<String> declaredPrefixes = new HashSet<String>();
+ printService(writer, serviceRegistry, declaredPrefixes);
+
+ }
+
+
+ private String generateEtag(Map<String, ServiceRegistry> serviceRegistries) {
+ StringBuilder etagBuilder = new StringBuilder();
+ for (Map.Entry<String, ServiceRegistry> entry : serviceRegistries.entrySet()) {
+ if (entry.getKey() != null) etagBuilder.append(entry.getKey()).append(':');
+ generateEtag(entry.getValue(), etagBuilder);
+ }
+ return String.valueOf(Math.abs(etagBuilder.toString().hashCode()));
+ }
+
+ private void generateEtag(ServiceRegistry serviceRegistry, StringBuilder etagBuilder) {
+ for (MethodMetaData methodMetaData : serviceRegistry.getMethodMetaData()) {
+ etagBuilder.append(methodMetaData.hashCode());
+
+ for (ServiceRegistry subService : serviceRegistry.getLocators()) {
+ generateEtag(subService, etagBuilder);
+ }
+
+ }
+ }
+
+ private void printService(PrintWriter writer, ServiceRegistry serviceRegistry, Set<String> declaredPrefixes) {
+
+
+ for (MethodMetaData methodMetaData : serviceRegistry.getMethodMetaData()) {
+ if (LOG.isLoggable(Level.FINE)) {
+ LOG.fine("Generating JS API: " + methodMetaData.getKlass().getName() + "#" + methodMetaData.getUri());
+ }
+ String declaringPrefix = methodMetaData.getFunctionPrefix(); // TODO Add prefix path segment
+ declarePrefix(writer, declaringPrefix, declaredPrefixes);
+
+ for (String httpMethod : methodMetaData.getHttpMethods()) {
+ print(writer, httpMethod, methodMetaData);
+ }
+ }
+ for (ServiceRegistry subService : serviceRegistry.getLocators())
+ printService(writer, subService, declaredPrefixes);
+ }
+
+ private void declarePrefix(PrintWriter writer, String declaringPrefix, Set<String> declaredPrefixes) {
+ if (declaredPrefixes.add(declaringPrefix)) {
+ int lastDot = declaringPrefix.lastIndexOf(".");
+ if (lastDot == -1)
+ writer.println("var " + declaringPrefix + " = {};");
+ else {
+ declarePrefix(writer, declaringPrefix.substring(0, lastDot), declaredPrefixes);
+ writer.println(declaringPrefix + " = {};");
+ }
+ }
+
+ }
+
+ private void copyResource(String name, PrintWriter writer)
+ throws IOException {
+ Reader reader = new InputStreamReader(getClass().getResourceAsStream(name));
+ char[] array = new char[1024];
+ int read;
+ while ((read = reader.read(array)) >= 0) {
+ writer.write(array, 0, read);
+ }
+ reader.close();
+ }
+
+ private void print(PrintWriter writer, String httpMethod, MethodMetaData methodMetaData) {
+ String uri = methodMetaData.getUri();
+ writer.println("// " + httpMethod + " " + uri);
+ writer.println(methodMetaData.getFunctionName() + " = function(_params");
+ printURIParamsSignature(uri, writer);
+ writer.println("){");
+ writer.println(" var params = _params ? _params : {};");
+ writer.println(" var request = new REST.Request();");
+ writer.println(" request.setMethod('" + httpMethod + "');");
+ writer
+ .println(" var uri = params.$apiURL ? params.$apiURL : REST.apiURL;");
+ if (uri.contains("{")) {
+ printURIParamCalls(uri, writer);
+ } else {
+ writer.println(" uri += '" + uri + "';");
+ }
+ printOtherParams(methodMetaData, writer);
+ writer.println(" request.setURI(uri);");
+ writer.println(" if(params.$username && params.$password)");
+ writer
+ .println(" request.setCredentials(params.$username, params.$password);");
+ writer.println(" if(params.$accepts)");
+ writer.println(" request.setAccepts(params.$accepts);");
+ if (methodMetaData.getWants() != null) {
+ writer.println(" else");
+ writer.println(" request.setAccepts('" + methodMetaData.getWants()
+ + "');");
+ }
+
+ writer.println("if (REST.antiBrowserCache == true) {");
+ writer.println(" request.addQueryParameter('resteasy_jsapi_anti_cache', (new Date().getTime()));");
+ writer.println(" var cached_obj = REST._get_cache_signature(REST._generate_cache_signature(uri));");
+
+ writer.println(" if (cached_obj != null) { request.addHeader('If-Modified-Since', cached_obj[1]['Last-Modified']); request.addHeader('If-None-Match', cached_obj[1]['Etag']);}");
+
+ writer.println("}");
+
+
+ writer.println(" if(params.$contentType)");
+ writer.println(" request.setContentType(params.$contentType);");
+ writer.println(" else");
+ writer.println(" request.setContentType('"
+ + methodMetaData.getConsumesMIMEType() + "');");
+ writer.println(" if(params.$callback){");
+ writer.println(" request.execute(params.$callback);");
+ writer.println(" }else{");
+ writer.println(" var returnValue;");
+ writer.println(" request.setAsync(false);");
+ writer
+ .println(" var callback = function(httpCode, xmlHttpRequest, value){ returnValue = value;};");
+ writer.println(" request.execute(callback);");
+ writer.println(" return returnValue;");
+ writer.println(" }");
+ writer.println("};");
+ }
+
+ private void printOtherParams(MethodMetaData methodMetaData,
+ PrintWriter writer) {
+ List<MethodParamMetaData> params = methodMetaData.getParameters();
+ for (MethodParamMetaData methodParamMetaData : params) {
+ printParameter(methodParamMetaData, writer);
+ }
+ }
+
+ private void printParameter(MethodParamMetaData metaData,
+ PrintWriter writer) {
+ switch (metaData.getParamType()) {
+ case QUERY_PARAMETER:
+ print(metaData, writer, "QueryParameter");
+ break;
+ case HEADER_PARAMETER:
+ print(metaData, writer, "Header");
+ // FIXME: warn about forbidden headers:
+ // http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method
+ break;
+ case COOKIE_PARAMETER:
+ print(metaData, writer, "Cookie");
+ break;
+ case MATRIX_PARAMETER:
+ print(metaData, writer, "MatrixParameter");
+ break;
+ case FORM_PARAMETER:
+ print(metaData, writer, "FormParameter");
+ break;
+ case FORM:
+ print(metaData, writer, "Form");
+ break;
+ case ENTITY_PARAMETER:
+ // the entity
+ writer.println(" if(params.$entity)");
+ writer.println(" request.setEntity(params.$entity);");
+ break;
+ }
+ }
+
+ private void print(MethodParamMetaData metaData, PrintWriter writer, String type) {
+ String paramName = metaData.getParamName();
+ writer.println(String.format(" if(Object.prototype.hasOwnProperty.call(params, '%s'))\n request.add%s('%s', params.%s);", paramName, type, paramName, paramName));
+ }
+
+ private void printURIParamsSignature(String uri, PrintWriter writer) {
+ String replacedCurlyURI = PathHelper.replaceEnclosedCurlyBraces(uri);
+ Matcher matcher = PathHelper.URI_PARAM_PATTERN.matcher(replacedCurlyURI);
+ while (matcher.find()) {
+ String name = matcher.group(1);
+ writer.println(", " + name);
+ }
+ }
+
+ private void printURIParamCalls(String uri, PrintWriter writer) {
+ String replacedCurlyURI = PathHelper.replaceEnclosedCurlyBraces(uri);
+ Matcher matcher = PathHelper.URI_PARAM_PATTERN.matcher(replacedCurlyURI);
+ int i = 0;
+ while (matcher.find()) {
+ if (matcher.start() > i) {
+ writer.println(" uri += '" + replacedCurlyURI.substring(i, matcher.start()) + "';");
+ }
+ String name = matcher.group(1);
+ writer.println(" uri += REST.Encoding.encodePathSegment(" + name + ");");
+ i = matcher.end();
+ }
+ if (i < replacedCurlyURI.length())
+ writer.println(" uri += '" + replacedCurlyURI.substring(i) + "';");
+ }
+
+}
diff --git a/container/src/main/java/org/openremote/container/web/jsapi/MethodMetaData.java b/container/src/main/java/org/openremote/container/web/jsapi/MethodMetaData.java
new file mode 100644
index 000000000..0d052e643
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/jsapi/MethodMetaData.java
@@ -0,0 +1,278 @@
+/*
+ * Copyright 2016 Red Hat, Inc. and/or its affiliates
+ * and other contributors as indicated by the @author tags.
+ *
+ * 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 org.openremote.container.web.jsapi;
+
+import org.jboss.resteasy.annotations.Form;
+import org.jboss.resteasy.core.ResourceInvoker;
+import org.jboss.resteasy.core.ResourceMethodInvoker;
+import org.jboss.resteasy.spi.metadata.ResourceLocator;
+import org.jboss.resteasy.spi.metadata.ResourceMethod;
+import org.jboss.resteasy.util.FindAnnotation;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Logger;
+
+public class MethodMetaData {
+
+ private static final Logger LOG = Logger.getLogger(MethodMetaData.class.getName());
+
+ private ResourceMethodInvoker invoker;
+ private Method method;
+ private ResourceMethod resourceMethod;
+ private Class<?> klass;
+ private String wants;
+ private String consumesMIMEType;
+ private String uri;
+ private String functionName;
+ private List<MethodParamMetaData> parameters = new ArrayList<MethodParamMetaData>();
+ private Collection<String> httpMethods;
+ private ServiceRegistry registry;
+ private String functionPrefix;
+ private boolean wantsForm;
+
+ public MethodMetaData(ServiceRegistry serviceRegistry, ResourceMethodInvoker invoker) throws Exception {
+ this.registry = serviceRegistry;
+ this.invoker = invoker;
+ this.method = invoker.getMethod();
+
+ this.resourceMethod = (ResourceMethod) getResourceLocator(invoker);
+ this.klass = invoker.getResourceClass();
+
+ String methodPath = resourceMethod.getPath();
+ String klassPath = resourceMethod.getResourceClass().getPath();
+ Produces produces = method.getAnnotation(Produces.class);
+
+ if (produces == null)
+ produces = klass.getAnnotation(Produces.class);
+ this.wants = getWants(produces);
+ Consumes consumes = method.getAnnotation(Consumes.class);
+ if (consumes == null)
+ consumes = klass.getAnnotation(Consumes.class);
+
+
+ this.uri = appendURIFragments(registry, klassPath, methodPath);
+
+ if (serviceRegistry.isRoot())
+ this.functionPrefix = klass.getSimpleName();
+ else
+ this.functionPrefix = serviceRegistry.getFunctionPrefix();
+ this.functionName = this.functionPrefix + "." + method.getName();
+ httpMethods = invoker.getHttpMethods();
+
+ // we need to add all parameters from parent resource locators until the root
+ List<Method> methodsUntilRoot = new ArrayList<Method>();
+ methodsUntilRoot.add(method);
+ serviceRegistry.collectResourceMethodsUntilRoot(methodsUntilRoot);
+ for (Method method : methodsUntilRoot) {
+ Annotation[][] allAnnotations = method.getParameterAnnotations();
+ Class<?>[] parameterTypes = method.getParameterTypes();
+ for (int i = 0; i < parameterTypes.length; i++) {
+ processMetaData(parameterTypes[i], allAnnotations[i], true);
+ }
+ }
+ // this must be after we scan the params in case of @Form
+ this.consumesMIMEType = getConsumes(consumes);
+ if (wantsForm && !"application/x-www-form-urlencoded".equals(consumesMIMEType)) {
+ LOG.warning("Overriding media type with application/x-www-form-urlencoded: " + consumesMIMEType);
+ this.consumesMIMEType = "application/x-www-form-urlencoded";
+ }
+ }
+
+ public static ResourceLocator getResourceLocator(ResourceInvoker invoker) throws Exception {
+ Field resourceMethodField = null;
+ resourceMethodField = invoker.getClass().getDeclaredField("method");
+ resourceMethodField.setAccessible(true);
+ return (ResourceLocator) resourceMethodField.get(invoker);
+ }
+
+ protected void processMetaData(Class<?> type, Annotation[] annotations,
+ boolean useBody) {
+ QueryParam query;
+ HeaderParam header;
+ MatrixParam matrix;
+ PathParam uriParam;
+ CookieParam cookie;
+ FormParam formParam;
+ Form form;
+ BeanParam beanParam;
+
+ // boolean isEncoded = FindAnnotation.findAnnotation(annotations,
+ // Encoded.class) != null;
+
+ if ((query = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null) {
+ addParameter(type, annotations, MethodParamMetaData.MethodParamType.QUERY_PARAMETER, query
+ .value());
+ } else if ((header = FindAnnotation.findAnnotation(annotations,
+ HeaderParam.class)) != null) {
+ addParameter(type, annotations, MethodParamMetaData.MethodParamType.HEADER_PARAMETER,
+ header.value());
+ } else if ((cookie = FindAnnotation.findAnnotation(annotations,
+ CookieParam.class)) != null) {
+ addParameter(type, annotations, MethodParamMetaData.MethodParamType.COOKIE_PARAMETER,
+ cookie.value());
+ } else if ((uriParam = FindAnnotation.findAnnotation(annotations,
+ PathParam.class)) != null) {
+ addParameter(type, annotations, MethodParamMetaData.MethodParamType.PATH_PARAMETER,
+ uriParam.value());
+ } else if ((matrix = FindAnnotation.findAnnotation(annotations,
+ MatrixParam.class)) != null) {
+ addParameter(type, annotations, MethodParamMetaData.MethodParamType.MATRIX_PARAMETER,
+ matrix.value());
+ } else if ((formParam = FindAnnotation.findAnnotation(annotations, FormParam.class)) != null) {
+ addParameter(type, annotations, MethodParamMetaData.MethodParamType.FORM_PARAMETER, formParam.value());
+ this.wantsForm = true;
+ } else if ((form = FindAnnotation.findAnnotation(annotations, Form.class)) != null) {
+ if (type == Map.class || type == List.class) {
+ addParameter(type, annotations, MethodParamMetaData.MethodParamType.FORM, form.prefix());
+ this.wantsForm = true;
+ } else
+ walkForm(type);
+ } else if ((beanParam = FindAnnotation.findAnnotation(annotations, BeanParam.class)) != null) {
+ if (type == Map.class || type == List.class) {
+ addParameter(type, annotations, MethodParamMetaData.MethodParamType.FORM, "");
+ this.wantsForm = true;
+ } else
+ walkForm(type);
+ } else if ((FindAnnotation.findAnnotation(annotations, Context.class)) != null) {
+ // righfully ignore
+ } else if (useBody) {
+ addParameter(type, annotations, MethodParamMetaData.MethodParamType.ENTITY_PARAMETER, null);
+ }
+ }
+
+ private void walkForm(Class<?> type) {
+ for (Field field : type.getDeclaredFields()) {
+ processMetaData(field.getType(), field.getAnnotations(), false);
+ }
+ for (Method method : type.getDeclaredMethods()) {
+ if (method.getParameterTypes().length != 1
+ || !method.getReturnType().equals(Void.class))
+ continue;
+ processMetaData(method.getParameterTypes()[0],
+ method.getAnnotations(), false);
+ }
+ if (type.getSuperclass() != null) {
+ walkForm(type.getSuperclass());
+ }
+ }
+
+ private void addParameter(Class<?> type, Annotation[] annotations,
+ MethodParamMetaData.MethodParamType paramType, String value) {
+ this.parameters.add(new MethodParamMetaData(type, annotations, paramType,
+ value));
+ }
+
+ private String getWants(Produces produces) {
+ if (produces == null)
+ return null;
+ String[] value = produces.value();
+ if (value.length == 0)
+ return null;
+ if (value.length == 1)
+ return value[0];
+ StringBuffer buf = new StringBuffer();
+ for (String mime : produces.value()) {
+ if (buf.length() != 0)
+ buf.append(",");
+ buf.append(mime);
+ }
+ return buf.toString();
+ }
+
+ private String getConsumes(Consumes consumes) {
+ if (consumes == null)
+ return "text/plain";
+ if (consumes.value().length > 0)
+ return consumes.value()[0];
+ return "text/plain";
+ }
+
+ public static String appendURIFragments(ServiceRegistry registry, String classPath, String methodPath) {
+ return appendURIFragments(registry == null ? null : registry.getUri(),
+ notEmpty(classPath) ? classPath : null,
+ notEmpty(methodPath) ? methodPath : null);
+ }
+
+ public static String appendURIFragments(String... fragments) {
+ StringBuilder str = new StringBuilder();
+ for (String fragment : fragments) {
+ if (fragment == null || fragment.length() == 0 || fragment.equals("/"))
+ continue;
+ if (fragment.startsWith("/"))
+ fragment = fragment.substring(1);
+ if (fragment.endsWith("/"))
+ fragment = fragment.substring(0, fragment.length() - 1);
+ str.append('/').append(fragment);
+ }
+ if (str.length() == 0)
+ return "/";
+ return str.toString();
+ }
+
+ public ResourceMethodInvoker getInvoker() {
+ return invoker;
+ }
+
+ public Method getMethod() {
+ return method;
+ }
+
+ public Class<?> getKlass() {
+ return klass;
+ }
+
+ public String getWants() {
+ return wants;
+ }
+
+ public String getConsumesMIMEType() {
+ return consumesMIMEType;
+ }
+
+ public String getUri() {
+ return uri;
+ }
+
+ public String getFunctionName() {
+ return functionName;
+ }
+
+ public List<MethodParamMetaData> getParameters() {
+ return parameters;
+ }
+
+ public Collection<String> getHttpMethods() {
+ return httpMethods;
+ }
+
+
+ private static boolean notEmpty(String string) {
+ return string != null && !string.isEmpty();
+ }
+
+ public String getFunctionPrefix() {
+ return functionPrefix;
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/web/jsapi/MethodParamMetaData.java b/container/src/main/java/org/openremote/container/web/jsapi/MethodParamMetaData.java
new file mode 100644
index 000000000..7c48c3055
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/jsapi/MethodParamMetaData.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2016 Red Hat, Inc. and/or its affiliates
+ * and other contributors as indicated by the @author tags.
+ *
+ * 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 org.openremote.container.web.jsapi;
+
+import java.lang.annotation.Annotation;
+
+public class MethodParamMetaData {
+
+ public static enum MethodParamType {
+ QUERY_PARAMETER, HEADER_PARAMETER, COOKIE_PARAMETER, PATH_PARAMETER, MATRIX_PARAMETER, FORM_PARAMETER, FORM, ENTITY_PARAMETER
+ }
+
+ private Class<?> type;
+ private Annotation[] annotations;
+
+ private MethodParamType paramType;
+ private String paramName;
+
+ public MethodParamMetaData(Class<?> type, Annotation[] annotations,
+ MethodParamType paramType, String paramName) {
+ super();
+ this.type = type;
+ this.annotations = annotations;
+ this.paramType = paramType;
+ this.paramName = paramName;
+ }
+
+ public Class<?> getType() {
+ return type;
+ }
+
+ public void setType(Class<?> type) {
+ this.type = type;
+ }
+
+ public Annotation[] getAnnotations() {
+ return annotations;
+ }
+
+ public void setAnnotations(Annotation[] annotations) {
+ this.annotations = annotations;
+ }
+
+ public MethodParamType getParamType() {
+ return paramType;
+ }
+
+ public void setParamType(MethodParamType paramType) {
+ this.paramType = paramType;
+ }
+
+ public String getParamName() {
+ return paramName;
+ }
+
+ public void setParamName(String paramName) {
+ this.paramName = paramName;
+ }
+
+}
diff --git a/container/src/main/java/org/openremote/container/web/jsapi/ServiceRegistry.java b/container/src/main/java/org/openremote/container/web/jsapi/ServiceRegistry.java
new file mode 100644
index 000000000..41d6e0cfa
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/web/jsapi/ServiceRegistry.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2016 Red Hat, Inc. and/or its affiliates
+ * and other contributors as indicated by the @author tags.
+ *
+ * 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 org.openremote.container.web.jsapi;
+
+import org.jboss.resteasy.core.ResourceInvoker;
+import org.jboss.resteasy.core.ResourceLocatorInvoker;
+import org.jboss.resteasy.core.ResourceMethodInvoker;
+import org.jboss.resteasy.core.ResourceMethodRegistry;
+import org.jboss.resteasy.spi.ResteasyProviderFactory;
+import org.jboss.resteasy.spi.metadata.ResourceLocator;
+import org.jboss.resteasy.util.GetRestful;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.logging.Logger;
+
+/**
+ * @author Stéphane Épardaud <[email protected]>
+ */
+public class ServiceRegistry {
+
+ private static final Logger LOG = Logger.getLogger(ServiceRegistry.class.getName());
+
+ private static final long serialVersionUID = -1985015444704126795L;
+
+ private ResourceMethodRegistry registry;
+
+ private ResteasyProviderFactory providerFactory;
+
+ private ServiceRegistry parent;
+
+ private ArrayList<MethodMetaData> methods;
+
+ private ArrayList<ServiceRegistry> locators;
+
+ private ResourceLocatorInvoker invoker;
+
+ private String uri;
+
+ private String functionPrefix;
+
+ public ServiceRegistry getParent() {
+ return parent;
+ }
+
+ public ServiceRegistry(ServiceRegistry parent, ResourceMethodRegistry registry,
+ ResteasyProviderFactory providerFactory, ResourceLocatorInvoker invoker) throws Exception {
+ this.parent = parent;
+ this.registry = registry;
+ this.providerFactory = providerFactory;
+ this.invoker = invoker;
+ if (invoker != null) {
+ Method method = invoker.getMethod();
+
+ ResourceLocator resourceLocator = MethodMetaData.getResourceLocator(invoker);
+
+ String methodPathVal = resourceLocator.getPath();
+ String classPathVal = resourceLocator.getResourceClass().getPath();
+
+ this.uri = MethodMetaData.appendURIFragments(parent, classPathVal, methodPathVal);
+
+ if (parent.isRoot())
+ this.functionPrefix = method.getDeclaringClass().getSimpleName() + "." + method.getName();
+ else
+ this.functionPrefix = parent.getFunctionPrefix() + "." + method.getName();
+ }
+ scanRegistry();
+ }
+
+ private void scanRegistry() throws Exception {
+ methods = new ArrayList<MethodMetaData>();
+ locators = new ArrayList<ServiceRegistry>();
+ for (Entry<String, List<ResourceInvoker>> entry : registry.getBounded().entrySet()) {
+ List<ResourceInvoker> invokers = entry.getValue();
+ for (ResourceInvoker invoker : invokers) {
+ if (invoker instanceof ResourceMethodInvoker) {
+ methods.add(new MethodMetaData(this, (ResourceMethodInvoker) invoker));
+ } else if (invoker instanceof ResourceLocatorInvoker) {
+ ResourceLocatorInvoker locator = (ResourceLocatorInvoker) invoker;
+ Method method = locator.getMethod();
+ Class<?> locatorType = method.getReturnType();
+ Class<?>[] locatorResourceTypes = GetRestful.getSubResourceClasses(locatorType);
+ for (Class<?> locatorResourceType : locatorResourceTypes) {
+ if (locatorResourceType == null) {
+ // FIXME: we could generate an error for the client, which would be more informative than
+ // just logging this
+ LOG.warning("Error generating JS API: " + method.getDeclaringClass().getName() + ":" + method.getName());
+ // skip this
+ continue;
+ }
+ ResourceMethodRegistry locatorRegistry = new ResourceMethodRegistry(providerFactory);
+ locatorRegistry.addResourceFactory(null, null, locatorResourceType);
+ locators.add(new ServiceRegistry(this, locatorRegistry, providerFactory, locator));
+ }
+ }
+ }
+ }
+ }
+
+
+ public List<MethodMetaData> getMethodMetaData() {
+ return methods;
+ }
+
+ public List<ServiceRegistry> getLocators() {
+ return locators;
+ }
+
+ public String getUri() {
+ return uri;
+ }
+
+ public boolean isRoot() {
+ return parent == null;
+ }
+
+ public String getFunctionPrefix() {
+ return functionPrefix;
+ }
+
+ public void collectResourceMethodsUntilRoot(List<Method> methods) {
+ if (isRoot())
+ return;
+ methods.add(invoker.getMethod());
+ parent.collectResourceMethodsUntilRoot(methods);
+ }
+
+}
diff --git a/container/src/main/resources/org/openremote/container/web/jsapi/client.js b/container/src/main/resources/org/openremote/container/web/jsapi/client.js
new file mode 100644
index 000000000..01fa8da5b
--- /dev/null
+++ b/container/src/main/resources/org/openremote/container/web/jsapi/client.js
@@ -0,0 +1,536 @@
+// namespace
+var REST = {
+ apiURL : null,
+ debug: false,
+ loglevel : 0,
+ antiBrowserCache : false,
+ cacheHeaders : []
+};
+
+// helper function
+REST.getKeys = function (o) {
+ if (o !== Object(o))
+ throw new TypeError('REST.getKeys called on non-object');
+ var ret = [], p;
+ for (p in o) if (Object.prototype.hasOwnProperty.call(o, p)) ret.push(p);
+ return ret;
+};
+
+// constructor
+REST.Request = function (){
+ REST.log("Creating new Request");
+ this.uri = null;
+ this.method = "GET";
+ this.username = null;
+ this.password = null;
+ this.acceptHeader = "*/*";
+ this.contentTypeHeader = null;
+ this.async = true;
+ this.queryParameters = [];
+ this.matrixParameters = [];
+ this.formParameters = [];
+ this.forms = [];
+ this.cookies = [];
+ this.headers = [];
+ this.entity = null;
+}
+
+REST.Request.prototype = {
+ execute : function(callback){
+ var request = new XMLHttpRequest();
+ var url = this.uri;
+
+ if (REST.antiBrowserCache == true) {
+ request.url = url;
+ }
+
+ var restRequest = this;
+ for(var i=0;i<this.matrixParameters.length;i++){
+ url += ";" + REST.Encoding.encodePathParamName(this.matrixParameters[i][0]);
+ url += "=" + REST.Encoding.encodePathParamValue(this.matrixParameters[i][1]);
+ }
+ for(var i=0;i<this.queryParameters.length;i++){
+ if(i == 0)
+ url += "?";
+ else
+ url += "&";
+ url += REST.Encoding.encodeQueryParamNameOrValue(this.queryParameters[i][0]);
+ url += "=" + REST.Encoding.encodeQueryParamNameOrValue(this.queryParameters[i][1]);
+ }
+ for(var i=0;i<this.cookies.length;i++){
+ document.cookie = encodeURI(this.cookies[i][0])
+ + "=" + encodeURI(this.cookies[i][1]);
+ }
+ request.open(this.method, url, this.async, this.username, this.password);
+ var acceptSet = false;
+ var contentTypeSet = false;
+ for(var i=0;i<this.headers.length;i++){
+ if(this.headers[i][0].toLowerCase() == 'accept')
+ acceptSet = this.headers[i][1];
+ if(this.headers[i][0].toLowerCase() == 'content-type')
+ contentTypeSet = this.headers[i][1];
+ request.setRequestHeader(REST.Encoding.encodeHeaderName(this.headers[i][0]),
+ REST.Encoding.encodeHeaderValue(this.headers[i][1]));
+ }
+ if(!acceptSet)
+ request.setRequestHeader('Accept', this.acceptHeader);
+ REST.log("Got form params: "+this.formParameters.length);
+ // see if we're sending an entity or a form
+ if(this.entity && (this.formParameters.length > 0 || this.forms.length > 0))
+ throw "Cannot have both an entity and form parameters";
+ // form
+ if(this.formParameters.length > 0 || this.forms.length > 0){
+ if(contentTypeSet && contentTypeSet != "application/x-www-form-urlencoded")
+ throw "The ContentType that was set by header value ("+contentTypeSet+") is incompatible with form parameters";
+ if(this.contentTypeHeader && this.contentTypeHeader != "application/x-www-form-urlencoded")
+ throw "The ContentType that was set with setContentType ("+this.contentTypeHeader+") is incompatible with form parameters";
+ contentTypeSet = "application/x-www-form-urlencoded";
+ request.setRequestHeader('Content-Type', contentTypeSet);
+ }else if(this.entity && !contentTypeSet && this.contentTypeHeader){
+ // entity
+ contentTypeSet = this.contentTypeHeader;
+ request.setRequestHeader('Content-Type', this.contentTypeHeader);
+ }
+ // we use this flag to work around buggy browsers
+ var gotReadyStateChangeEvent = false;
+ if(callback){
+ request.onreadystatechange = function() {
+ gotReadyStateChangeEvent = true;
+ REST.log("Got readystatechange");
+ REST._complete(this, callback);
+ };
+ }
+ var data = this.entity;
+ if(this.entity){
+ if(this.entity instanceof Element){
+ if(!contentTypeSet || REST._isXMLMIME(contentTypeSet))
+ data = REST.serialiseXML(this.entity);
+ }else if(this.entity instanceof Document){
+ if(!contentTypeSet || REST._isXMLMIME(contentTypeSet))
+ data = this.entity;
+ }else if(this.entity instanceof Object){
+ if(!contentTypeSet || REST._isJSONMIME(contentTypeSet))
+ data = JSON.stringify(this.entity);
+ }
+ }else if(this.formParameters.length > 0){
+ data = '';
+ for(var i=0;i<this.formParameters.length;i++){
+ if(i > 0)
+ data += "&";
+ data += REST.Encoding.encodeFormNameOrValue(this.formParameters[i][0]);
+ data += "=" + REST.Encoding.encodeFormNameOrValue(this.formParameters[i][1]);
+ }
+ } else if (this.forms.length > 0) {
+ data = '';
+ for (var i = 0; i < this.forms.length; i++) {
+ if (i > 0)
+ data += "&";
+ var obj = this.forms[i][1];
+ var key = REST.getKeys(obj)[0];
+ data += REST.Encoding.encodeFormNameOrValue(key);
+ data += "=" + REST.Encoding.encodeFormNameOrValue(obj[key]);
+ }
+ }
+ REST.log("Content-Type set to "+contentTypeSet);
+ REST.log("Entity set to "+data);
+ request.send(data);
+ // now if the browser did not follow the specs and did not fire the events while synchronous,
+ // handle it manually
+ if(!this.async && !gotReadyStateChangeEvent && callback){
+ REST.log("Working around browser readystatechange bug");
+ REST._complete(request, callback);
+ }
+
+ if (REST.debug == true) { REST.lastRequest = request; }
+
+ if (REST.antiBrowserCache == true && request.status != 304) {
+ var _cachedHeaders = {
+ "Etag":request.getResponseHeader('Etag'),
+ "Last-Modified":request.getResponseHeader('Last-Modified'),
+ "entity":request.responseText
+ };
+
+ var signature = REST._generate_cache_signature(url);
+ REST._remove_deprecated_cache_signature(signature);
+ REST._addToArray(REST.cacheHeaders, signature, _cachedHeaders);
+ }
+ },
+ setAccepts : function(acceptHeader){
+ REST.log("setAccepts("+acceptHeader+")");
+ this.acceptHeader = acceptHeader;
+ },
+ setCredentials : function(username, password){
+ this.password = password;
+ this.username = username;
+ },
+ setEntity : function(entity){
+ REST.log("setEntity("+entity+")");
+ this.entity = entity;
+ },
+ setContentType : function(contentType){
+ REST.log("setContentType("+contentType+")");
+ this.contentTypeHeader = contentType;
+ },
+ setURI : function(uri){
+ REST.log("setURI("+uri+")");
+ this.uri = uri;
+ },
+ setMethod : function(method){
+ REST.log("setMethod("+method+")");
+ this.method = method;
+ },
+ setAsync : function(async){
+ REST.log("setAsync("+async+")");
+ this.async = async;
+ },
+ addCookie : function(name, value){
+ REST.log("addCookie("+name+"="+value+")");
+ REST._addToArray(this.cookies, name, value);
+ },
+ addQueryParameter : function(name, value){
+ REST.log("addQueryParameter("+name+"="+value+")");
+ REST._addToArray(this.queryParameters, name, value);
+ },
+ addMatrixParameter : function(name, value){
+ REST.log("addMatrixParameter("+name+"="+value+")");
+ REST._addToArray(this.matrixParameters, name, value);
+ },
+ addFormParameter : function(name, value){
+ REST.log("addFormParameter("+name+"="+value+")");
+ REST._addToArray(this.formParameters, name, value);
+ },
+ addForm : function(name, value){
+ REST.log("addForm("+name+"="+value+")");
+ REST._addToArray(this.forms, name, value);
+ },
+ addHeader : function(name, value){
+ REST.log("addHeader("+name+"="+value+")");
+ REST._addToArray(this.headers, name, value);
+ }
+};
+
+REST.log = function (string) {
+ if (REST.loglevel > 0)
+ print(string);
+};
+
+REST._addToArray = function (array, name, value) {
+ if (value instanceof Array) {
+ for (var i = 0; i < value.length; i++) {
+ array.push([name, value[i]]);
+ }
+ } else {
+ array.push([name, value]);
+ }
+};
+
+REST._generate_cache_signature = function (url) {
+ return url.replace(/\?resteasy_jsapi_anti_cache=\d+/, '');
+};
+
+REST._remove_deprecated_cache_signature = function (signature) {
+ for (idx in REST.cacheHeaders) {
+ var _signature = REST.cacheHeaders[idx][0];
+ if (signature == _signature) {
+ REST.cacheHeaders.splice(idx, 1);
+ }
+ }
+
+};
+
+REST._get_cache_signature = function (signature) {
+ for (idx in REST.cacheHeaders) {
+ var _signature = REST.cacheHeaders[idx][0];
+ if (signature == _signature) {
+ return REST.cacheHeaders[idx];
+ }
+ }
+ return null;
+};
+
+REST._complete = function(request, callback){
+ REST.log("Request ready state: "+request.readyState);
+ if(request.readyState == 4) {
+ var entity;
+ REST.log("Request status: "+request.status);
+ REST.log("Request response: "+request.responseText);
+ if(request.status >= 200 && request.status < 300){
+ request.onreadystatechange = null;
+ var contentType = request.getResponseHeader("Content-Type");
+ if(contentType != null){
+ if(REST._isXMLMIME(contentType))
+ entity = request.responseXML;
+ else if(REST._isJSONMIME(contentType))
+ entity = JSON.parse(request.responseText);
+ else
+ entity = request.responseText;
+ }else
+ entity = request.responseText;
+ }
+
+ if (request.status == 304) {
+ entity = REST._get_cache_signature(REST._generate_cache_signature(request.url))[1]['entity'];
+ }
+ REST.log("Calling callback with: "+entity);
+ callback(request.status, request, entity);
+ }
+}
+
+REST._isXMLMIME = function(contentType){
+ return contentType == "text/xml"
+ || contentType == "application/xml"
+ || (contentType.indexOf("application/") == 0
+ && contentType.lastIndexOf("+xml") == (contentType.length - 4));
+}
+
+REST._isJSONMIME = function(contentType){
+ return contentType == "application/json"
+ || (contentType.indexOf("application/") == 0
+ && contentType.lastIndexOf("+json") == (contentType.length - 5));
+}
+
+/* Encoding */
+
+REST.Encoding = {};
+
+REST.Encoding.hash = function(a){
+ var ret = {};
+ for(var i=0;i<a.length;i++)
+ ret[a[i]] = 1;
+ return ret;
+}
+
+//
+// rules
+
+REST.Encoding.Alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
+
+REST.Encoding.Numeric = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
+
+REST.Encoding.AlphaNum = [].concat(REST.Encoding.Alpha, REST.Encoding.Numeric);
+
+REST.Encoding.AlphaNumHash = REST.Encoding.hash(REST.Encoding.AlphaNum);
+
+/**
+ * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ */
+REST.Encoding.Unreserved = [].concat(REST.Encoding.AlphaNum, ['-', '.', '_', '~']);
+
+/**
+ * gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
+ */
+REST.Encoding.GenDelims = [':', '/', '?', '#', '[', ']', '@'];
+
+/**
+ * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
+ */
+REST.Encoding.SubDelims = ['!','$','&','\'','(', ')', '*','+',',',';','='];
+
+/**
+ * reserved = gen-delims | sub-delims
+ */
+REST.Encoding.Reserved = [].concat(REST.Encoding.GenDelims, REST.Encoding.SubDelims);
+
+/**
+ * pchar = unreserved | escaped | sub-delims | ":" | "@"
+ *
+ * Note: we don't allow escaped here since we will escape it ourselves, so we don't want to allow them in the
+ * unescaped sequences
+ */
+REST.Encoding.PChar = [].concat(REST.Encoding.Unreserved, REST.Encoding.SubDelims, [':', '@']);
+
+/**
+ * path_segment = pchar <without> ";"
+ */
+REST.Encoding.PathSegmentHash = REST.Encoding.hash(REST.Encoding.PChar);
+delete REST.Encoding.PathSegmentHash[";"];
+
+/**
+ * path_param_name = pchar <without> ";" | "="
+ */
+REST.Encoding.PathParamHash = REST.Encoding.hash(REST.Encoding.PChar);
+delete REST.Encoding.PathParamHash[";"];
+delete REST.Encoding.PathParamHash["="];
+
+/**
+ * path_param_value = pchar <without> ";"
+ */
+REST.Encoding.PathParamValueHash = REST.Encoding.hash(REST.Encoding.PChar);
+delete REST.Encoding.PathParamValueHash[";"];
+
+/**
+ * query = pchar / "/" / "?"
+ */
+REST.Encoding.QueryHash = REST.Encoding.hash([].concat(REST.Encoding.PChar, ['/', '?']));
+// deviate from the RFC to disallow separators such as "=", "@" and the famous "+" which is treated as a space
+// when decoding
+delete REST.Encoding.QueryHash["="];
+delete REST.Encoding.QueryHash["&"];
+delete REST.Encoding.QueryHash["+"];
+
+/**
+ * fragment = pchar / "/" / "?"
+ */
+REST.Encoding.FragmentHash = REST.Encoding.hash([].concat(REST.Encoding.PChar, ['/', '?']));
+
+// HTTP
+
+REST.Encoding.HTTPSeparators = ["(" , ")" , "<" , ">" , "@"
+ , "," , ";" , ":" , "\\" , "\""
+ , "/" , "[" , "]" , "?" , "="
+ , "{" , "}" , ' ' , '\t'];
+
+// This should also hold the CTLs but we never need them
+REST.Encoding.HTTPChar = [];
+(function(){
+ for(var i=32;i<127;i++)
+ REST.Encoding.HTTPChar.push(String.fromCharCode(i));
+})()
+
+// CHAR - separators
+REST.Encoding.HTTPToken = REST.Encoding.hash(REST.Encoding.HTTPChar);
+(function(){
+ for(var i=0;i<REST.Encoding.HTTPSeparators.length;i++)
+ delete REST.Encoding.HTTPToken[REST.Encoding.HTTPSeparators[i]];
+})()
+
+//
+// functions
+
+//see http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
+//and http://www.apps.ietf.org/rfc/rfc1738.html#page-4
+REST.Encoding.encodeFormNameOrValue = function (val){
+ return REST.Encoding.encodeValue(val, REST.Encoding.AlphaNumHash, true);
+};
+
+
+//see http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
+REST.Encoding.encodeHeaderName = function (val){
+ // token+ from http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2
+
+ // There is no way to encode a header name. it is either a valid token or invalid and the
+ // XMLHttpRequest will fail (http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method)
+ // What we could do here is throw if the value is invalid
+ return val;
+}
+
+//see http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
+REST.Encoding.encodeHeaderValue = function (val){
+ // *TEXT or combinations of token, separators, and quoted-string from http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2
+ // FIXME: implement me. Stef has given up, since it involves latin1, quoted strings, MIME encoding (http://www.ietf.org/rfc/rfc2047.txt)
+ // which mentions a limit on encoded value of 75 chars, which should be split into several lines. This is mad.
+ return val;
+}
+
+// see http://www.ietf.org/rfc/rfc3986.txt
+REST.Encoding.encodeQueryParamNameOrValue = function (val){
+ return REST.Encoding.encodeValue(val, REST.Encoding.QueryHash);
+}
+
+//see http://www.ietf.org/rfc/rfc3986.txt
+REST.Encoding.encodePathSegment = function (val){
+ return REST.Encoding.encodeValue(val, REST.Encoding.PathSegmentHash);
+}
+
+//see http://www.ietf.org/rfc/rfc3986.txt
+REST.Encoding.encodePathParamName = function (val){
+ return REST.Encoding.encodeValue(val, REST.Encoding.PathParamHash);
+}
+
+//see http://www.ietf.org/rfc/rfc3986.txt
+REST.Encoding.encodePathParamValue = function (val){
+ return REST.Encoding.encodeValue(val, REST.Encoding.PathParamValueHash);
+}
+
+REST.Encoding.encodeValue = function (val, allowed, form){
+ if(typeof val != "string"){
+ REST.log("val is not a string");
+ return val;
+ }
+ if(val.length == 0){
+ REST.log("empty string");
+ return val;
+ }
+ var ret = '';
+ for(var i=0;i<val.length;i++){
+ var first = val[i];
+ if(allowed[first] == 1){
+ REST.log("char allowed: "+first);
+ ret = ret.concat(first);
+ }else if(form && (first == ' ' || first == '\n')){
+ // special rules for application/x-www-form-urlencoded
+ if(first == ' ')
+ ret += '+';
+ else
+ ret += '%0D%0A';
+ }else{
+ // See http://www.faqs.org/rfcs/rfc2781.html 2.2
+
+ // switch to codepoint
+ first = val.charCodeAt(i);
+ // utf-16 pair?
+ if(first < 0xD800 || first > 0xDFFF){
+ // just a single utf-16 char
+ ret = ret.concat(REST.Encoding.percentUTF8(first));
+ }else{
+ if(first > 0xDBFF || i+1 >= val.length)
+ throw "Invalid UTF-16 value: " + val;
+ var second = val.charCodeAt(++i);
+ if(second < 0xDC00 || second > 0xDFFF)
+ throw "Invalid UTF-16 value: " + val;
+ // char = 10 lower bits of first shifted left + 10 lower bits of second
+ var c = ((first & 0x3FF) << 10) | (second & 0x3FF);
+ // and add this
+ c += 0x10000;
+ // char is now 32 bit unicode
+ ret = ret.concat(REST.Encoding.percentUTF8(c));
+ }
+ }
+ }
+ return ret;
+}
+
+// see http://tools.ietf.org/html/rfc3629
+REST.Encoding.percentUTF8 = function(c){
+ if(c < 0x80)
+ return REST.Encoding.percentByte(c);
+ if(c < 0x800){
+ var first = 0xC0 | ((c & 0x7C0) >> 6);
+ var second = 0x80 | (c & 0x3F);
+ return REST.Encoding.percentByte(first, second);
+ }
+ if(c < 0x10000){
+ var first = 0xE0 | ((c >> 12) & 0xF);
+ var second = 0x80 | ((c >> 6) & 0x3F);
+ var third = 0x80 | (c & 0x3F);
+ return REST.Encoding.percentByte(first, second, third);
+ }
+ if(c < 0x110000){
+ var first = 0xF0 | ((c >> 18) & 0x7);
+ var second = 0x80 | ((c >> 12) & 0x3F);
+ var third = 0x80 | ((c >> 6) & 0x3F);
+ var fourth = 0x80 | (c & 0x3F);
+ return REST.Encoding.percentByte(first, second, third, fourth);
+ }
+ throw "Invalid character for UTF-8: "+c;
+}
+
+REST.Encoding.percentByte = function(){
+ var ret = '';
+ for(var i=0;i<arguments.length;i++){
+ var b = arguments[i];
+ if (b >= 0 && b <= 15)
+ ret += "%0" + b.toString(16);
+ else
+ ret += "%" + b.toString(16);
+ }
+ return ret;
+}
+
+REST.serialiseXML = function(node){
+ if (typeof XMLSerializer != "undefined")
+ return (new XMLSerializer()).serializeToString(node) ;
+ else if (node.xml) return node.xml;
+ else throw "XML.serialize is not supported or can't serialize " + node;
+}
diff --git a/manager/src/main/java/org/openremote/manager/client/ManagerActivityMapper.java b/manager/src/main/java/org/openremote/manager/client/ManagerActivityMapper.java
index ebeccd17f..87caf6c0a 100644
--- a/manager/src/main/java/org/openremote/manager/client/ManagerActivityMapper.java
+++ b/manager/src/main/java/org/openremote/manager/client/ManagerActivityMapper.java
@@ -24,8 +24,10 @@ import com.google.inject.Inject;
import com.google.inject.Provider;
import org.openremote.manager.client.admin.overview.AdminOverviewActivity;
import org.openremote.manager.client.admin.overview.AdminOverviewPlace;
+import org.openremote.manager.client.admin.realms.AdminRealmActivity;
import org.openremote.manager.client.admin.realms.AdminRealmsActivity;
import org.openremote.manager.client.admin.realms.AdminRealmPlace;
+import org.openremote.manager.client.admin.realms.AdminRealmsPlace;
import org.openremote.manager.client.admin.users.AdminUsersActivity;
import org.openremote.manager.client.admin.users.AdminUsersPlace;
import org.openremote.manager.client.assets.AssetDetailActivity;
@@ -58,6 +60,7 @@ public class ManagerActivityMapper implements AppActivityMapper {
protected final Provider<FlowsActivity> flowsActivityProvider;
protected final Provider<AdminOverviewActivity> adminOverviewActivityProvider;
protected final Provider<AdminRealmsActivity> adminRealmsActivityProvider;
+ protected final Provider<AdminRealmActivity> adminRealmActivityProvider;
protected final Provider<AdminUsersActivity> adminUsersActivityProvider;
protected final Provider<UserAccountActivity> userProfileActivityProvider;
@@ -70,6 +73,7 @@ public class ManagerActivityMapper implements AppActivityMapper {
Provider<FlowsActivity> flowsActivityProvider,
Provider<AdminOverviewActivity> adminOverviewActivityProvider,
Provider<AdminRealmsActivity> adminRealmsActivityProvider,
+ Provider<AdminRealmActivity> adminRealmActivityProvider,
Provider<AdminUsersActivity> adminUsersActivityProvider,
Provider<UserAccountActivity> userProfileActivityProvider) {
this.securityService = securityService;
@@ -80,6 +84,7 @@ public class ManagerActivityMapper implements AppActivityMapper {
this.flowsActivityProvider = flowsActivityProvider;
this.adminOverviewActivityProvider = adminOverviewActivityProvider;
this.adminRealmsActivityProvider = adminRealmsActivityProvider;
+ this.adminRealmActivityProvider = adminRealmActivityProvider;
this.adminUsersActivityProvider = adminUsersActivityProvider;
this.userProfileActivityProvider = userProfileActivityProvider;
}
@@ -98,8 +103,11 @@ public class ManagerActivityMapper implements AppActivityMapper {
if (place instanceof AdminOverviewPlace) {
return adminOverviewActivityProvider.get().init(securityService, (AdminOverviewPlace) place);
}
+ if (place instanceof AdminRealmsPlace) {
+ return adminRealmsActivityProvider.get().init(securityService, (AdminRealmsPlace) place);
+ }
if (place instanceof AdminRealmPlace) {
- return adminRealmsActivityProvider.get().init(securityService, (AdminRealmPlace) place);
+ return adminRealmActivityProvider.get().init(securityService, (AdminRealmPlace) place);
}
if (place instanceof AdminUsersPlace) {
return adminUsersActivityProvider.get().init(securityService, (AdminUsersPlace) place);
diff --git a/manager/src/main/java/org/openremote/manager/client/ManagerHistoryMapper.java b/manager/src/main/java/org/openremote/manager/client/ManagerHistoryMapper.java
index 824c55c92..374b3ca35 100644
--- a/manager/src/main/java/org/openremote/manager/client/ManagerHistoryMapper.java
+++ b/manager/src/main/java/org/openremote/manager/client/ManagerHistoryMapper.java
@@ -23,6 +23,7 @@ import com.google.gwt.place.shared.PlaceHistoryMapper;
import com.google.gwt.place.shared.WithTokenizers;
import org.openremote.manager.client.admin.overview.AdminOverviewPlace;
import org.openremote.manager.client.admin.realms.AdminRealmPlace;
+import org.openremote.manager.client.admin.realms.AdminRealmsPlace;
import org.openremote.manager.client.admin.users.AdminUsersPlace;
import org.openremote.manager.client.assets.AssetsPlace;
import org.openremote.manager.client.flows.FlowsPlace;
@@ -35,6 +36,7 @@ import org.openremote.manager.client.user.UserAccountPlace;
MapPlace.Tokenizer.class,
FlowsPlace.Tokenizer.class,
AdminOverviewPlace.Tokenizer.class,
+ AdminRealmsPlace.Tokenizer.class,
AdminRealmPlace.Tokenizer.class,
AdminUsersPlace.Tokenizer.class,
UserAccountPlace.Tokenizer.class
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/AdminModule.java b/manager/src/main/java/org/openremote/manager/client/admin/AdminModule.java
index 447754105..906be0ddf 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/AdminModule.java
+++ b/manager/src/main/java/org/openremote/manager/client/admin/AdminModule.java
@@ -28,9 +28,7 @@ import org.openremote.manager.client.admin.navigation.AdminNavigationPresenter;
import org.openremote.manager.client.admin.overview.AdminOverview;
import org.openremote.manager.client.admin.overview.AdminOverviewActivity;
import org.openremote.manager.client.admin.overview.AdminOverviewImpl;
-import org.openremote.manager.client.admin.realms.AdminRealms;
-import org.openremote.manager.client.admin.realms.AdminRealmsActivity;
-import org.openremote.manager.client.admin.realms.AdminRealmsImpl;
+import org.openremote.manager.client.admin.realms.*;
import org.openremote.manager.client.admin.users.AdminUsers;
import org.openremote.manager.client.admin.users.AdminUsersActivity;
import org.openremote.manager.client.admin.users.AdminUsersImpl;
@@ -47,6 +45,8 @@ public class AdminModule extends AbstractGinModule {
bind(AdminOverviewActivity.class);
bind(AdminRealms.class).to(AdminRealmsImpl.class).in(Singleton.class);
bind(AdminRealmsActivity.class);
+ bind(AdminRealm.class).to(AdminRealmImpl.class).in(Singleton.class);
+ bind(AdminRealmActivity.class);
bind(AdminUsers.class).to(AdminUsersImpl.class).in(Singleton.class);
bind(AdminUsersActivity.class);
}
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/RealmMapper.java b/manager/src/main/java/org/openremote/manager/client/admin/RealmMapper.java
new file mode 100644
index 000000000..2d494c9b6
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/client/admin/RealmMapper.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2016, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.client.admin;
+
+import com.github.nmorel.gwtjackson.client.ObjectMapper;
+import org.keycloak.representations.idm.RealmRepresentation;
+
+public interface RealmMapper extends ObjectMapper<RealmRepresentation> {
+}
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/navigation/AdminNavigationImpl.java b/manager/src/main/java/org/openremote/manager/client/admin/navigation/AdminNavigationImpl.java
index 855b5e0ff..0de5e1f9f 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/navigation/AdminNavigationImpl.java
+++ b/manager/src/main/java/org/openremote/manager/client/admin/navigation/AdminNavigationImpl.java
@@ -25,9 +25,10 @@ import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
+import org.openremote.manager.client.admin.AdminPlace;
import org.openremote.manager.client.admin.realms.AdminRealmPlace;
+import org.openremote.manager.client.admin.realms.AdminRealmsPlace;
import org.openremote.manager.client.admin.users.AdminUsersPlace;
-import org.openremote.manager.client.admin.AdminPlace;
import org.openremote.manager.client.widget.Hyperlink;
import javax.inject.Inject;
@@ -76,7 +77,9 @@ public class AdminNavigationImpl extends Composite implements AdminNavigation {
realmsLink.removeStyleName("active");
usersLink.removeStyleName("active");
- if (adminPlace instanceof AdminRealmPlace) {
+ if (adminPlace instanceof AdminRealmsPlace) {
+ realmsLink.addStyleName("active");
+ } else if (adminPlace instanceof AdminRealmPlace) {
realmsLink.addStyleName("active");
} else if (adminPlace instanceof AdminUsersPlace) {
usersLink.addStyleName("active");
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/navigation/AdminNavigationPresenter.java b/manager/src/main/java/org/openremote/manager/client/admin/navigation/AdminNavigationPresenter.java
index c743df009..d5429a05d 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/navigation/AdminNavigationPresenter.java
+++ b/manager/src/main/java/org/openremote/manager/client/admin/navigation/AdminNavigationPresenter.java
@@ -24,6 +24,7 @@ import org.openremote.manager.client.ManagerHistoryMapper;
import org.openremote.manager.client.admin.AdminPlace;
import org.openremote.manager.client.admin.overview.AdminOverviewPlace;
import org.openremote.manager.client.admin.realms.AdminRealmPlace;
+import org.openremote.manager.client.admin.realms.AdminRealmsPlace;
import org.openremote.manager.client.admin.users.AdminUsersPlace;
public class AdminNavigationPresenter implements AdminNavigation.Presenter {
@@ -52,7 +53,7 @@ public class AdminNavigationPresenter implements AdminNavigation.Presenter {
@Override
public String getAdminRealmsPlaceToken(String realm) {
- return managerHistoryMapper.getToken(new AdminRealmPlace(realm));
+ return managerHistoryMapper.getToken(new AdminRealmsPlace(realm));
}
@Override
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealm.java b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealm.java
new file mode 100644
index 000000000..5058d5371
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealm.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2016, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.client.admin.realms;
+
+import org.keycloak.representations.idm.RealmRepresentation;
+import org.openremote.manager.client.admin.AdminContent;
+
+public interface AdminRealm extends AdminContent {
+
+ interface Presenter {
+
+ void createRealm(RealmRepresentation realm);
+
+ void updateRealm(RealmRepresentation realm);
+
+ void deleteRealm(RealmRepresentation realm);
+ }
+
+ void setPresenter(Presenter presenter);
+
+ void setRealm(RealmRepresentation realm);
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmActivity.java b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmActivity.java
new file mode 100644
index 000000000..4fe28fc16
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmActivity.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2016, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.client.admin.realms;
+
+import com.google.gwt.place.shared.PlaceController;
+import com.google.gwt.user.client.ui.AcceptsOneWidget;
+import org.keycloak.representations.idm.RealmRepresentation;
+import org.openremote.manager.client.admin.AbstractAdminActivity;
+import org.openremote.manager.client.admin.AdminView;
+import org.openremote.manager.client.admin.RealmMapper;
+import org.openremote.manager.client.admin.navigation.AdminNavigation;
+import org.openremote.manager.client.event.bus.EventBus;
+import org.openremote.manager.client.event.bus.EventRegistration;
+import org.openremote.manager.client.i18n.ManagerMessages;
+import org.openremote.manager.client.mvp.AppActivity;
+import org.openremote.manager.client.service.RequestService;
+import org.openremote.manager.shared.event.ui.ShowFailureEvent;
+import org.openremote.manager.shared.http.ObjectMapperCallback;
+import org.openremote.manager.shared.security.RealmsResource;
+
+import javax.inject.Inject;
+import java.util.Collection;
+import java.util.logging.Logger;
+
+public class AdminRealmActivity
+ extends AbstractAdminActivity<AdminRealmPlace, AdminRealm>
+ implements AdminRealm.Presenter {
+
+ private static final Logger LOG = Logger.getLogger(AdminRealmActivity.class.getName());
+
+ final protected ManagerMessages managerMessages;
+ final protected PlaceController placeController;
+ final protected EventBus eventBus;
+ final protected RequestService requestService;
+ final protected RealmsResource realmsResource;
+ final protected RealmMapper realmMapper;
+
+ protected String realmId;
+
+ @Inject
+ public AdminRealmActivity(AdminView adminView,
+ AdminNavigation.Presenter adminNavigationPresenter,
+ AdminRealm view,
+ ManagerMessages managerMessages,
+ PlaceController placeController,
+ EventBus eventBus,
+ RequestService requestService,
+ RealmsResource realmsResource,
+ RealmMapper realmMapper) {
+ super(adminView, adminNavigationPresenter, view);
+ this.managerMessages = managerMessages;
+ this.placeController = placeController;
+ this.eventBus = eventBus;
+ this.requestService = requestService;
+ this.realmsResource = realmsResource;
+ this.realmMapper = realmMapper;
+ }
+
+ @Override
+ protected String[] getRequiredRoles() {
+ return new String[]{"read:admin"};
+ }
+
+ @Override
+ protected AppActivity<AdminRealmPlace> init(AdminRealmPlace place) {
+ realmId = place.getRealmId();
+ return super.init(place);
+ }
+
+ @Override
+ public void start(AcceptsOneWidget container, EventBus eventBus, Collection<EventRegistration> registrations) {
+ super.start(container, eventBus, registrations);
+ adminContent.setPresenter(this);
+
+ if (realmId != null) {
+ loadRealm();
+ } else {
+ adminContent.setRealm(new RealmRepresentation());
+ }
+ }
+
+ @Override
+ public void createRealm(RealmRepresentation realm) {
+
+ }
+
+ @Override
+ public void updateRealm(RealmRepresentation realm) {
+
+ }
+
+ @Override
+ public void deleteRealm(RealmRepresentation realm) {
+
+ }
+
+ protected void loadRealm() {
+ realmsResource.getRealm(
+ requestService.createRequestParams(new ObjectMapperCallback<>(
+ realmMapper,
+ 200,
+ adminContent::setRealm,
+ ex -> eventBus.dispatch(new ShowFailureEvent(
+ managerMessages.failureLoadingResource(ex.getMessage()),
+ 10000
+ ))
+ )
+ ),
+ realmId
+ );
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmImpl.java b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmImpl.java
index 0e94fdbf3..5556d1355 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmImpl.java
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmImpl.java
@@ -24,17 +24,12 @@ import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.LabelElement;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
-import com.google.gwt.user.cellview.client.CellTable;
-import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy;
-import com.google.gwt.user.cellview.client.TextColumn;
-import com.google.gwt.user.cellview.client.TextHeader;
import com.google.gwt.user.client.ui.*;
import org.keycloak.representations.idm.RealmRepresentation;
import javax.inject.Inject;
-import java.util.Arrays;
-public class AdminRealmImpl extends Composite implements AdminRealms {
+public class AdminRealmImpl extends Composite implements AdminRealm {
interface UI extends UiBinder<HTMLPanel, AdminRealmImpl> {
}
@@ -43,11 +38,6 @@ public class AdminRealmImpl extends Composite implements AdminRealms {
Presenter presenter;
- @UiField
- LabelElement realmsListBoxLabel;
- @UiField
- ListBox realmsListBox;
-
@UiField
LabelElement realmNameInputLabel;
@UiField
@@ -61,36 +51,12 @@ public class AdminRealmImpl extends Composite implements AdminRealms {
@UiField
SimplePanel cellTableContainer;
- final CellTable<RealmRepresentation> realmTable = new CellTable<>();
+ protected RealmRepresentation realm;
@Inject
public AdminRealmImpl() {
initWidget(ui.createAndBindUi(this));
- cellTableContainer.add(realmTable);
- realmTable.setKeyboardSelectionPolicy(HasKeyboardSelectionPolicy.KeyboardSelectionPolicy.ENABLED);
-
- TextHeader textHeader = new TextHeader("headerTitle");
- textHeader.setHeaderStyleNames("my-style");
- TextColumn<RealmRepresentation> nameColumn = new TextColumn<RealmRepresentation>() {
- @Override
- public String getValue(RealmRepresentation realmRepresentation) {
- return realmRepresentation.getDisplayName();
- }
- };
- realmTable.addColumn(nameColumn, textHeader);
-
- TextColumn<RealmRepresentation> foo = new TextColumn<RealmRepresentation>() {
- @Override
- public String getValue(RealmRepresentation realmRepresentation) {
- return realmRepresentation.getRealm();
- }
- };
- realmTable.addColumn(foo, "Realm");
-
- realmsListBoxLabel.setHtmlFor(Document.get().createUniqueId());
- realmsListBox.getElement().setId(realmsListBoxLabel.getHtmlFor());
-
realmNameInputLabel.setHtmlFor(Document.get().createUniqueId());
realmNameInput.getElement().setId(realmNameInputLabel.getHtmlFor());
@@ -107,13 +73,9 @@ public class AdminRealmImpl extends Composite implements AdminRealms {
}
@Override
- public void setRealms(RealmRepresentation[] realms) {
- realmsListBox.clear();
- for (RealmRepresentation realm : realms) {
- realmsListBox.addItem(realm.getDisplayName());
- }
-
- realmTable.setRowData(0, Arrays.asList(realms));
-
+ public void setRealm(RealmRepresentation realm) {
+ this.realm = realm;
+ realmNameInput.setText(realm.getDisplayName());
}
+
}
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmImpl.ui.xml b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmImpl.ui.xml
index 63673a11e..56fc66a77 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmImpl.ui.xml
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmImpl.ui.xml
@@ -8,7 +8,9 @@
<g:HTMLPanel styleName="flex layout vertical">
- <div class="{widgetStyle.Headline1} {themeStyle.Headline1}">Manage Tenants</div>
+ <div class="{widgetStyle.Headline1} {themeStyle.Headline1}">
+ <g:Label text="{constants.editRealm}"/>
+ </div>
<div class="layout vertical {widgetStyle.Form} {themeStyle.Form}">
@@ -16,18 +18,7 @@
<div class="layout horizontal center {widgetStyle.FormGroup} {themeStyle.FormGroup}">
<div class="larger {widgetStyle.FormLabel} {themeStyle.FormLabel}">
- <label ui:field="realmsListBoxLabel">Select tenant</label>
- </div>
- <div class="{widgetStyle.FormField} {themeStyle.FormField}">
- <g:ListBox ui:field="realmsListBox"
- addStyleNames="{widgetStyle.FormControl} {themeStyle.FormControl} {widgetStyle.FormDropDown} {themeStyle.FormDropDown}"
- visibleItemCount="1"/>
- </div>
- </div>
-
- <div class="layout horizontal center {widgetStyle.FormGroup} {themeStyle.FormGroup}">
- <div class="larger {widgetStyle.FormLabel} {themeStyle.FormLabel}">
- <label ui:field="realmNameInputLabel">Tenant display name</label>
+ <label ui:field="realmNameInputLabel"><g:Label text="{constants.realmDisplayName}"/></label>
</div>
<div class="{widgetStyle.FormField} {themeStyle.FormField}">
<g:TextBox ui:field="realmNameInput"
@@ -37,11 +28,11 @@
<div class="layout horizontal center {widgetStyle.FormGroup} {themeStyle.FormGroup}">
<div class="larger {widgetStyle.FormLabel} {themeStyle.FormLabel}">
- <label ui:field="realmEnabledLabel">Enabled</label>
+ <label ui:field="realmEnabledLabel"><g:Label text="{constants.enabled}"/></label>
</div>
<div class="{widgetStyle.FormField} {themeStyle.FormField}">
<g:SimpleCheckBox ui:field="realmEnabledCheckBox"
- addStyleNames="{widgetStyle.FormControl} {themeStyle.FormControl} {widgetStyle.FormCheckBox} {themeStyle.FormCheckBox}"/>
+ addStyleNames="{widgetStyle.FormControl} {themeStyle.FormControl} {widgetStyle.FormCheckBox} {themeStyle.FormCheckBox}"/>
</div>
</div>
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmPlace.java b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmPlace.java
index c8d858a2f..479827357 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmPlace.java
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmPlace.java
@@ -25,14 +25,18 @@ import org.openremote.manager.client.admin.AdminPlace;
public class AdminRealmPlace extends AdminPlace {
- final String realm;
+ final String realmId;
- public AdminRealmPlace(String realm) {
- this.realm = realm;
+ public AdminRealmPlace() {
+ realmId = null;
}
- public String getRealm() {
- return realm;
+ public AdminRealmPlace(String realmId) {
+ this.realmId = realmId;
+ }
+
+ public String getRealmId() {
+ return realmId;
}
@Prefix("realm")
@@ -40,12 +44,12 @@ public class AdminRealmPlace extends AdminPlace {
@Override
public AdminRealmPlace getPlace(String token) {
- return new AdminRealmPlace(token);
+ return new AdminRealmPlace(token != null && token.length() > 0 ? token : null);
}
@Override
public String getToken(AdminRealmPlace place) {
- return place.getRealm();
+ return place.getRealmId() != null ? place.getRealmId() : "";
}
}
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealms.java b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealms.java
index bd376c884..87d5034ff 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealms.java
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealms.java
@@ -28,6 +28,8 @@ public interface AdminRealms extends AdminContent {
void onRealmSelected(RealmRepresentation realm);
+ void createRealm();
+
}
void setPresenter(Presenter presenter);
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsActivity.java b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsActivity.java
index 2eb6b1aae..7785ecbc7 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsActivity.java
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsActivity.java
@@ -39,7 +39,7 @@ import java.util.Collection;
import java.util.logging.Logger;
public class AdminRealmsActivity
- extends AbstractAdminActivity<AdminRealmPlace, AdminRealms>
+ extends AbstractAdminActivity<AdminRealmsPlace, AdminRealms>
implements AdminRealms.Presenter {
private static final Logger LOG = Logger.getLogger(AdminRealmsActivity.class.getName());
@@ -82,7 +82,8 @@ public class AdminRealmsActivity
200,
adminContent::setRealms,
ex -> eventBus.dispatch(new ShowFailureEvent(
- managerMessages.failureLoadingResource(ex.getMessage())
+ managerMessages.failureLoadingResource(ex.getMessage()),
+ 10000
))
)
));
@@ -90,6 +91,11 @@ public class AdminRealmsActivity
@Override
public void onRealmSelected(RealmRepresentation realm) {
- placeController.goTo(new AdminRealmPlace(realm.getRealm()));
+ placeController.goTo(new AdminRealmPlace(realm.getId()));
+ }
+
+ @Override
+ public void createRealm() {
+ placeController.goTo(new AdminRealmPlace());
}
}
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsImpl.java b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsImpl.java
index 626deac7c..9e9ccc186 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsImpl.java
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsImpl.java
@@ -20,10 +20,13 @@
package org.openremote.manager.client.admin.realms;
import com.google.gwt.core.client.GWT;
+import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
+import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.*;
import org.keycloak.representations.idm.RealmRepresentation;
+import org.openremote.manager.client.admin.overview.AdminOverviewPlace;
import org.openremote.manager.client.i18n.ManagerConstants;
import org.openremote.manager.client.style.FormTableStyle;
import org.openremote.manager.client.widget.PushButton;
@@ -82,6 +85,11 @@ public class AdminRealmsImpl extends Composite implements AdminRealms {
realmsTable.setRowData(Arrays.asList(realms));
}
+ @UiHandler("createRealmButton")
+ void createRealmClicked(ClickEvent e) {
+ presenter.createRealm();
+ }
+
protected void setTestData() {
List<RealmRepresentation> testData = new ArrayList<>();
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsImpl.ui.xml b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsImpl.ui.xml
index 1e80b3b9b..28b2a14d7 100644
--- a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsImpl.ui.xml
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsImpl.ui.xml
@@ -22,7 +22,9 @@
<g:HTMLPanel styleName="flex layout vertical">
- <div class="{widgetStyle.Headline1} {themeStyle.Headline1}">Manage Tenants</div>
+ <div class="{widgetStyle.Headline1} {themeStyle.Headline1}">
+ <g:Label text="{constants.manageRealms}"/>
+ </div>
<div class="layout vertical {widgetStyle.Form} {themeStyle.Form}">
diff --git a/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsPlace.java b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsPlace.java
new file mode 100644
index 000000000..969dc972e
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/client/admin/realms/AdminRealmsPlace.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2016, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.manager.client.admin.realms;
+
+import com.google.gwt.place.shared.PlaceTokenizer;
+import com.google.gwt.place.shared.Prefix;
+import org.openremote.manager.client.admin.AdminPlace;
+
+public class AdminRealmsPlace extends AdminPlace {
+
+ final String realm;
+
+ public AdminRealmsPlace(String realm) {
+ this.realm = realm;
+ }
+
+ public String getRealm() {
+ return realm;
+ }
+
+ @Prefix("realms")
+ public static class Tokenizer implements PlaceTokenizer<AdminRealmsPlace> {
+
+ @Override
+ public AdminRealmsPlace getPlace(String token) {
+ return new AdminRealmsPlace(token);
+ }
+
+ @Override
+ public String getToken(AdminRealmsPlace place) {
+ return place.getRealm();
+ }
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/client/i18n/ManagerConstants.java b/manager/src/main/java/org/openremote/manager/client/i18n/ManagerConstants.java
index 4eddfc04e..04f5a2108 100644
--- a/manager/src/main/java/org/openremote/manager/client/i18n/ManagerConstants.java
+++ b/manager/src/main/java/org/openremote/manager/client/i18n/ManagerConstants.java
@@ -58,4 +58,8 @@ public interface ManagerConstants extends Constants {
String realm();
String enabled();
+
+ String editRealm();
+
+ String realmDisplayName();
}
diff --git a/manager/src/main/java/org/openremote/manager/client/i18n/ManagerConstants.properties b/manager/src/main/java/org/openremote/manager/client/i18n/ManagerConstants.properties
index 016fd5c48..3f1a9010e 100644
--- a/manager/src/main/java/org/openremote/manager/client/i18n/ManagerConstants.properties
+++ b/manager/src/main/java/org/openremote/manager/client/i18n/ManagerConstants.properties
@@ -14,4 +14,6 @@ overview = Overview
createRealm = New tenant
realmName = Tenant name
realm = Realm
-enabled = Enabled
\ No newline at end of file
+enabled = Enabled
+editRealm = Edit tenant
+realmDisplayName = Tenant name
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java b/manager/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java
index bd8f468db..0de4b85fc 100644
--- a/manager/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/server/assets/AssetsResourceImpl.java
@@ -22,7 +22,6 @@ package org.openremote.manager.server.assets;
import elemental.json.Json;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
-import org.jboss.resteasy.annotations.Form;
import org.openremote.container.web.WebResource;
import org.openremote.manager.shared.assets.AssetsResource;
import org.openremote.manager.shared.http.RequestParams;
@@ -45,33 +44,33 @@ public class AssetsResourceImpl extends WebResource implements AssetsResource {
}
@Override
- public JsonArray getEntities(@Form RequestParams requestParams, @Form EntityListParams entityListParams) {
+ public JsonArray getEntities(RequestParams requestParams, EntityListParams entityListParams) {
return assetsService.getContextBroker().getEntities(entityListParams);
}
@Override
- public void postEntity(@Form RequestParams requestParams, Entity entity) {
+ public void postEntity(RequestParams requestParams, Entity entity) {
checkSuccessResponse(assetsService.getContextBroker().postEntity(entity));
}
@Override
- public JsonObject getEntity(@Form RequestParams requestParams, String entityId, @Form EntityParams entityParams) {
+ public JsonObject getEntity(RequestParams requestParams, String entityId, EntityParams entityParams) {
return assetsService.getContextBroker().getEntity(entityId, entityParams);
}
@Override
- public void deleteEntity(@Form RequestParams requestParams, String entityId) {
+ public void deleteEntity(RequestParams requestParams, String entityId) {
checkSuccessResponse(assetsService.getContextBroker().deleteEntity(entityId));
}
@Override
- public void putEntity(@Form RequestParams requestParams, String entityId, Entity entity) {
+ public void putEntity(RequestParams requestParams, String entityId, Entity entity) {
entity = new Entity(fixForUpdate(entity.getJsonObject()));
checkSuccessResponse(assetsService.getContextBroker().putEntity(entityId, entity));
}
@Override
- public void patchEntity(@Form RequestParams requestParams, String entityId, Entity entity) {
+ public void patchEntity(RequestParams requestParams, String entityId, Entity entity) {
entity = new Entity(fixForUpdate(entity.getJsonObject()));
checkSuccessResponse(assetsService.getContextBroker().patchEntity(entityId, entity));
}
diff --git a/manager/src/main/java/org/openremote/manager/server/security/RealmsResourceImpl.java b/manager/src/main/java/org/openremote/manager/server/security/RealmsResourceImpl.java
index 2feaf9867..2f1d591ae 100644
--- a/manager/src/main/java/org/openremote/manager/server/security/RealmsResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/server/security/RealmsResourceImpl.java
@@ -19,7 +19,6 @@
*/
package org.openremote.manager.server.security;
-import org.jboss.resteasy.annotations.Form;
import org.keycloak.representations.idm.RealmRepresentation;
import org.openremote.container.web.WebResource;
import org.openremote.manager.shared.http.RequestParams;
@@ -39,8 +38,13 @@ public class RealmsResourceImpl extends WebResource implements RealmsResource {
}
@Override
- public RealmRepresentation[] getRealms(@Form RequestParams requestParams) {
+ public RealmRepresentation[] getRealms(RequestParams requestParams) {
List<RealmRepresentation> realms = managerIdentityService.getRealms(requestParams).findAll();
return realms.toArray(new RealmRepresentation[realms.size()]);
}
+
+ @Override
+ public RealmRepresentation getRealm(RequestParams requestParams, String realmId) {
+ return managerIdentityService.getRealms(requestParams).realm(realmId).toRepresentation();
+ }
}
diff --git a/manager/src/main/java/org/openremote/manager/shared/assets/AssetsResource.java b/manager/src/main/java/org/openremote/manager/shared/assets/AssetsResource.java
index ca81ed35e..44e63b55d 100644
--- a/manager/src/main/java/org/openremote/manager/shared/assets/AssetsResource.java
+++ b/manager/src/main/java/org/openremote/manager/shared/assets/AssetsResource.java
@@ -22,7 +22,6 @@ package org.openremote.manager.shared.assets;
import elemental.json.JsonArray;
import elemental.json.JsonObject;
import jsinterop.annotations.JsType;
-import org.jboss.resteasy.annotations.Form;
import org.openremote.manager.shared.http.PATCH;
import org.openremote.manager.shared.http.RequestParams;
import org.openremote.manager.shared.http.SuccessStatusCode;
@@ -32,7 +31,6 @@ import org.openremote.manager.shared.ngsi.params.EntityParams;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.*;
-import javax.ws.rs.core.Response;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
@@ -48,40 +46,40 @@ public interface AssetsResource {
@Produces(APPLICATION_JSON)
@SuccessStatusCode(200)
@RolesAllowed({"read:assets"})
- JsonArray getEntities(@Form RequestParams requestParams, @Form EntityListParams entityListParams);
+ JsonArray getEntities(@BeanParam RequestParams requestParams, @BeanParam EntityListParams entityListParams);
@POST
@Path("entities")
@Consumes(APPLICATION_JSON)
@SuccessStatusCode(201)
@RolesAllowed({"write:assets"})
- void postEntity(@Form RequestParams requestParams, Entity entity);
+ void postEntity(@BeanParam RequestParams requestParams, Entity entity);
@GET
@Path("entities/{entityId}")
@Produces(APPLICATION_JSON)
@SuccessStatusCode(200)
@RolesAllowed({"read:assets"})
- JsonObject getEntity(@Form RequestParams requestParams, @PathParam("entityId") String entityId, @Form EntityParams entityParams);
+ JsonObject getEntity(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId, @BeanParam EntityParams entityParams);
@DELETE
@Path("entities/{entityId}")
@SuccessStatusCode(204)
@RolesAllowed({"write:assets"})
- void deleteEntity(@Form RequestParams requestParams, @PathParam("entityId") String entityId);
+ void deleteEntity(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId);
@PUT
@Path("entities/{entityId}")
@Consumes(APPLICATION_JSON)
@SuccessStatusCode(204)
@RolesAllowed({"write:assets"})
- void putEntity(@Form RequestParams requestParams, @PathParam("entityId") String entityId, Entity entity);
+ void putEntity(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId, Entity entity);
@PATCH
@Path("entities/{entityId}")
@Consumes(APPLICATION_JSON)
@SuccessStatusCode(204)
@RolesAllowed({"write:assets"})
- void patchEntity(@Form RequestParams requestParams, @PathParam("entityId") String entityId, Entity entity);
+ void patchEntity(@BeanParam RequestParams requestParams, @PathParam("entityId") String entityId, Entity entity);
}
diff --git a/manager/src/main/java/org/openremote/manager/shared/http/AbstractCallback.java b/manager/src/main/java/org/openremote/manager/shared/http/AbstractCallback.java
index e4c97148c..71d0da046 100644
--- a/manager/src/main/java/org/openremote/manager/shared/http/AbstractCallback.java
+++ b/manager/src/main/java/org/openremote/manager/shared/http/AbstractCallback.java
@@ -46,7 +46,10 @@ public abstract class AbstractCallback<T> implements Callback<T> {
return;
}
if (expectedStatusCode != ANY_STATUS_CODE && responseCode != expectedStatusCode) {
- onFailure.accept(new RequestParams.Failure(responseCode, "Expected status code: " + expectedStatusCode));
+ onFailure.accept(new RequestParams.Failure(
+ responseCode,
+ "Expected response status code " + expectedStatusCode + " but received " + responseCode + ".")
+ );
return;
}
onSuccess.accept(readMessageBody(entity));
diff --git a/manager/src/main/java/org/openremote/manager/shared/map/MapResource.java b/manager/src/main/java/org/openremote/manager/shared/map/MapResource.java
index d11adbcb8..9a8dcd99e 100644
--- a/manager/src/main/java/org/openremote/manager/shared/map/MapResource.java
+++ b/manager/src/main/java/org/openremote/manager/shared/map/MapResource.java
@@ -21,15 +21,11 @@ package org.openremote.manager.shared.map;
import elemental.json.JsonObject;
import jsinterop.annotations.JsType;
-import org.jboss.resteasy.annotations.Form;
import org.openremote.manager.shared.http.RequestParams;
import org.openremote.manager.shared.http.SuccessStatusCode;
import javax.annotation.security.RolesAllowed;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
+import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@Path("map")
@@ -40,7 +36,7 @@ public interface MapResource {
@Produces(MediaType.APPLICATION_JSON)
@SuccessStatusCode(200)
@RolesAllowed({"read:map"})
- JsonObject getSettings(@Form RequestParams requestParams);
+ JsonObject getSettings(@BeanParam RequestParams requestParams);
@GET
@Produces("application/vnd.mapbox-vector-tile")
diff --git a/manager/src/main/java/org/openremote/manager/shared/security/RealmsResource.java b/manager/src/main/java/org/openremote/manager/shared/security/RealmsResource.java
index c6857cdb5..2e6750a09 100644
--- a/manager/src/main/java/org/openremote/manager/shared/security/RealmsResource.java
+++ b/manager/src/main/java/org/openremote/manager/shared/security/RealmsResource.java
@@ -20,13 +20,10 @@
package org.openremote.manager.shared.security;
import jsinterop.annotations.JsType;
-import org.jboss.resteasy.annotations.Form;
import org.keycloak.representations.idm.RealmRepresentation;
import org.openremote.manager.shared.http.RequestParams;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
+import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
@Path("realm")
@@ -35,6 +32,11 @@ public interface RealmsResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
- RealmRepresentation[] getRealms(@Form RequestParams requestParams);
+ RealmRepresentation[] getRealms(@BeanParam RequestParams requestParams);
+
+ @GET
+ @Path("{realmId}")
+ @Produces(MediaType.APPLICATION_JSON)
+ RealmRepresentation getRealm(@BeanParam RequestParams requestParams, @PathParam("realmId") String realmId);
}